From ef0b1c37dc71b6fadfe24c1f3e741ffc7a2de10f Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Sun, 4 Oct 2026 15:38:02 -0500 Subject: [PATCH] serve: live Claude chat feed endpoints (/v1/chat/claude) Proxy tail/cat of the Spark chat feed on each request; no hub disk writes. Co-Authored-By: Claude Fable 5.1 --- .crumb | 12 +++--- NOTES.md | 6 +++ README.md | 1 + src/.crumb | 8 ++-- src/main.rs | 114 ++++++++++++++++++++++++++++++++++++++++++++-------- 5 files changed, 115 insertions(+), 26 deletions(-) diff --git a/.crumb b/.crumb index d32b72a..7cb8939 100644 --- a/.crumb +++ b/.crumb @@ -19,21 +19,21 @@ "purpose": "Directory scripts. Purpose not yet described by a human." }, { - "digest": "20c1764543006c90f64ad969c0beb862ff4d0d156473bcf77286188fd1dc93dc", + "digest": "6fec168497c47fb9a79824aa8ecee67eda1513bbe82ce63996e336473be2edf8", "last_commit": "d910ecb", "name": "src", "purpose": "Directory src. Purpose not yet described by a human." } ], - "children_root": "sha256:2370aabb1416026f33dae6c6c8894d5d5a4d49273fb6eb98f82838bac1aca5f0", - "compiled_at": "2026-10-04T18:13:52Z", + "children_root": "sha256:2744808a6e52aeb290efba03e11d2f22fe4c862e855a1d6dd797b7d5c6a252e9", + "compiled_at": "2026-10-04T20:38:02Z", "compiler": "crumb-compile/1", - "digest": "sha256:7c7ec083e888be8cd56d251e7441e4b7d2c0e0ef1d75d9f9197d119354194b50", + "digest": "sha256:cbf98a95a4f58a082c642b10d45ecfae1ece37ea4a27d70335809657bd090204", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 10, - "generated_at_commit": "7c5d85b6e146aab45dddc3e6a4839e58f5f926bb", - "source_tree": "sha256:d560f2122cd474b22c97119ea9788af07a49425f5298d8c7053352ed045d2ef3" + "generated_at_commit": "6191d9bf53be78428bd3f5a8181b2d8eb5af3abd", + "source_tree": "sha256:1b298e3b4e3c3ae6b173724dd2b2d971ddf947a08df1a15affc9f15c8d5e994e" }, "owner_lane": "", "seed": { diff --git a/NOTES.md b/NOTES.md index e1ea416..11d1fe2 100644 --- a/NOTES.md +++ b/NOTES.md @@ -37,3 +37,9 @@ tiny_http 0.12 pulls rustls 0.20 (older); acceptable for read-only data, UNVERIF - `GET /v1/exposure` (Bearer token) serves the file; `/health` gains `"exposure":"ok|changed|unknown"` (unknown if missing, invalid or older than 1 h). - First run found TCP 53 open on the public IP (DNS answered a recursive query). Source UNVERIFIED: hairpin from inside the LAN may hit the router itself rather than the hub. UDP 3478 not confirmed open by nmap (open|filtered), UNVERIFIED. - Registered in pi-register as `exposure-watch` (health: last-run.txt younger than 20 min). + +## Live Claude chat feed (added 2026-10-04) +- Why: Drake wants the whole Claude chat stream visible to Muse on his MacBook and phone. +- `GET /v1/chat/claude` serves `/home/drakestapleton/shared/agents/claude-chat.txt`, `GET /v1/chat/claude.jsonl` serves `claude-chat.jsonl` (Bearer token). `?lines=N` (default 500, clamped 1..50000) runs `tail -n N` on the Spark; `?all=1` runs `cat`. Only constant paths and a parsed integer reach the remote shell. +- Proxied live over ssh on each request. NOTHING is written or cached on the hub, because its root disk is a fragile USB stick. Spark unreachable gives 502 `{"error":"spark unreachable"}`. +- Each request blocks the single-threaded server for the ssh round trip (up to ~5 s connect timeout per host); `?all=1` on a large file is a big response. UNVERIFIED under load. diff --git a/README.md b/README.md index 6a54550..3c5b9ac 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ A small Rust service: it collects one JSON line of readings from the Spark every - `GET /health`: liveness plus an `exposure` field (`ok|changed|unknown`). - `GET /v1/readings/current`, `GET /v1/readings/history?hours=N` (default 24, max 720). - `GET /v1/status`, `GET /v1/results`, `GET /v1/exposure`. +- `GET /v1/chat/claude?lines=N` (text, last N lines, default 500, max 50000; `?all=1` for the whole file) and `GET /v1/chat/claude.jsonl` (same, raw JSON lines, `application/x-ndjson`): the live Claude chat feed, proxied from the Spark on every request (no hub disk writes). 502 `{"error":"spark unreachable"}` if the Spark cannot be reached. - All `/v1/*` routes need `Authorization: Bearer `. The token and the TLS key live on the hub only (`/etc/readings-window/`), never in this repository. ## Commands diff --git a/src/.crumb b/src/.crumb index 500b7bd..5dc4609 100644 --- a/src/.crumb +++ b/src/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-04T15:56:29Z", + "compiled_at": "2026-10-04T20:38:02Z", "compiler": "crumb-compile/1", - "digest": "sha256:20c1764543006c90f64ad969c0beb862ff4d0d156473bcf77286188fd1dc93dc", + "digest": "sha256:6fec168497c47fb9a79824aa8ecee67eda1513bbe82ce63996e336473be2edf8", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 1, - "generated_at_commit": "d910ecbfcd8224bc8520bdeda3ecc172fe69d6f5", - "source_tree": "sha256:dfce961ebb6da04e541efbae2eb756e13f53b2091db5e47db34b4533969a33bd" + "generated_at_commit": "6191d9bf53be78428bd3f5a8181b2d8eb5af3abd", + "source_tree": "sha256:0abf3a5d75ea5c394ccd88672eafc37ef9572b8dbe13c79ff0e173bca258ca88" }, "owner_lane": "", "seed": { diff --git a/src/main.rs b/src/main.rs index bbeb5e7..1ae6c62 100644 --- a/src/main.rs +++ b/src/main.rs @@ -187,23 +187,69 @@ fn last_line() -> Option { fs::read_to_string(HISTORY).ok()?.lines().rev().find(|l| ts_of(l).is_some()).map(String::from) } -fn json_resp(code: u16, body: String) -> Response>> { +const CHAT_TXT: &str = "/home/drakestapleton/shared/agents/claude-chat.txt"; +const CHAT_JSONL: &str = "/home/drakestapleton/shared/agents/claude-chat.jsonl"; +const CHAT_DEFAULT_LINES: u64 = 500; +const CHAT_MAX_LINES: u64 = 50000; +const JSON_TYPE: &str = "application/json"; +const TEXT_TYPE: &str = "text/plain; charset=utf-8"; +const NDJSON_TYPE: &str = "application/x-ndjson"; + +/// Number of lines asked for in `?lines=N`: default 500, clamped to 1..=50000. +fn clamp_lines(q: Option<&str>) -> u64 { + let n = q + .and_then(|q| q.split('&').find_map(|kv| kv.strip_prefix("lines="))) + .and_then(|v| v.parse::().ok()) + .unwrap_or(CHAT_DEFAULT_LINES); + n.clamp(1, CHAT_MAX_LINES) +} + +/// Remote command for a chat feed: only a constant path and a validated integer reach the shell. +fn chat_command(path: &'static str, q: Option<&str>) -> String { + if q.is_some_and(|q| q.split('&').any(|kv| kv == "all=1")) { + format!("cat {path}") + } else { + format!("tail -n {} {path}", clamp_lines(q)) + } +} + +/// Chat feed paths: (file on the Spark, content type). +fn chat_route(path: &str) -> Option<(&'static str, &'static str)> { + match path { + "/v1/chat/claude" => Some((CHAT_TXT, TEXT_TYPE)), + "/v1/chat/claude.jsonl" => Some((CHAT_JSONL, NDJSON_TYPE)), + _ => None, + } +} + +/// Proxy a chat feed live from the Spark; nothing is written or cached on the hub. +fn chat_feed(path: &'static str, ctype: &'static str, q: Option<&str>) -> (u16, String, &'static str) { + match fetch(&chat_command(path, q)) { + Ok(o) => (200, String::from_utf8_lossy(&o.stdout).into_owned(), ctype), + Err(e) => { + eprintln!("readings-window: chat feed {path}: {e}"); + (502, r#"{"error":"spark unreachable"}"#.into(), JSON_TYPE) + } + } +} + +fn resp(code: u16, ctype: &str, body: String) -> Response>> { Response::from_string(body) .with_status_code(code) - .with_header(Header::from_bytes("Content-Type", "application/json").unwrap()) + .with_header(Header::from_bytes("Content-Type", ctype).unwrap()) } -fn handle(method: &Method, url: &str, auth: Option<&str>, token: &str) -> (u16, String) { +fn handle(method: &Method, url: &str, auth: Option<&str>, token: &str) -> (u16, String, &'static str) { let (path, query) = match url.split_once('?') { Some((p, q)) => (p, Some(q)), None => (url, None), }; - let known = matches!(path, "/health" | "/v1/readings/current" | "/v1/readings/history" | "/v1/status" | "/v1/results" | "/v1/exposure"); + let known = matches!(path, "/health" | "/v1/readings/current" | "/v1/readings/history" | "/v1/status" | "/v1/results" | "/v1/exposure" | "/v1/chat/claude" | "/v1/chat/claude.jsonl"); if !known { - return (404, r#"{"error":"not found"}"#.into()); + return (404, r#"{"error":"not found"}"#.into(), JSON_TYPE); } if *method != Method::Get { - return (405, r#"{"error":"method not allowed"}"#.into()); + return (405, r#"{"error":"method not allowed"}"#.into(), JSON_TYPE); } if path == "/health" { let ex = exposure_state(fs::read_to_string(EXPOSURE).ok().as_deref(), now()); @@ -211,30 +257,33 @@ fn handle(method: &Method, url: &str, auth: Option<&str>, token: &str) -> (u16, Some(t) => now().saturating_sub(t).to_string(), None => "null".into(), }; - return (200, format!(r#"{{"status":"ok","last_reading_age_s":{age},"exposure":"{ex}"}}"#)); + return (200, format!(r#"{{"status":"ok","last_reading_age_s":{age},"exposure":"{ex}"}}"#), JSON_TYPE); } if !auth_ok(auth, token) { - return (401, r#"{"error":"unauthorized"}"#.into()); + return (401, r#"{"error":"unauthorized"}"#.into(), JSON_TYPE); } if path == "/v1/exposure" { - return (200, feed_body(EXPOSURE, validate_exposure, EXPOSURE_DEFAULT)); + return (200, feed_body(EXPOSURE, validate_exposure, EXPOSURE_DEFAULT), JSON_TYPE); } if path == "/v1/status" { - return (200, feed_body(STATUS, validate_status, STATUS_DEFAULT)); + return (200, feed_body(STATUS, validate_status, STATUS_DEFAULT), JSON_TYPE); } if path == "/v1/results" { - return (200, feed_body(RESULTS, validate_results, RESULTS_DEFAULT)); + return (200, feed_body(RESULTS, validate_results, RESULTS_DEFAULT), JSON_TYPE); + } + if let Some((file, ctype)) = chat_route(path) { + return chat_feed(file, ctype, query); } if path == "/v1/readings/current" { return match last_line() { - Some(l) => (200, l), - None => (503, r#"{"error":"no readings yet"}"#.into()), + Some(l) => (200, l, JSON_TYPE), + None => (503, r#"{"error":"no readings yet"}"#.into(), JSON_TYPE), }; } let cutoff = now().saturating_sub(clamp_hours(query) * 3600); let all = fs::read_to_string(HISTORY).unwrap_or_default(); let rows = filter_since(all.lines(), cutoff); - (200, format!("[{}]", rows.join(","))) + (200, format!("[{}]", rows.join(",")), JSON_TYPE) } fn serve() -> Result<(), String> { @@ -249,8 +298,8 @@ fn serve() -> Result<(), String> { let server = Server::https("0.0.0.0:9443", ssl).map_err(|e| format!("bind: {e}"))?; for req in server.incoming_requests() { let auth = req.headers().iter().find(|h| h.field.equiv("Authorization")).map(|h| h.value.to_string()); - let (code, body) = handle(req.method(), req.url(), auth.as_deref(), &token); - let _ = req.respond(json_resp(code, body)); + let (code, body, ctype) = handle(req.method(), req.url(), auth.as_deref(), &token); + let _ = req.respond(resp(code, ctype, body)); } Ok(()) } @@ -337,6 +386,39 @@ mod tests { assert!(validate_results("[]").is_err()); } #[test] + fn lines_clamp() { + assert_eq!(clamp_lines(None), 500); + assert_eq!(clamp_lines(Some("lines=0")), 1); + assert_eq!(clamp_lines(Some("lines=1")), 1); + assert_eq!(clamp_lines(Some("lines=500")), 500); + assert_eq!(clamp_lines(Some("lines=60000")), 50000); + assert_eq!(clamp_lines(Some("lines=abc")), 500); + assert_eq!(clamp_lines(Some("lines=1;rm -rf /")), 500); + assert_eq!(clamp_lines(Some("lines=-5")), 500); + } + #[test] + fn chat_commands() { + assert_eq!(chat_command(CHAT_TXT, None), "tail -n 500 /home/drakestapleton/shared/agents/claude-chat.txt"); + assert_eq!(chat_command(CHAT_TXT, Some("lines=60000")), "tail -n 50000 /home/drakestapleton/shared/agents/claude-chat.txt"); + assert_eq!(chat_command(CHAT_TXT, Some("all=1")), "cat /home/drakestapleton/shared/agents/claude-chat.txt"); + assert_eq!(chat_command(CHAT_JSONL, Some("lines=7&all=1")), "cat /home/drakestapleton/shared/agents/claude-chat.jsonl"); + assert_eq!(chat_command(CHAT_JSONL, Some("lines=7")), "tail -n 7 /home/drakestapleton/shared/agents/claude-chat.jsonl"); + assert_eq!(chat_command(CHAT_JSONL, Some("all=1;id")), "tail -n 500 /home/drakestapleton/shared/agents/claude-chat.jsonl"); + } + #[test] + fn chat_routes_known_and_typed() { + assert_eq!(chat_route("/v1/chat/claude"), Some((CHAT_TXT, "text/plain; charset=utf-8"))); + assert_eq!(chat_route("/v1/chat/claude.jsonl"), Some((CHAT_JSONL, "application/x-ndjson"))); + assert_eq!(chat_route("/v1/chat/other"), None); + let tok = "s3cret"; + for p in ["/v1/chat/claude", "/v1/chat/claude.jsonl"] { + assert_eq!(handle(&Method::Get, p, None, tok).0, 401); + assert_eq!(handle(&Method::Get, &format!("{p}?lines=5"), Some("Bearer wrong"), tok).0, 401); + assert_eq!(handle(&Method::Post, p, None, tok).0, 405); + } + assert_eq!(handle(&Method::Get, "/v1/chat/claude.txt", None, tok).0, 404); + } + #[test] fn feed_defaults() { assert_eq!(feed_body("/nonexistent/x", validate_status, STATUS_DEFAULT), STATUS_DEFAULT); assert_eq!(feed_body("/nonexistent/x", validate_results, RESULTS_DEFAULT), RESULTS_DEFAULT);