Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
Harden the host: stricter checks, safer shutdown and agent downloads
leepokaid10d83f2a750
diff --git a/.github/workflows/host.yml b/.github/workflows/host.ymlindex f52b3d9e..fd8d7de0 100644--- a/.github/workflows/host.yml+++ b/.github/workflows/host.yml@@ -21,11 +21,12 @@ jobs:- uses: actions/checkout@v4- uses: dtolnay/rust-toolchain@stablewith:- components: clippy+ components: clippy, rustfmt- uses: Swatinem/rust-cache@v2with:workspaces: host- - run: cargo clippy -- -D warnings+ - run: cargo fmt --check+ - run: cargo clippy --all-targets -- -D warnings- run: cargo testlinux-app:diff --git a/CLAUDE.md b/CLAUDE.mdindex 6074aa97..bf6e251c 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -9,7 +9,8 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess- Use structured concurrency (`async/await`, `TaskGroup`) over Combine- Use `sending`, `nonisolated`, `@MainActor` correctly per Swift 6 rules- Avoid `@unchecked Sendable` — prefer proper `Sendable` conformance-- Host is Rust 2024 edition; keep `cargo clippy -- -D warnings` clean+- Host is Rust 2024 edition and follows the `rust-skills` rules (`~/.agents/skills/rust-skills`). Lints live in `host/Cargo.toml` (`[lints]`: default groups + pedantic, `unwrap_used`); CI runs `cargo fmt --check` and `cargo clippy --all-targets -- -D warnings`+- Host conventions: no `unwrap()` outside tests (`expect("why this can't fail")` for true invariants); lock std mutexes with `LockExt::locked()` (poison-tolerant); enums, not strings, for states and modes (`BotStatus`, `Permission`, `EntryKind`, `AlertKind`); `tracing` with structured fields (`error = format!("{e:#}")` keeps the context chain); blocking fs/process work goes through `spawn_blocking`; registry JSON is untrusted (paths are validated)## Architecturediff --git a/host/Cargo.toml b/host/Cargo.tomlindex 963b0e50..4c050a5c 100644--- a/host/Cargo.toml+++ b/host/Cargo.toml@@ -2,6 +2,11 @@name = "codync-host"version = "2.0.0"edition = "2024"+# let-chains (`if let … && let …`) need 1.88.+rust-version = "1.88"+description = "Runs your coding-agent bots and serves the Codync apps"+license = "MIT"+repository = "https://github.com/leepokai/Codync"[dependencies]anyhow = "1.0.104"@@ -22,3 +27,33 @@ tokio-stream = { version = "0.1.19", features = ["sync"] }tracing = "0.1.44"tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }uuid = { version = "1.26.1", features = ["v4"] }++# rust-skills lint-* rules: all default groups plus pedantic, with the+# library-oriented pedantic lints turned off for this binary crate.+[lints.rust]+unsafe_op_in_unsafe_fn = "deny"+unused_qualifications = "warn"++[lints.clippy]+correctness = { level = "deny", priority = -1 }+suspicious = { level = "warn", priority = -1 }+style = { level = "warn", priority = -1 }+complexity = { level = "warn", priority = -1 }+perf = { level = "warn", priority = -1 }+pedantic = { level = "warn", priority = -1 }+missing_errors_doc = "allow"+missing_panics_doc = "allow"+must_use_candidate = "allow"+module_name_repetitions = "allow"+too_many_lines = "allow"+unwrap_used = "warn"+dbg_macro = "warn"+todo = "warn"+undocumented_unsafe_blocks = "warn"++# perf-release-profile / opt-lto-release. Unwinding stays on: a panic in one+# bot's task must not take down the whole daemon.+[profile.release]+lto = "thin"+codegen-units = 1+strip = truediff --git a/host/clippy.toml b/host/clippy.tomlnew file mode 100644index 00000000..1a248a62--- /dev/null+++ b/host/clippy.toml@@ -0,0 +1,4 @@+# Tests may unwrap: a panic there is the failure report.+allow-unwrap-in-tests = true+allow-expect-in-tests = true+doc-valid-idents = ["SQLite", "OpenCode", "JSON-RPC", ".."]diff --git a/host/rustfmt.toml b/host/rustfmt.tomlnew file mode 100644index 00000000..c775577e--- /dev/null+++ b/host/rustfmt.toml@@ -0,0 +1,2 @@+max_width = 120+use_small_heuristics = "Max"diff --git a/host/src/acp.rs b/host/src/acp.rsindex 57df2454..da3a1279 100644--- a/host/src/acp.rs+++ b/host/src/acp.rs@@ -2,7 +2,8 @@//! process's stdio. Updates are kept as `serde_json::Value` on purpose so a//! newer adapter adding a variant never breaks parsing.-use anyhow::{Result, anyhow, bail};+use crate::LockExt;+use anyhow::{Context, Result, bail};use serde_json::{Value, json};use std::collections::{HashMap, VecDeque};use std::process::Stdio;@@ -10,7 +11,10 @@ use std::sync::Arc;use std::sync::atomic::{AtomicI64, Ordering};use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};use tokio::process::{Child, ChildStdin, Command};-use tokio::sync::{Mutex, mpsc, oneshot};+use tokio::sync::{mpsc, oneshot};++/// stderr lines kept to explain a crash.+const STDERR_TAIL_LINES: usize = 12;pub enum Incoming {Notification { method: String, params: Value },@@ -18,13 +22,14 @@ pub enum Incoming {Closed { stderr_tail: String },}-type Pending = Arc<Mutex<HashMap<i64, oneshot::Sender<Result<Value, Value>>>>>;+/// In-flight requests by JSON-RPC id. A std mutex: it's never held across an `.await`.+type Pending = Arc<std::sync::Mutex<HashMap<i64, oneshot::Sender<Result<Value, Value>>>>>;pub struct Acp {- stdin: Mutex<ChildStdin>,+ stdin: tokio::sync::Mutex<ChildStdin>,next_id: AtomicI64,pending: Pending,- child: Mutex<Child>,+ child: tokio::sync::Mutex<Child>,}impl Acp {@@ -39,22 +44,25 @@ impl Acp {.stderr(Stdio::piped()).kill_on_drop(true).spawn()- .map_err(|e| anyhow!("failed to start `{command}`: {e}"))?;- let stdin = child.stdin.take().unwrap();- let stdout = child.stdout.take().unwrap();- let stderr = child.stderr.take().unwrap();+ .with_context(|| format!("starting `{command}`"))?;+ let stdin = child.stdin.take().expect("stdin is piped");+ let stdout = child.stdout.take().expect("stdout is piped");+ let stderr = child.stderr.take().expect("stderr is piped");+ // Deliberately unbounded: `session/load` replays a whole history as notifications+ // *before* its response, while the bot is still awaiting that response. A bounded+ // queue would stall this reader, and with it the response — a deadlock.let (tx, rx) = mpsc::unbounded_channel();- let pending: Pending = Default::default();+ let pending = Pending::default();- let tail = Arc::new(std::sync::Mutex::new(VecDeque::<String>::new()));+ let tail = Arc::new(std::sync::Mutex::new(VecDeque::<String>::with_capacity(STDERR_TAIL_LINES)));{let tail = tail.clone();tokio::spawn(async move {let mut lines = BufReader::new(stderr).lines();while let Ok(Some(line)) = lines.next_line().await {- tracing::debug!(target: "agent", "{line}");- let mut t = tail.lock().unwrap();- if t.len() == 12 {+ tracing::debug!(target: "agent", stderr = %line);+ let mut t = tail.locked();+ if t.len() == STDERR_TAIL_LINES {t.pop_front();}t.push_back(line);@@ -67,7 +75,7 @@ impl Acp {let mut lines = BufReader::new(stdout).lines();while let Ok(Some(line)) = lines.next_line().await {let Ok(msg) = serde_json::from_str::<Value>(&line) else {- tracing::debug!(target: "agent", "non-json stdout: {line}");+ tracing::debug!(target: "agent", stdout = %line, "ignoring non-JSON output");continue;};let method = msg["method"].as_str().map(str::to_owned);@@ -80,7 +88,7 @@ impl Acp {}(None, Some(id)) => {if let Some(id) = id.as_i64()- && let Some(waiter) = pending.lock().await.remove(&id)+ && let Some(waiter) = pending.locked().remove(&id){let res = match msg.get("error") {Some(err) => Err(err.clone()),@@ -93,19 +101,19 @@ impl Acp {}}// Process gone: fail everyone still waiting.- for (_, w) in pending.lock().await.drain() {+ for (_, w) in pending.locked().drain() {let _ = w.send(Err(json!({"message": "agent process exited"})));}- let stderr_tail = tail.lock().unwrap().iter().cloned().collect::<Vec<_>>().join("\n");+ let stderr_tail = tail.locked().iter().cloned().collect::<Vec<_>>().join("\n");let _ = tx.send(Incoming::Closed { stderr_tail });});}let acp = Arc::new(Self {- stdin: Mutex::new(stdin),+ stdin: tokio::sync::Mutex::new(stdin),next_id: AtomicI64::new(1),pending,- child: Mutex::new(child),+ child: tokio::sync::Mutex::new(child),});Ok((acp, rx))}@@ -122,12 +130,12 @@ impl Acp {pub async fn request(&self, method: &str, params: Value) -> Result<Value> {let id = self.next_id.fetch_add(1, Ordering::Relaxed);let (tx, rx) = oneshot::channel();- self.pending.lock().await.insert(id, tx);+ self.pending.locked().insert(id, tx);self.write(json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})).await?;match rx.await {Ok(Ok(v)) => Ok(v),Ok(Err(e)) => {- let msg = e["message"].as_str().map(str::to_owned).unwrap_or_else(|| e.to_string());+ let msg = e["message"].as_str().map_or_else(|| e.to_string(), str::to_owned);match e["data"]["details"].as_str().or(e["data"].as_str()) {Some(d) => bail!("{msg} ({d})"),None => bail!("{msg}"),@@ -150,7 +158,12 @@ impl Acp {}pub async fn kill(&self) {- let _ = self.child.lock().await.kill().await;+ // Already exited is fine; anything else is worth a log line.+ if let Err(error) = self.child.lock().await.kill().await+ && error.kind() != std::io::ErrorKind::InvalidInput+ {+ tracing::debug!(%error, "couldn't kill agent process");+ }}}@@ -162,12 +175,9 @@ pub fn content_text(v: &Value) -> String {Some("text") => o.get("text").and_then(Value::as_str).unwrap_or_default().to_owned(),Some("content") => o.get("content").map(content_text).unwrap_or_default(),Some("resource_link") => o.get("uri").and_then(Value::as_str).unwrap_or_default().to_owned(),- Some("resource") => o- .get("resource")- .and_then(|r| r.get("text"))- .and_then(Value::as_str)- .unwrap_or_default()- .to_owned(),+ Some("resource") => {+ o.get("resource").and_then(|r| r.get("text")).and_then(Value::as_str).unwrap_or_default().to_owned()+ }_ => String::new(),},_ => String::new(),diff --git a/host/src/api.rs b/host/src/api.rsindex c1a3afea..31ee8013 100644--- a/host/src/api.rs+++ b/host/src/api.rs@@ -1,11 +1,12 @@//! HTTP API: `POST /api/<method>` commands + `GET /events` SSE.//! Auth: `Authorization: Bearer <token>` (or `?token=` for SSE).+use crate::LockExt;use crate::bot::Cmd;use crate::hub::Hub;-use crate::store::BotConfig;+use crate::store::{BotConfig, EntryKind};use crate::{backends, usage};-use anyhow::{Result, anyhow};+use anyhow::{Context, Result, anyhow, bail};use axum::extract::{Path, Query, State};use axum::http::{HeaderMap, StatusCode};use axum::response::sse::{Event, KeepAlive, Sse};@@ -21,6 +22,9 @@ use std::sync::atomic::Ordering;use std::time::Duration;use tokio_stream::wrappers::BroadcastStream;+/// Entries a fresh client receives per bot before paging with `history`.+const CATCH_UP_PER_BOT: i64 = 200;+pub fn router(hub: Arc<Hub>) -> Router {Router::new().route("/health", get(health))@@ -31,10 +35,7 @@ pub fn router(hub: Arc<Hub>) -> Router {}fn authorized(hub: &Hub, headers: &HeaderMap, query_token: Option<&str>) -> bool {- let header = headers- .get("authorization")- .and_then(|v| v.to_str().ok())- .and_then(|v| v.strip_prefix("Bearer "));+ let header = headers.get("authorization").and_then(|v| v.to_str().ok()).and_then(|v| v.strip_prefix("Bearer "));let given = header.or(query_token).unwrap_or_default();// Constant-time compare.given.len() == hub.token.len() && given.bytes().zip(hub.token.bytes()).fold(0u8, |acc, (a, b)| acc | (a ^ b)) == 0@@ -42,6 +43,18 @@ fn authorized(hub: &Hub, headers: &HeaderMap, query_token: Option<&str>) -> boolstruct ApiError(StatusCode, String);+/// `POST /api/<method>` with a method this host doesn't know (404, not 400).+#[derive(Debug)]+struct UnknownMethod;++impl std::fmt::Display for UnknownMethod {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str("unknown method")+ }+}++impl std::error::Error for UnknownMethod {}+impl IntoResponse for ApiError {fn into_response(self) -> Response {(self.0, Json(json!({"error": self.1}))).into_response()@@ -69,11 +82,12 @@ async fn command(if !authorized(&hub, &headers, None) {return Err(ApiError(StatusCode::UNAUTHORIZED, "invalid token".into()));}- let body = body.map(|b| b.0).unwrap_or(Value::Null);+ let body = body.map_or(Value::Null, |b| b.0);match dispatch(&hub, &method, body).await {Ok(v) => Ok(Json(v)),- Err(e) if e.to_string() == "unknown method" => Err(ApiError(StatusCode::NOT_FOUND, e.to_string())),- Err(e) => Err(ApiError(StatusCode::BAD_REQUEST, e.to_string())),+ Err(e) if e.is::<UnknownMethod>() => Err(ApiError(StatusCode::NOT_FOUND, e.to_string())),+ // `{:#}` keeps the context chain ("starting `npx …`: No such file or directory").+ Err(e) => Err(ApiError(StatusCode::BAD_REQUEST, format!("{e:#}"))),}}@@ -98,8 +112,8 @@ pub async fn dispatch(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Value> {"hostId": hub.host_id,"rev": hub.store.current_rev(),"bots": hub.bots_json(since)?,- "entries": hub.store.entries_since(since, 200)?,- "usage": hub.usage.lock().unwrap().clone(),+ "entries": hub.store.entries_since(since, CATCH_UP_PER_BOT)?,+ "usage": hub.usage.locked().clone(),})}"history" => {@@ -111,10 +125,10 @@ pub async fn dispatch(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Value> {"createBot" => {let mut b = b;b["id"] = "".into();- let cfg: BotConfig = serde_json::from_value(b).map_err(|e| anyhow!("invalid bot: {e}"))?;+ let cfg: BotConfig = serde_json::from_value(b).context("invalid bot")?;json!({"bot": hub.create_bot(cfg)?})}- "updateBot" => json!({"bot": hub.update_bot(b)?}),+ "updateBot" => json!({"bot": hub.update_bot(&b)?}),"deleteBot" => {hub.delete_bot(str_arg(&b, "botId")?)?;json!({})@@ -127,7 +141,7 @@ pub async fn dispatch(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Value> {let bot = str_arg(&b, "botId")?;let text = str_arg(&b, "text")?.trim();if text.is_empty() {- return Err(anyhow!("empty message"));+ bail!("empty message");}let nonce = b["clientNonce"].as_str().unwrap_or_default();if !nonce.is_empty()@@ -137,9 +151,13 @@ pub async fn dispatch(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Value> {}hub.store.bot(bot)?.filter(|r| !r.deleted).ok_or_else(|| anyhow!("unknown bot"))?;let turn = hub.store.max_turn(bot) + 1;- let e = hub.add_entry(bot, "user", turn, json!({"text": text, "clientNonce": nonce, "status": "queued"}))?;+ let e = hub+ .add_entry(bot, EntryKind::User, turn, &json!({"text": text, "clientNonce": nonce, "status": "queued"}))+ .ok_or_else(|| anyhow!("couldn't save the message"))?;hub.send_cmd(bot, Cmd::Send { entry_id: e.id.clone(), text: text.to_owned() })?;- let _ = hub.mark_read(bot);+ if let Err(error) = hub.mark_read(bot) {+ tracing::warn!(%error, bot, "couldn't mark bot read after send");+ }json!({"entry": e})}"stop" => {@@ -168,7 +186,7 @@ pub async fn dispatch(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Value> {"registerActivity" => {let bot = str_arg(&b, "botId")?.to_owned();let ticket = str_arg(&b, "ticket")?.to_owned();- let mut map = hub.activities.lock().unwrap();+ let mut map = hub.activities.locked();let list = map.entry(bot).or_default();if !list.contains(&ticket) {list.push(ticket);@@ -183,11 +201,16 @@ pub async fn dispatch(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Value> {if b["refresh"].as_bool().unwrap_or(false) {usage::refresh(hub).await;}- hub.usage.lock().unwrap().clone()+ serde_json::to_value(&*hub.usage.locked())?+ }+ "listDirs" => {+ let path = b["path"].as_str().map(std::path::PathBuf::from);+ tokio::task::spawn_blocking(move || list_dirs(path)).await??}- "listDirs" => list_dirs(b["path"].as_str())?,"pairing" => {- let urls = crate::service::addresses(hub.port);+ let port = hub.port;+ // Shells out to `tailscale`: keep it off the async workers.+ let urls = tokio::task::spawn_blocking(move || crate::service::addresses(port)).await?;let url = crate::service::pairing_url(&crate::service::host_name(), &hub.token, &urls);let svg = qrcode::QrCode::new(url.as_bytes())?.render::<qrcode::render::svg::Color>()@@ -196,15 +219,19 @@ pub async fn dispatch(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Value> {.build();json!({"pairingUrl": url, "urls": urls, "svg": svg})}- _ => return Err(anyhow!("unknown method")),+ _ => return Err(UnknownMethod.into()),})}-fn list_dirs(path: Option<&str>) -> Result<Value> {- let home = dirs::home_dir().ok_or_else(|| anyhow!("no home"))?;- let dir = path.map(std::path::PathBuf::from).unwrap_or(home);- let mut dirs: Vec<Value> = std::fs::read_dir(&dir)?- .filter_map(|e| e.ok())+/// Blocking (`std::fs`): call through `spawn_blocking`.+fn list_dirs(path: Option<std::path::PathBuf>) -> Result<Value> {+ let dir = match path {+ Some(p) => p,+ None => dirs::home_dir().ok_or_else(|| anyhow!("no home directory"))?,+ };+ let mut dirs: Vec<Value> = std::fs::read_dir(&dir)+ .with_context(|| format!("listing {}", dir.display()))?+ .filter_map(Result::ok).filter(|e| e.file_type().is_ok_and(|t| t.is_dir())).filter_map(|e| {let name = e.file_name().to_string_lossy().into_owned();@@ -231,13 +258,19 @@ struct EventsQuery {client: Option<String>,}-struct ClientGuard(Arc<Hub>, bool);+/// Counts a connected iOS client (pushes are held while one is connected) for as long as its stream lives.+struct IosClientGuard(Arc<Hub>);-impl Drop for ClientGuard {+impl IosClientGuard {+ fn new(hub: Arc<Hub>) -> Self {+ hub.ios_clients.fetch_add(1, Ordering::Relaxed);+ Self(hub)+ }+}++impl Drop for IosClientGuard {fn drop(&mut self) {- if self.1 {- self.0.ios_clients.fetch_sub(1, Ordering::Relaxed);- }+ self.0.ios_clients.fetch_sub(1, Ordering::Relaxed);}}@@ -257,18 +290,18 @@ async fn events(for bot in hub.bots_json(since).map_err(|e| ApiError(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))? {catch_up.push(json!({"type": "bot", "rev": bot["rev"], "bot": bot}));}- for e in hub.store.entries_since(since, 200).unwrap_or_default() {+ let entries = hub+ .store+ .entries_since(since, CATCH_UP_PER_BOT)+ .map_err(|e| ApiError(StatusCode::INTERNAL_SERVER_ERROR, format!("{e:#}")))?;+ for e in entries {catch_up.push(json!({"type": "entry", "rev": e.rev, "entry": e}));}catch_up.sort_by_key(|v| v["rev"].as_i64().unwrap_or(0));- let hello = json!({"type": "hello", "hostId": hub.host_id, "rev": hub.store.current_rev(), "usage": hub.usage.lock().unwrap().clone()});+ let hello = json!({"type": "hello", "hostId": hub.host_id, "rev": hub.store.current_rev(), "usage": hub.usage.locked().clone()});catch_up.insert(0, hello);- let is_ios = q.client.as_deref() == Some("ios");- if is_ios {- hub.ios_clients.fetch_add(1, Ordering::Relaxed);- }- let guard = Arc::new(ClientGuard(hub.clone(), is_ios));+ let guard = Arc::new((q.client.as_deref() == Some("ios")).then(|| IosClientGuard::new(hub.clone())));let head = stream::iter(catch_up.into_iter().map(|v| Ok(Event::default().data(v.to_string()))));let tail = live.filter_map(move |msg| {let _keep = guard.clone();diff --git a/host/src/backends.rs b/host/src/backends.rsindex 07704141..3e1acf71 100644--- a/host/src/backends.rs+++ b/host/src/backends.rs@@ -6,10 +6,11 @@//! each known CLI. Launching prefers the installed CLI's own ACP mode and falls//! back to the official ACP registry build (npx / uvx / downloaded binary).+use crate::LockExt;use crate::registry;use serde_json::{Value, json};use std::collections::HashSet;-use std::path::PathBuf;+use std::path::{Path, PathBuf};use std::sync::Mutex;use std::time::Duration;@@ -26,26 +27,166 @@ pub struct Harness {}pub const HARNESSES: &[Harness] = &[- Harness { id: "claude", name: "Claude Code", bins: &["claude"], local: None, registry: Some("claude-acp"), setup: "Install Claude Code and run `claude` once to sign in." },- Harness { id: "codex", name: "Codex", bins: &["codex"], local: None, registry: Some("codex-acp"), setup: "Install Codex CLI and run `codex login`." },- Harness { id: "cursor", name: "Cursor", bins: &["cursor-agent"], local: Some("{bin} acp"), registry: Some("cursor"), setup: "Install Cursor CLI (curl https://cursor.com/install -fsS | bash) and run `cursor-agent login`." },- Harness { id: "pi", name: "Pi", bins: &["pi"], local: None, registry: Some("pi-acp"), setup: "Install pi (npm install -g @mariozechner/pi-coding-agent) and sign in with `pi`." },- Harness { id: "opencode", name: "OpenCode", bins: &["opencode"], local: Some("{bin} acp"), registry: Some("opencode"), setup: "Install OpenCode (curl -fsSL https://opencode.ai/install | bash) and run `opencode auth login`." },- Harness { id: "grok", name: "Grok Build", bins: &["grok"], local: Some("{bin} agent stdio"), registry: Some("grok-build"), setup: "Install Grok Build (curl -fsSL https://x.ai/cli/install.sh | bash) and run `grok` once to sign in." },- Harness { id: "gemini", name: "Gemini CLI", bins: &["gemini"], local: Some("{bin} --acp"), registry: Some("gemini"), setup: "Install Gemini CLI (npm install -g @google/gemini-cli) and run `gemini` once to sign in." },- Harness { id: "copilot", name: "GitHub Copilot", bins: &["copilot"], local: Some("{bin} --acp --stdio"), registry: Some("github-copilot-cli"), setup: "Install Copilot CLI (npm install -g @github/copilot) and run `copilot` to sign in." },- Harness { id: "qwen", name: "Qwen Code", bins: &["qwen"], local: Some("{bin} --acp"), registry: Some("qwen-code"), setup: "Install Qwen Code (npm install -g @qwen-code/qwen-code) and sign in with `qwen`." },- Harness { id: "goose", name: "goose", bins: &["goose"], local: Some("{bin} acp"), registry: Some("goose"), setup: "Install goose and run `goose configure`." },- Harness { id: "kimi", name: "Kimi CLI", bins: &["kimi"], local: Some("{bin} acp"), registry: Some("kimi"), setup: "Install Kimi CLI and sign in with `kimi`." },- Harness { id: "droid", name: "Factory Droid", bins: &["droid"], local: Some("{bin} exec --output-format acp-daemon"), registry: Some("factory-droid"), setup: "Install Droid (curl -fsSL https://app.factory.ai/cli | sh) and sign in with `droid`." },- Harness { id: "amp", name: "Amp", bins: &["amp"], local: None, registry: Some("amp-acp"), setup: "Install Amp and sign in with `amp login`." },- Harness { id: "kilo", name: "Kilo", bins: &["kilo"], local: Some("{bin} acp"), registry: Some("kilo"), setup: "Install Kilo CLI (npm install -g @kilocode/cli) and sign in." },- Harness { id: "cline", name: "Cline", bins: &["cline"], local: Some("{bin} --acp"), registry: Some("cline"), setup: "Install Cline CLI (npm install -g cline) and sign in." },- Harness { id: "auggie", name: "Auggie", bins: &["auggie"], local: Some("{bin} --acp"), registry: Some("auggie"), setup: "Install Auggie (npm install -g @augmentcode/auggie) and run `auggie login`." },- Harness { id: "vibe", name: "Mistral Vibe", bins: &["vibe-acp", "vibe"], local: None, registry: Some("mistral-vibe"), setup: "Install Mistral Vibe and run `vibe` once to sign in." },- Harness { id: "kiro", name: "Kiro CLI", bins: &["kiro-cli"], local: Some("{bin} acp"), registry: None, setup: "Install Kiro CLI (curl -fsSL https://cli.kiro.dev/install | bash) and run `kiro-cli login`." },- Harness { id: "devin", name: "Devin", bins: &["devin"], local: Some("{bin} acp"), registry: Some("devin"), setup: "Install the Devin CLI and sign in." },- Harness { id: "qoder", name: "Qoder CLI", bins: &["qodercli"], local: Some("{bin} --acp"), registry: Some("qoder"), setup: "Install Qoder CLI and sign in." },+ Harness {+ id: "claude",+ name: "Claude Code",+ bins: &["claude"],+ local: None,+ registry: Some("claude-acp"),+ setup: "Install Claude Code and run `claude` once to sign in.",+ },+ Harness {+ id: "codex",+ name: "Codex",+ bins: &["codex"],+ local: None,+ registry: Some("codex-acp"),+ setup: "Install Codex CLI and run `codex login`.",+ },+ Harness {+ id: "cursor",+ name: "Cursor",+ bins: &["cursor-agent"],+ local: Some("{bin} acp"),+ registry: Some("cursor"),+ setup: "Install Cursor CLI (curl https://cursor.com/install -fsS | bash) and run `cursor-agent login`.",+ },+ Harness {+ id: "pi",+ name: "Pi",+ bins: &["pi"],+ local: None,+ registry: Some("pi-acp"),+ setup: "Install pi (npm install -g @mariozechner/pi-coding-agent) and sign in with `pi`.",+ },+ Harness {+ id: "opencode",+ name: "OpenCode",+ bins: &["opencode"],+ local: Some("{bin} acp"),+ registry: Some("opencode"),+ setup: "Install OpenCode (curl -fsSL https://opencode.ai/install | bash) and run `opencode auth login`.",+ },+ Harness {+ id: "grok",+ name: "Grok Build",+ bins: &["grok"],+ local: Some("{bin} agent stdio"),+ registry: Some("grok-build"),+ setup: "Install Grok Build (curl -fsSL https://x.ai/cli/install.sh | bash) and run `grok` once to sign in.",+ },+ Harness {+ id: "gemini",+ name: "Gemini CLI",+ bins: &["gemini"],+ local: Some("{bin} --acp"),+ registry: Some("gemini"),+ setup: "Install Gemini CLI (npm install -g @google/gemini-cli) and run `gemini` once to sign in.",+ },+ Harness {+ id: "copilot",+ name: "GitHub Copilot",+ bins: &["copilot"],+ local: Some("{bin} --acp --stdio"),+ registry: Some("github-copilot-cli"),+ setup: "Install Copilot CLI (npm install -g @github/copilot) and run `copilot` to sign in.",+ },+ Harness {+ id: "qwen",+ name: "Qwen Code",+ bins: &["qwen"],+ local: Some("{bin} --acp"),+ registry: Some("qwen-code"),+ setup: "Install Qwen Code (npm install -g @qwen-code/qwen-code) and sign in with `qwen`.",+ },+ Harness {+ id: "goose",+ name: "goose",+ bins: &["goose"],+ local: Some("{bin} acp"),+ registry: Some("goose"),+ setup: "Install goose and run `goose configure`.",+ },+ Harness {+ id: "kimi",+ name: "Kimi CLI",+ bins: &["kimi"],+ local: Some("{bin} acp"),+ registry: Some("kimi"),+ setup: "Install Kimi CLI and sign in with `kimi`.",+ },+ Harness {+ id: "droid",+ name: "Factory Droid",+ bins: &["droid"],+ local: Some("{bin} exec --output-format acp-daemon"),+ registry: Some("factory-droid"),+ setup: "Install Droid (curl -fsSL https://app.factory.ai/cli | sh) and sign in with `droid`.",+ },+ Harness {+ id: "amp",+ name: "Amp",+ bins: &["amp"],+ local: None,+ registry: Some("amp-acp"),+ setup: "Install Amp and sign in with `amp login`.",+ },+ Harness {+ id: "kilo",+ name: "Kilo",+ bins: &["kilo"],+ local: Some("{bin} acp"),+ registry: Some("kilo"),+ setup: "Install Kilo CLI (npm install -g @kilocode/cli) and sign in.",+ },+ Harness {+ id: "cline",+ name: "Cline",+ bins: &["cline"],+ local: Some("{bin} --acp"),+ registry: Some("cline"),+ setup: "Install Cline CLI (npm install -g cline) and sign in.",+ },+ Harness {+ id: "auggie",+ name: "Auggie",+ bins: &["auggie"],+ local: Some("{bin} --acp"),+ registry: Some("auggie"),+ setup: "Install Auggie (npm install -g @augmentcode/auggie) and run `auggie login`.",+ },+ Harness {+ id: "vibe",+ name: "Mistral Vibe",+ bins: &["vibe-acp", "vibe"],+ local: None,+ registry: Some("mistral-vibe"),+ setup: "Install Mistral Vibe and run `vibe` once to sign in.",+ },+ Harness {+ id: "kiro",+ name: "Kiro CLI",+ bins: &["kiro-cli"],+ local: Some("{bin} acp"),+ registry: None,+ setup: "Install Kiro CLI (curl -fsSL https://cli.kiro.dev/install | bash) and run `kiro-cli login`.",+ },+ Harness {+ id: "devin",+ name: "Devin",+ bins: &["devin"],+ local: Some("{bin} acp"),+ registry: Some("devin"),+ setup: "Install the Devin CLI and sign in.",+ },+ Harness {+ id: "qoder",+ name: "Qoder CLI",+ bins: &["qodercli"],+ local: Some("{bin} --acp"),+ registry: Some("qoder"),+ setup: "Install Qoder CLI and sign in.",+ },];pub fn harness(id: &str) -> Option<&'static Harness> {@@ -85,18 +226,21 @@ fn login_shell_path() -> Option<String> {Some(out[start..end].to_owned())}+/// `…/v22.1.0` → `[22, 1, 0]` (unparseable parts count as 0).+fn node_version(dir: &Path) -> Vec<u32> {+ dir.file_name()+ .and_then(|n| n.to_str())+ .map(|n| n.trim_start_matches('v').split('.').map(|p| p.parse().unwrap_or(0)).collect())+ .unwrap_or_default()+}+fn well_known_dirs() -> Vec<PathBuf> {let Some(home) = dirs::home_dir() else { return vec![] };- let mut dirs: Vec<PathBuf> = [- "/opt/homebrew/bin",- "/usr/local/bin",- "/home/linuxbrew/.linuxbrew/bin",- "/usr/bin",- "/bin",- ]- .iter()- .map(PathBuf::from)- .collect();+ let mut dirs: Vec<PathBuf> =+ ["/opt/homebrew/bin", "/usr/local/bin", "/home/linuxbrew/.linuxbrew/bin", "/usr/bin", "/bin"]+ .iter()+ .map(PathBuf::from)+ .collect();for rel in [".local/bin",".bun/bin",@@ -116,10 +260,10 @@ fn well_known_dirs() -> Vec<PathBuf> {}// Every nvm-installed node, newest first (global npm CLIs live next to node).if let Ok(entries) = std::fs::read_dir(home.join(".nvm/versions/node")) {- let mut versions: Vec<PathBuf> = entries.filter_map(|e| e.ok()).map(|e| e.path().join("bin")).collect();- versions.sort();- versions.reverse();- dirs.extend(versions);+ let mut versions: Vec<PathBuf> = entries.filter_map(Result::ok).map(|e| e.path()).collect();+ // Numeric, not lexicographic: v22.1.0 is newer than v9.11.2.+ versions.sort_by_key(|p| std::cmp::Reverse(node_version(p)));+ dirs.extend(versions.into_iter().map(|p| p.join("bin")));}dirs}@@ -143,12 +287,12 @@ pub fn hydrate_path() {// SAFETY: called at startup and from the single refresh command, before/between spawns.unsafe { std::env::set_var("PATH", joined) };}- *SEARCH_PATH.lock().unwrap() = path;+ *SEARCH_PATH.locked() = path;}pub fn which(bin: &str) -> Option<PathBuf> {let dirs = {- let cached = SEARCH_PATH.lock().unwrap();+ let cached = SEARCH_PATH.locked();if cached.is_empty() {std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default()} else {@@ -158,7 +302,7 @@ pub fn which(bin: &str) -> Option<PathBuf> {dirs.into_iter().map(|d| d.join(bin)).find(|p| is_executable(p))}-fn is_executable(p: &std::path::Path) -> bool {+fn is_executable(p: &Path) -> bool {#[cfg(unix)]{use std::os::unix::fs::PermissionsExt;@@ -184,7 +328,8 @@ pub fn list() -> Vec<Value> {.map(|h| {let path = h.bins.iter().find_map(|b| which(b));let reg = h.registry.and_then(|id| registry.iter().find(|a| a["id"] == id));- let runnable = (path.is_some() && h.local.is_some()) || reg.is_some_and(|a| registry::launch_kind(a).is_some());+ let runnable =+ (path.is_some() && h.local.is_some()) || reg.is_some_and(|a| registry::launch_kind(a).is_some());json!({"id": h.id,"name": h.name,@@ -241,11 +386,11 @@ pub async fn launch_candidates(id: &str, progress: impl Fn(&str)) -> anyhow::Resmatch registry::command(&agent, &progress).await {Ok(cmd) => out.push(cmd),Err(e) if out.is_empty() => return Err(e),- Err(e) => tracing::info!("registry launch for {id} unavailable: {e}"),+ Err(e) => tracing::info!(backend = id, error = format!("{e:#}"), "registry build unavailable"),}}if out.is_empty() {- let hint = h.map(|h| h.setup).unwrap_or("Check that it's installed on this computer.");+ let hint = h.map_or("Check that it's installed on this computer.", |h| h.setup);anyhow::bail!("{} isn't set up on this computer. {hint}", h.map_or(id, |h| h.name));}Ok(out)@@ -269,7 +414,7 @@ mod tests {std::fs::create_dir_all(&dir).unwrap();let bin = dir.join("fake-harness");std::fs::write(&bin, "#!/bin/sh\n").unwrap();- *SEARCH_PATH.lock().unwrap() = vec![dir.clone()];+ *SEARCH_PATH.locked() = vec![dir.clone()];assert!(which("fake-harness").is_none(), "not executable yet");#[cfg(unix)]{@@ -277,7 +422,7 @@ mod tests {std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();}assert_eq!(which("fake-harness"), Some(bin));- SEARCH_PATH.lock().unwrap().clear();+ SEARCH_PATH.locked().clear();}#[test]diff --git a/host/src/bot.rs b/host/src/bot.rsindex 592bb473..db860d95 100644--- a/host/src/bot.rs+++ b/host/src/bot.rs@@ -7,16 +7,26 @@//! "full conversation" sheet, and surface live as the roster activity line.use crate::acp::{self, Acp, Incoming};-use crate::hub::Hub;-use crate::push;-use crate::store::{BotConfig, now_ms};-use anyhow::{Result, anyhow};+use crate::hub::{BotStatus, Hub};+use crate::push::{self, AlertKind};+use crate::store::{BotConfig, EntryKind, Permission, now_ms};+use anyhow::{Result, anyhow, bail};+use serde::Serialize;use serde_json::{Value, json};use std::collections::{HashMap, HashSet, VecDeque};use std::sync::Arc;use std::time::{Duration, Instant};use tokio::sync::mpsc;+/// How a notice renders in the chat (wire values: `info` / `error` / `divider`).+#[derive(Clone, Copy, Debug, Serialize)]+#[serde(rename_all = "lowercase")]+pub enum NoticeStyle {+ Info,+ Error,+ Divider,+}+pub enum Cmd {Send { entry_id: String, text: String },Stop,@@ -28,6 +38,8 @@ pub enum Cmd {pub struct BotHandle {pub tx: mpsc::UnboundedSender<Cmd>,+ /// The actor task; it kills its agent process on the way out.+ pub task: tokio::task::JoinHandle<()>,}pub fn spawn(hub: Arc<Hub>, cfg: BotConfig) -> BotHandle {@@ -49,8 +61,8 @@ pub fn spawn(hub: Arc<Hub>, cfg: BotConfig) -> BotHandle {stop_requested: false,exit_tail: None,};- tokio::spawn(actor.run(rx));- BotHandle { tx }+ let task = tokio::spawn(actor.run(rx));+ BotHandle { tx, task }}struct Conn {@@ -110,7 +122,7 @@ impl Actor {while let Some(inc) = self.conn.as_mut().and_then(|c| c.rx.try_recv().ok()) {self.on_incoming(Some(inc)).await;}- self.finish_turn(done).await;+ self.finish_turn(&done);self.next_in_queue(&done_tx).await;}_ = flush_tick.tick() => self.flush(false),@@ -141,20 +153,19 @@ impl Actor {if self.turn.is_some() {self.stop().await;}- self.session_id = None;- let _ = self.hub.store.set_session(&self.cfg.id, None);- self.notice("New session — the agent starts with a fresh context.", "divider");+ self.forget_session();+ self.notice("New session — the agent starts with a fresh context.", NoticeStyle::Divider);}Cmd::Reconfigure(cfg) => {let cfg = *cfg;- let restart = cfg.backend != self.cfg.backend || cfg.command != self.cfg.command || cfg.cwd != self.cfg.cwd;+ let restart =+ cfg.backend != self.cfg.backend || cfg.command != self.cfg.command || cfg.cwd != self.cfg.cwd;self.cfg = cfg;if restart {if let Some(c) = self.conn.take() {c.acp.kill().await;}- self.session_id = None;- let _ = self.hub.store.set_session(&self.cfg.id, None);+ self.forget_session();// A running prompt now fails; finish_turn reports it.}}@@ -168,7 +179,7 @@ impl Actor {for (entry_id, _) in self.queue.drain(..) {if let Some(mut e) = self.hub.store.entry(&entry_id) {e.data["status"] = "cancelled".into();- let _ = self.hub.set_entry(&entry_id, e.data);+ self.hub.set_entry(&entry_id, &e.data);}}if self.turn.is_none() {@@ -194,10 +205,10 @@ impl Actor {{msg = format!("{} needs you to sign in on your computer first. {}", h.name, h.setup);}- self.notice(&msg, "error");+ self.notice(&msg, NoticeStyle::Error);self.turn = None;self.hub.set_runtime(&self.id(), |r| {- r.status = "error".into();+ r.status = BotStatus::Error;r.activity = "Couldn't start".into();r.started_at = None;});@@ -206,10 +217,10 @@ impl Actor {}async fn start_turn(&mut self, entry_id: &str, text: &str, done_tx: &mpsc::UnboundedSender<Done>) -> Result<()> {- let turn = self.hub.store.entry(entry_id).map(|e| e.turn).unwrap_or(0);+ let turn = self.hub.store.entry(entry_id).map_or(0, |e| e.turn);if let Some(mut e) = self.hub.store.entry(entry_id) {e.data["status"] = "sent".into();- self.hub.set_entry(entry_id, e.data)?;+ self.hub.set_entry(entry_id, &e.data);}self.turn = Some(turn);self.stop_requested = false;@@ -219,7 +230,7 @@ impl Actor {self.plan_entry = None;self.last_text = None;self.hub.set_runtime(&self.id(), |r| {- r.status = "working".into();+ r.status = BotStatus::Working;r.activity = "Starting…".into();r.started_at = Some(now_ms());});@@ -241,11 +252,17 @@ impl Actor {let mut prompt = text.to_owned();if self.session_fresh {self.session_fresh = false;- let mut profile = format!("You are \"{}\", a persistent agent the user delegates work to from their phone.", self.cfg.name);+ let mut profile = format!(+ "You are \"{}\", a persistent agent the user delegates work to from their phone.",+ self.cfg.name+ );if !self.cfg.description.trim().is_empty() {- profile.push_str(&format!(" Standing instructions:\n{}", self.cfg.description.trim()));+ profile.push_str(" Standing instructions:\n");+ profile.push_str(self.cfg.description.trim());}- profile.push_str("\nKeep your final reply short and phone-friendly: say what you did and what needs the user.");+ profile.push_str(+ "\nKeep your final reply short and phone-friendly: say what you did and what needs the user.",+ );prompt = format!("<bot-profile>\n{profile}\n</bot-profile>\n\n{text}");}self.hub.set_runtime(&self.id(), |r| r.activity = "Thinking…".into());@@ -287,7 +304,7 @@ impl Actor {break;}Err(e) => {- tracing::info!("`{command}` failed to start: {e}");+ tracing::info!(command, error = format!("{e:#}"), "agent failed to start");last_err = Some(e);}}@@ -296,13 +313,16 @@ impl Actor {return Err(last_err.unwrap_or_else(|| anyhow!("agent failed to start")));}}- let conn = self.conn.as_mut().unwrap();+ let Some(conn) = self.conn.as_mut() else { bail!("agent not running") };if let Some(sid) = self.session_id.clone() {if conn.loaded.contains(&sid) {return Ok(());}if !conn.can_load {- self.notice("This agent can't resume sessions after a restart — starting a fresh one.", "divider");+ self.notice(+ "This agent can't resume sessions after a restart — starting a fresh one.",+ NoticeStyle::Divider,+ );self.session_id = None;return Box::pin(self.ensure_session()).await;}@@ -323,29 +343,29 @@ impl Actor {return Ok(());}Err(e) => {- tracing::warn!("session/load failed, starting fresh: {e}");- self.notice("Couldn't resume the previous session — starting a fresh one.", "divider");+ tracing::warn!(error = format!("{e:#}"), "session/load failed; starting fresh");+ self.notice("Couldn't resume the previous session — starting a fresh one.", NoticeStyle::Divider);}}}- let conn = self.conn.as_mut().unwrap();- let res = conn- .acp- .request("session/new", json!({"cwd": self.cfg.cwd, "mcpServers": []}))- .await?;+ let Some(conn) = self.conn.as_mut() else { bail!("agent not running") };+ let res = conn.acp.request("session/new", json!({"cwd": self.cfg.cwd, "mcpServers": []})).await?;let sid = res["sessionId"].as_str().ok_or_else(|| anyhow!("agent returned no sessionId"))?.to_owned();conn.loaded.insert(sid.clone());if let Some(model) = self.cfg.model.clone().filter(|m| !m.is_empty()) {let has_model = res["configOptions"].as_array().is_some_and(|o| o.iter().any(|o| o["id"] == "model"));let r = if has_model {conn.acp- .request("session/set_config_option", json!({"sessionId": sid, "configId": "model", "value": model}))+ .request(+ "session/set_config_option",+ json!({"sessionId": sid, "configId": "model", "value": model}),+ ).await} else {conn.acp.request("session/set_model", json!({"sessionId": sid, "modelId": model})).await};if let Err(e) = r {- tracing::warn!("couldn't set model {model}: {e}");+ tracing::warn!(model, error = format!("{e:#}"), "couldn't set model");}}self.session_id = Some(sid.clone());@@ -354,7 +374,7 @@ impl Actor {Ok(())}- async fn finish_turn(&mut self, done: Done) {+ fn finish_turn(&mut self, done: &Done) {if self.turn.is_none() {return;}@@ -365,7 +385,7 @@ impl Actor {for id in ids {if let Some(mut e) = self.hub.store.entry(&id) {e.data["status"] = "expired".into();- let _ = self.hub.set_entry(&id, e.data);+ self.hub.set_entry(&id, &e.data);}}let stopped = self.stop_requested || matches!(&done, Ok(v) if v["stopReason"] == "cancelled");@@ -375,7 +395,7 @@ impl Actor {&& matches!(e.data["status"].as_str(), Some("pending" | "in_progress")){e.data["status"] = if stopped || done.is_err() { "failed" } else { "completed" }.into();- let _ = self.hub.set_entry(entry_id, e.data);+ self.hub.set_entry(entry_id, &e.data);}}let mut final_text = None;@@ -384,7 +404,7 @@ impl Actor {{e.data["final"] = true.into();final_text = e.data["text"].as_str().map(str::to_owned);- let _ = self.hub.set_entry(&id, e.data);+ self.hub.set_entry(&id, &e.data);}let stop_reason = match &done {Ok(v) => v["stopReason"].as_str().unwrap_or("end_turn").to_owned(),@@ -394,24 +414,25 @@ impl Actor {(Err(e), _) if !self.stop_requested => {let tail = self.exit_tail.take().filter(|t| !t.is_empty());let detail = tail.map(|t| format!("\n\n{}", acp::truncate(&t, 1200))).unwrap_or_default();- self.notice(&format!("The agent failed: {e}{detail}"), "error")+ self.notice(&format!("The agent failed: {e}{detail}"), NoticeStyle::Error);}- (_, "cancelled") | (Err(_), _) => self.notice("Stopped.", "info"),- (_, "max_tokens") => self.notice("The agent hit its output limit.", "info"),- (_, "max_turn_requests") => self.notice("The agent hit its step limit for this turn.", "info"),- (_, "refusal") => self.notice("The agent declined to continue.", "info"),+ (_, "cancelled") | (Err(_), _) => self.notice("Stopped.", NoticeStyle::Info),+ (_, "max_tokens") => self.notice("The agent hit its output limit.", NoticeStyle::Info),+ (_, "max_turn_requests") => self.notice("The agent hit its step limit for this turn.", NoticeStyle::Info),+ (_, "refusal") => self.notice("The agent declined to continue.", NoticeStyle::Info),_ => {}}let failed = done.is_err() && !self.stop_requested;self.turn = None;self.hub.set_runtime(&self.id(), |r| {- r.status = if failed { "error" } else { "idle" }.into();+ r.status = if failed { BotStatus::Error } else { BotStatus::Idle };r.activity = String::new();r.started_at = None;});if !self.stop_requested {- let body = final_text.unwrap_or_else(|| if failed { "The agent failed.".into() } else { "Finished.".into() });- push::notify(&self.hub, &self.cfg, &self.cfg.name, &body, "done");+ let body =+ final_text.unwrap_or_else(|| if failed { "The agent failed.".into() } else { "Finished.".into() });+ push::notify(&self.hub, &self.cfg, &self.cfg.name, &body, AlertKind::Done);}push::live_activity_end(&self.hub, &self.cfg.id);}@@ -430,7 +451,10 @@ impl Actor {self.exit_tail = Some(tail);}Some(Incoming::Notification { method, params }) => {- if method == "session/update" && params["sessionId"].as_str() == self.session_id.as_deref() && self.turn.is_some() {+ if method == "session/update"+ && params["sessionId"].as_str() == self.session_id.as_deref()+ && self.turn.is_some()+ {self.on_update(¶ms["update"]);}}@@ -473,7 +497,7 @@ impl Actor {});merge_tool_content(&mut data, &u["content"]);let title = data["title"].as_str().unwrap_or("Tool").to_owned();- if let Ok(e) = self.hub.add_entry(&self.cfg.id, "tool", turn, data) {+ if let Some(e) = self.hub.add_entry(&self.cfg.id, EntryKind::Tool, turn, &data) {self.tools.insert(tool_id, e.id);}self.set_activity(&title);@@ -493,7 +517,7 @@ impl Actor {merge_tool_content(&mut e.data, &u["content"]);let status = e.data["status"].as_str().unwrap_or_default().to_owned();let title = e.data["title"].as_str().unwrap_or_default().to_owned();- let _ = self.hub.set_entry(&entry_id, e.data);+ self.hub.set_entry(&entry_id, &e.data);if status == "in_progress" {self.set_activity(&title);}@@ -508,10 +532,10 @@ impl Actor {let data = json!({"entries": u["entries"].clone()});match &self.plan_entry {Some(id) => {- let _ = self.hub.set_entry(id, data);+ self.hub.set_entry(id, &data);}None => {- if let Ok(e) = self.hub.add_entry(&self.cfg.id, "plan", turn, data) {+ if let Some(e) = self.hub.add_entry(&self.cfg.id, EntryKind::Plan, turn, &data) {self.plan_entry = Some(e.id);}}@@ -524,7 +548,7 @@ impl Actor {async fn on_permission(&mut self, rpc_id: Value, params: Value) {let options = params["options"].as_array().cloned().unwrap_or_default();let tool = ¶ms["toolCall"];- if self.cfg.permission == "auto" {+ if self.cfg.permission == Permission::Auto {let pick = ["allow_once", "allow_always"].iter().find_map(|k| options.iter().find(|o| o["kind"] == *k))@@ -549,10 +573,9 @@ impl Actor {let mut detail = json!({"output": "", "diffs": []});merge_tool_content(&mut detail, &tool["content"]);let raw = &tool["rawInput"];- let command = raw["command"]- .as_str()- .map(str::to_owned)- .or_else(|| raw["command"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(" ")));+ let command = raw["command"].as_str().map(str::to_owned).or_else(|| {+ raw["command"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(" "))+ });let data = json!({"title": title,"toolKind": tool["kind"].as_str().unwrap_or("other"),@@ -566,14 +589,14 @@ impl Actor {});let turn = self.turn.unwrap_or(0);self.close_seg();- if let Ok(e) = self.hub.add_entry(&self.cfg.id, "permission", turn, data) {+ if let Some(e) = self.hub.add_entry(&self.cfg.id, EntryKind::Permission, turn, &data) {self.perms.insert(e.id, rpc_id);}self.hub.set_runtime(&self.cfg.id, |r| {- r.status = "needsInput".into();+ r.status = BotStatus::NeedsInput;r.activity = format!("Needs approval: {title}");});- push::notify(&self.hub, &self.cfg, &format!("{} needs you", self.cfg.name), &title, "needsInput");+ push::notify(&self.hub, &self.cfg, &format!("{} needs you", self.cfg.name), &title, AlertKind::NeedsInput);}async fn answer_permission(&mut self, entry_id: &str, option_id: Option<String>) {@@ -588,11 +611,11 @@ impl Actor {if let Some(mut e) = self.hub.store.entry(entry_id) {e.data["status"] = if option_id.is_some() { "answered" } else { "cancelled" }.into();e.data["selected"] = option_id.into();- let _ = self.hub.set_entry(entry_id, e.data);+ self.hub.set_entry(entry_id, &e.data);}if self.perms.is_empty() && self.turn.is_some() {self.hub.set_runtime(&self.cfg.id, |r| {- r.status = "working".into();+ r.status = BotStatus::Working;r.activity = "Continuing…".into();});}@@ -608,14 +631,15 @@ impl Actor {if !same {self.close_seg();let (k, data) = match kind {- SegKind::Text => ("agent", json!({"text": text, "final": false})),- SegKind::Thought => ("thought", json!({"text": text})),+ SegKind::Text => (EntryKind::Agent, json!({"text": text, "final": false})),+ SegKind::Thought => (EntryKind::Thought, json!({"text": text})),};- if let Ok(e) = self.hub.add_entry(&self.cfg.id, k, self.turn.unwrap_or(0), data) {+ if let Some(e) = self.hub.add_entry(&self.cfg.id, k, self.turn.unwrap_or(0), &data) {if kind == SegKind::Text {self.last_text = Some(e.id.clone());}- self.seg = Seg::Open { kind, entry_id: e.id, buf: text.to_owned(), flushed: Instant::now(), dirty: false };+ self.seg =+ Seg::Open { kind, entry_id: e.id, buf: text.to_owned(), flushed: Instant::now(), dirty: false };}return;}@@ -635,7 +659,7 @@ impl Actor {SegKind::Text => json!({"text": buf, "final": false}),SegKind::Thought => json!({"text": buf}),};- let _ = self.hub.set_entry(entry_id, data);+ self.hub.set_entry(entry_id, &data);*flushed = Instant::now();*dirty = false;}@@ -650,16 +674,24 @@ impl Actor {if self.hub.runtime(&self.cfg.id).activity != a {let a = a.to_owned();self.hub.set_runtime(&self.cfg.id, |r| {- if r.status == "working" {+ if r.status == BotStatus::Working {r.activity = a;}});}}- fn notice(&self, text: &str, style: &str) {+ /// Drops the ACP session so the next turn starts a fresh one.+ fn forget_session(&mut self) {+ self.session_id = None;+ if let Err(error) = self.hub.store.set_session(&self.cfg.id, None) {+ tracing::warn!(bot = %self.cfg.id, error = format!("{error:#}"), "couldn't clear the stored session");+ }+ }++ fn notice(&self, text: &str, style: NoticeStyle) {let turn = self.turn.unwrap_or_else(|| self.hub.store.max_turn(&self.cfg.id));- let _ = self.hub.add_entry(&self.cfg.id, "notice", turn, json!({"text": text, "style": style}));+ self.hub.add_entry(&self.cfg.id, EntryKind::Notice, turn, &json!({"text": text, "style": style}));}}@@ -741,12 +773,13 @@ pub fn diff_summary(path: &str, old: &str, new: &str) -> Value {let suffix = a[prefix..].iter().rev().zip(b[prefix..].iter().rev()).take_while(|(x, y)| x == y).count();let removed = &a[prefix..a.len() - suffix];let added = &b[prefix..b.len() - suffix];- let mut patch = String::new();- for l in removed {- patch.push_str(&format!("-{l}\n"));- }- for l in added {- patch.push_str(&format!("+{l}\n"));+ let mut unified = String::new();+ for (sign, lines) in [('-', removed), ('+', added)] {+ for l in lines {+ unified.push(sign);+ unified.push_str(l);+ unified.push('\n');+ }}json!({"path": path,@@ -754,7 +787,7 @@ pub fn diff_summary(path: &str, old: &str, new: &str) -> Value {"removed": removed.len(),"isNew": old.is_empty(),"startLine": prefix + 1,- "patch": acp::truncate(&patch, 6000),+ "patch": acp::truncate(&unified, 6000),})}diff --git a/host/src/hub.rs b/host/src/hub.rsindex 1f52df25..391ea85b 100644--- a/host/src/hub.rs+++ b/host/src/hub.rs@@ -1,19 +1,33 @@//! Shared host state: store, event fan-out, bot actors, push, usage.+use crate::LockExt;use crate::bot::{self, BotHandle, Cmd};-use crate::store::{BotConfig, BotRow, Entry, Store};+use crate::store::{BotConfig, BotRow, Entry, EntryKind, Store};+use crate::usage::Usage;use crate::{push, service};-use anyhow::{Result, anyhow};+use anyhow::{Result, anyhow, bail};+use serde::Serialize;use serde_json::{Value, json};use std::collections::HashMap;use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::{Arc, Mutex};+use std::time::Duration;use tokio::sync::broadcast;+/// What a bot is doing right now (wire values: `idle` / `working` / `needsInput` / `error`).+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub enum BotStatus {+ #[default]+ Idle,+ Working,+ NeedsInput,+ Error,+}+#[derive(Clone, Default, Debug)]pub struct Runtime {- /// idle | working | needsInput | error- pub status: String,+ pub status: BotStatus,pub activity: String,pub started_at: Option<i64>,}@@ -29,7 +43,7 @@ pub struct Hub {bots: Mutex<HashMap<String, BotHandle>>,runtime: Mutex<HashMap<String, Runtime>>,pub ios_clients: AtomicUsize,- pub usage: Mutex<Value>,+ pub usage: Mutex<Usage>,keep_awake: Mutex<service::KeepAwake>,/// botId -> Live Activity push tickets.pub activities: Mutex<HashMap<String, Vec<String>>>,@@ -45,12 +59,12 @@ impl Hub {port,events,emit_lock: Mutex::new(()),- bots: Default::default(),- runtime: Default::default(),+ bots: Mutex::default(),+ runtime: Mutex::default(),ios_clients: AtomicUsize::new(0),- usage: Mutex::new(json!({"providers": []})),- keep_awake: Default::default(),- activities: Default::default(),+ usage: Mutex::default(),+ keep_awake: Mutex::default(),+ activities: Mutex::default(),})}@@ -67,16 +81,29 @@ impl Hub {fn spawn_bot(self: &Arc<Self>, cfg: BotConfig) {let id = cfg.id.clone();- self.runtime.lock().unwrap().insert(- id.clone(),- Runtime { status: "idle".into(), ..Default::default() },- );+ self.runtime.locked().insert(id.clone(), Runtime::default());let handle = bot::spawn(self.clone(), cfg);- self.bots.lock().unwrap().insert(id, handle);+ self.bots.locked().insert(id, handle);+ }++ /// Stops every bot actor (and so every agent process), waiting briefly for them to exit.+ pub async fn shutdown(&self) {+ let handles: Vec<BotHandle> = self.bots.locked().drain().map(|(_, h)| h).collect();+ let tasks: Vec<_> = handles+ .into_iter()+ .map(|h| {+ let _ = h.tx.send(Cmd::Shutdown);+ h.task+ })+ .collect();+ if tokio::time::timeout(Duration::from_secs(5), futures::future::join_all(tasks)).await.is_err() {+ tracing::warn!("some bots didn't stop within 5 s");+ }+ self.keep_awake.locked().set(false);}pub fn send_cmd(&self, bot_id: &str, cmd: Cmd) -> Result<()> {- let bots = self.bots.lock().unwrap();+ let bots = self.bots.locked();let h = bots.get(bot_id).ok_or_else(|| anyhow!("unknown bot"))?;h.tx.send(cmd).map_err(|_| anyhow!("bot stopped"))}@@ -84,17 +111,17 @@ impl Hub {// MARK: botspub fn bot_json(&self, row: &BotRow) -> Value {- let mut v = serde_json::to_value(&row.config).unwrap();- let rt = self.runtime.lock().unwrap().get(&row.config.id).cloned().unwrap_or_default();+ let mut v = serde_json::to_value(&row.config).expect("BotConfig is plain data and always serializes");+ let rt = self.runtime.locked().get(&row.config.id).cloned().unwrap_or_default();let last = self.store.last_message(&row.config.id);v["rev"] = row.rev.into();v["deleted"] = row.deleted.into();- v["status"] = if rt.status.is_empty() { "idle".into() } else { rt.status.into() };+ v["status"] = json!(rt.status);v["activity"] = rt.activity.into();v["startedAt"] = rt.started_at.into();v["unread"] = self.store.unread(&row.config.id, row.read_rev).into();v["lastMessage"] = last.as_ref().map(|l| crate::acp::truncate(&l.0, 280)).into();- v["lastAt"] = last.map(|l| l.1).unwrap_or(row.config.created_at).into();+ v["lastAt"] = last.map_or(row.config.created_at, |l| l.1).into();v}@@ -113,7 +140,7 @@ impl Hub {cfg.created_at = crate::store::now_ms();validate(&cfg)?;{- let _g = self.emit_lock.lock().unwrap();+ let _g = self.emit_lock.locked();self.store.save_bot(&cfg)?;}self.spawn_bot(cfg.clone());@@ -121,7 +148,7 @@ impl Hub {Ok(self.bot_value(&cfg.id).unwrap_or(Value::Null))}- pub fn update_bot(&self, patch: Value) -> Result<Value> {+ pub fn update_bot(&self, patch: &Value) -> Result<Value> {let id = patch["id"].as_str().ok_or_else(|| anyhow!("id required"))?.to_owned();let row = self.store.bot(&id)?.filter(|b| !b.deleted).ok_or_else(|| anyhow!("unknown bot"))?;let mut merged = serde_json::to_value(&row.config)?;@@ -133,7 +160,7 @@ impl Hub {let cfg: BotConfig = serde_json::from_value(merged)?;validate(&cfg)?;{- let _g = self.emit_lock.lock().unwrap();+ let _g = self.emit_lock.locked();self.store.save_bot(&cfg)?;}self.send_cmd(&id, Cmd::Reconfigure(Box::new(cfg)))?;@@ -143,9 +170,9 @@ impl Hub {pub fn delete_bot(&self, id: &str) -> Result<()> {let _ = self.send_cmd(id, Cmd::Shutdown);- self.bots.lock().unwrap().remove(id);- self.runtime.lock().unwrap().remove(id);- let _g = self.emit_lock.lock().unwrap();+ self.bots.locked().remove(id);+ self.runtime.locked().remove(id);+ let _g = self.emit_lock.locked();let rev = self.store.delete_bot(id)?;let _ = self.events.send(json!({"type": "bot", "rev": rev, "bot": {"id": id, "deleted": true, "rev": rev}}));Ok(())@@ -153,7 +180,7 @@ impl Hub {pub fn mark_read(&self, id: &str) -> Result<()> {{- let _g = self.emit_lock.lock().unwrap();+ let _g = self.emit_lock.locked();self.store.mark_read(id)?;}self.emit_bot_row(id);@@ -166,7 +193,7 @@ impl Hub {/// Bumps the bot's rev and broadcasts its current state.pub fn emit_bot(&self, id: &str) {- let _g = self.emit_lock.lock().unwrap();+ let _g = self.emit_lock.locked();if self.store.touch_bot(id).is_ok()&& let Some(v) = self.bot_value(id){@@ -175,7 +202,7 @@ impl Hub {}fn emit_bot_row(&self, id: &str) {- let _g = self.emit_lock.lock().unwrap();+ let _g = self.emit_lock.locked();if let Some(v) = self.bot_value(id) {let _ = self.events.send(json!({"type": "bot", "rev": v["rev"], "bot": v}));}@@ -183,7 +210,7 @@ impl Hub {pub fn set_runtime(&self, id: &str, f: impl FnOnce(&mut Runtime)) {let (before, after) = {- let mut map = self.runtime.lock().unwrap();+ let mut map = self.runtime.locked();let rt = map.entry(id.to_owned()).or_default();let before = rt.clone();f(rt);@@ -197,35 +224,57 @@ impl Hub {}pub fn runtime(&self, id: &str) -> Runtime {- self.runtime.lock().unwrap().get(id).cloned().unwrap_or_default()+ self.runtime.locked().get(id).cloned().unwrap_or_default()}fn update_keep_awake(&self) {- let busy = self.runtime.lock().unwrap().values().any(|r| r.status == "working");- self.keep_awake.lock().unwrap().set(busy);+ let busy = self.runtime.locked().values().any(|r| r.status == BotStatus::Working);+ self.keep_awake.locked().set(busy);}// MARK: entries- pub fn add_entry(&self, bot_id: &str, kind: &str, turn: i64, data: Value) -> Result<Entry> {- let _g = self.emit_lock.lock().unwrap();- let e = self.store.insert_entry(bot_id, kind, turn, &data)?;- let _ = self.events.send(json!({"type": "entry", "rev": e.rev, "entry": e}));- Ok(e)+ /// Persists and broadcasts a new transcript entry. A failed write is logged here+ /// (once) and yields `None`: the conversation goes on without that line.+ pub fn add_entry(&self, bot_id: &str, kind: EntryKind, turn: i64, data: &Value) -> Option<Entry> {+ let _g = self.emit_lock.locked();+ match self.store.insert_entry(bot_id, kind, turn, data) {+ Ok(e) => {+ let _ = self.events.send(json!({"type": "entry", "rev": e.rev, "entry": e}));+ Some(e)+ }+ Err(error) => {+ tracing::error!(+ error = format!("{error:#}"),+ bot = bot_id,+ kind = kind.as_str(),+ "couldn't save transcript entry"+ );+ None+ }+ }}- pub fn set_entry(&self, id: &str, data: Value) -> Result<Option<Entry>> {- let _g = self.emit_lock.lock().unwrap();- let e = self.store.update_entry(id, &data)?;- if let Some(e) = &e {- let _ = self.events.send(json!({"type": "entry", "rev": e.rev, "entry": e}));+ /// Updates and broadcasts an entry; failures are logged here, like [`Self::add_entry`].+ pub fn set_entry(&self, id: &str, data: &Value) -> Option<Entry> {+ let _g = self.emit_lock.locked();+ match self.store.update_entry(id, data) {+ Ok(e) => {+ if let Some(e) = &e {+ let _ = self.events.send(json!({"type": "entry", "rev": e.rev, "entry": e}));+ }+ e+ }+ Err(error) => {+ tracing::error!(error = format!("{error:#}"), entry = id, "couldn't update transcript entry");+ None+ }}- Ok(e)}- pub fn set_usage(&self, usage: Value) {- *self.usage.lock().unwrap() = usage.clone();+ pub fn set_usage(&self, usage: Usage) {let _ = self.events.send(json!({"type": "usage", "usage": usage}));+ *self.usage.locked() = usage;}pub fn ios_connected(&self) -> bool {@@ -235,13 +284,14 @@ impl Hub {fn validate(cfg: &BotConfig) -> Result<()> {if cfg.name.trim().is_empty() {- return Err(anyhow!("name is required"));+ bail!("name is required");}if !std::path::Path::new(&cfg.cwd).is_dir() {- return Err(anyhow!("workspace folder does not exist: {}", cfg.cwd));+ bail!("workspace folder does not exist: {}", cfg.cwd);}- if cfg.command.as_deref().map(str::trim).unwrap_or_default().is_empty() && !crate::backends::is_known(&cfg.backend) {- return Err(anyhow!("unknown backend {}", cfg.backend));+ if cfg.command.as_deref().map(str::trim).unwrap_or_default().is_empty() && !crate::backends::is_known(&cfg.backend)+ {+ bail!("unknown backend {}", cfg.backend);}Ok(())}diff --git a/host/src/main.rs b/host/src/main.rsindex f03554ae..471fb720 100644--- a/host/src/main.rs+++ b/host/src/main.rs@@ -1,3 +1,5 @@+//! `codync-host`: runs coding-agent bots over ACP and serves the Codync apps.+mod acp;mod api;mod backends;@@ -9,14 +11,39 @@ mod service;mod store;mod usage;-use anyhow::Result;+use anyhow::{Context, Result};use clap::{Parser, Subcommand};use serde_json::json;+use std::fmt::Write as _;use std::io::Read;+use std::sync::{LazyLock, Mutex, MutexGuard, PoisonError};use std::time::Duration;+/// Poison-tolerant locking. Every critical section in the host is a short,+/// self-contained update, so a panic elsewhere never leaves the data half+/// written — and a daemon must not wedge every later caller over one panic.+pub trait LockExt<T> {+ fn locked(&self) -> MutexGuard<'_, T>;+}++impl<T> LockExt<T> for Mutex<T> {+ fn locked(&self) -> MutexGuard<'_, T> {+ self.lock().unwrap_or_else(PoisonError::into_inner)+ }+}++/// One shared HTTP client (connection pool + TLS config) for the whole process.+pub fn http() -> &'static reqwest::Client {+ static CLIENT: LazyLock<reqwest::Client> = LazyLock::new(reqwest::Client::new);+ &CLIENT+}+#[derive(Parser)]-#[command(name = "codync-host", version, about = "Codync host: runs your coding-agent bots and serves the Codync phone app")]+#[command(+ name = "codync-host",+ version,+ about = "Codync host: runs your coding-agent bots and serves the Codync phone app"+)]struct Cli {#[command(subcommand)]cmd: Option<Sub>,@@ -68,15 +95,15 @@ enum Sub {/// `~/.codync/token` (0600) for local helpers like the statusline command.fn open_store() -> Result<(store::Store, String, String)> {let dir = service::data_dir();- std::fs::create_dir_all(&dir)?;- let store = store::Store::open(&dir.join("codync.db"))?;- let host_id = match store.kv_get("host_id") {- Some(v) => v,- None => {- let v = uuid::Uuid::new_v4().to_string();- store.kv_set("host_id", &v)?;- v- }+ std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;+ let db = dir.join("codync.db");+ let store = store::Store::open(&db).with_context(|| format!("opening {}", db.display()))?;+ let host_id = if let Some(v) = store.kv_get("host_id") {+ v+ } else {+ let v = uuid::Uuid::new_v4().to_string();+ store.kv_set("host_id", &v)?;+ v};let token = match store.kv_get("token") {Some(v) => v,@@ -94,11 +121,12 @@ fn rotate_token(store: &store::Store) -> Result<String> {fn write_token_file(token: &str) -> Result<()> {let path = service::data_dir().join("token");- std::fs::write(&path, token)?;+ std::fs::write(&path, token).with_context(|| format!("writing {}", path.display()))?;#[cfg(unix)]{use std::os::unix::fs::PermissionsExt;- std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))+ .with_context(|| format!("restricting {}", path.display()))?;}Ok(())}@@ -114,7 +142,10 @@ async fn main() -> Result<()> {let name = service::host_name();let url = service::pairing_url(&name, &token, &urls);if json {- println!("{}", json!({"name": name, "hostId": host_id, "token": token, "urls": urls, "pairingUrl": url}));+ println!(+ "{}",+ json!({"name": name, "hostId": host_id, "token": token, "urls": urls, "pairingUrl": url})+ );} else {let code = qrcode::QrCode::new(url.as_bytes())?;println!("{}", code.render::<qrcode::render::unicode::Dense1x2>().quiet_zone(true).build());@@ -132,11 +163,15 @@ async fn main() -> Result<()> {if let Some(home) = dirs::home_dir() {match service::remove_legacy_hooks(&home.join(".claude/settings.json")) {Ok(0) => {}- Ok(n) => println!("Removed {n} Codync 1.x hook(s) from ~/.claude/settings.json (backup saved next to it)."),+ Ok(n) => println!(+ "Removed {n} Codync 1.x hook(s) from ~/.claude/settings.json (backup saved next to it)."+ ),Err(e) => eprintln!("Couldn't clean up Codync 1.x hooks: {e}"),}match service::ensure_statusline(&home.join(".claude/settings.json")) {- Ok(true) => println!("Claude Code's status line now also reports usage limits to Codync (your own status line still shows)."),+ Ok(true) => println!(+ "Claude Code's status line now also reports usage limits to Codync (your own status line still shows)."+ ),Ok(false) => {}Err(e) => eprintln!("Couldn't set Claude Code's status line: {e}"),}@@ -146,21 +181,27 @@ async fn main() -> Result<()> {Ok(())}Sub::Uninstall => {- service::uninstall()?;- if let Some(home) = dirs::home_dir() {- let _ = service::restore_statusline(&home.join(".claude/settings.json"));+ service::uninstall();+ if let Some(home) = dirs::home_dir()+ && let Err(e) = service::restore_statusline(&home.join(".claude/settings.json"))+ {+ eprintln!("Couldn't restore Claude Code's status line: {e:#}");}println!("Codync host service removed. Data is kept in {}", service::data_dir().display());Ok(())}Sub::Status { port } => {- let running = reqwest::Client::new()+ let running = http().get(format!("http://127.0.0.1:{port}/health")).timeout(Duration::from_secs(2)).send().await.is_ok_and(|r| r.status().is_success());- println!("installed: {}\nrunning: {running}\nport: {port}\ndata: {}", service::installed(), service::data_dir().display());+ println!(+ "installed: {}\nrunning: {running}\nport: {port}\ndata: {}",+ service::installed(),+ service::data_dir().display()+ );Ok(())}Sub::Statusline { port, wrapped } => {@@ -189,19 +230,51 @@ async fn serve(bind: &str, port: u16) -> Result<()> {hub.start()?;tokio::spawn(registry::refresh_loop());tokio::spawn(usage::poll(hub.clone()));- let listener = tokio::net::TcpListener::bind((bind, port)).await?;- tracing::info!("codync-host {} listening on {bind}:{port}", env!("CARGO_PKG_VERSION"));- axum::serve(listener, api::router(hub)).await?;+ let listener =+ tokio::net::TcpListener::bind((bind, port)).await.with_context(|| format!("binding {bind}:{port}"))?;+ tracing::info!(version = env!("CARGO_PKG_VERSION"), bind, port, "codync-host listening");+ axum::serve(listener, api::router(hub.clone())).with_graceful_shutdown(shutdown_signal()).await?;+ // launchd/systemd stop us with SIGTERM: stop every agent instead of orphaning it.+ hub.shutdown().await;+ tracing::info!("codync-host stopped");Ok(())}+/// Resolves on Ctrl-C or SIGTERM.+async fn shutdown_signal() {+ let ctrl_c = async {+ if let Err(error) = tokio::signal::ctrl_c().await {+ tracing::warn!(%error, "can't listen for Ctrl-C");+ std::future::pending::<()>().await;+ }+ };+ #[cfg(unix)]+ let term = async {+ match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {+ Ok(mut s) => {+ s.recv().await;+ }+ Err(error) => {+ tracing::warn!(%error, "can't listen for SIGTERM");+ std::future::pending::<()>().await;+ }+ }+ };+ #[cfg(not(unix))]+ let term = std::future::pending::<()>();+ tokio::select! {+ () = ctrl_c => {}+ () = term => {}+ }+}+/// Never blocks Claude Code: 1 s budget, all errors ignored.async fn statusline(port: u16, wrapped: String) {let mut input = String::new();let _ = std::io::stdin().read_to_string(&mut input);let v: serde_json::Value = serde_json::from_str(&input).unwrap_or_default();if let Ok(token) = std::fs::read_to_string(service::data_dir().join("token")) {- let _ = reqwest::Client::new()+ let _ = http().post(format!("http://127.0.0.1:{port}/ingest/statusline")).bearer_auth(token.trim()).json(&v)@@ -212,11 +285,8 @@ async fn statusline(port: u16, wrapped: String) {if !wrapped.trim().is_empty() {// The user's own status line gets the same JSON on stdin.use std::io::Write;- if let Ok(mut child) = std::process::Command::new("/bin/sh")- .arg("-c")- .arg(&wrapped)- .stdin(std::process::Stdio::piped())- .spawn()+ if let Ok(mut child) =+ std::process::Command::new("/bin/sh").arg("-c").arg(&wrapped).stdin(std::process::Stdio::piped()).spawn(){if let Some(mut stdin) = child.stdin.take() {let _ = stdin.write_all(input.as_bytes());@@ -229,7 +299,7 @@ async fn statusline(port: u16, wrapped: String) {let mut line = model.to_owned();for (k, label) in [("five_hour", "5h"), ("seven_day", "7d")] {if let Some(p) = v["rate_limits"][k]["used_percentage"].as_f64() {- line.push_str(&format!(" · {label} {p:.0}%"));+ let _ = write!(line, " · {label} {p:.0}%");}}println!("{line}");diff --git a/host/src/push.rs b/host/src/push.rsindex a8f0fc9c..201dcef3 100644--- a/host/src/push.rs+++ b/host/src/push.rs@@ -4,54 +4,75 @@//! Like Grok Bot there are only two alert kinds: "needs you" and "done", and//! none are sent while the phone app is connected (it's in the foreground).-use crate::hub::{Hub, Runtime};+use crate::LockExt;+use crate::hub::{BotStatus, Hub, Runtime};use crate::store::BotConfig;+use serde::Serialize;use serde_json::{Value, json};use std::collections::HashMap;-use std::sync::Mutex;+use std::sync::{LazyLock, Mutex};use std::time::{Duration, Instant};-static LAST: Mutex<Option<HashMap<String, Instant>>> = Mutex::new(None);+/// The two alert kinds (wire values double as the APNs category).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]+#[serde(rename_all = "camelCase")]+pub enum AlertKind {+ Done,+ NeedsInput,+}++/// `(bot id, Some(kind))` for alerts, `(bot id, None)` for Live Activity updates.+type ThrottleKey = (String, Option<AlertKind>);++/// Throttle key → last send.+static LAST_SENT: LazyLock<Mutex<HashMap<ThrottleKey, Instant>>> = LazyLock::new(Mutex::default);/// Tickets the relay reported as dead (app uninstalled / token rotated); purged on the next push.static GONE: Mutex<Vec<String>> = Mutex::new(Vec::new());+/// Seconds between the Unix epoch and Swift's `Date` reference date (2001-01-01).+const SWIFT_REFERENCE_EPOCH: f64 = 978_307_200.0;+fn relay_url(hub: &Hub) -> Option<String> {std::env::var("CODYNC_RELAY_URL").ok().or_else(|| hub.store.kv_get("relay_url")).filter(|u| !u.is_empty())}+/// True when `key` was sent less than `min_gap` ago; otherwise records now.+fn throttled(key: ThrottleKey, min_gap: Duration) -> bool {+ let mut last = LAST_SENT.locked();+ if last.get(&key).is_some_and(|t| t.elapsed() < min_gap) {+ return true;+ }+ last.insert(key, Instant::now());+ false+}+fn post(url: String, body: Value) {tokio::spawn(async move {- let client = reqwest::Client::new();- match client.post(&url).json(&body).timeout(Duration::from_secs(10)).send().await {+ match crate::http().post(&url).json(&body).timeout(Duration::from_secs(10)).send().await {Ok(r) if r.status().is_success() => {}Ok(r) if r.status() == reqwest::StatusCode::GONE => {if let Some(t) = body["ticket"].as_str() {- GONE.lock().unwrap().push(t.to_owned());+ GONE.locked().push(t.to_owned());}}- Ok(r) => tracing::warn!("relay {} → {}", url, r.status()),- Err(e) => tracing::warn!("relay {url}: {e}"),+ Ok(r) => tracing::warn!(%url, status = %r.status(), "relay rejected push"),+ Err(error) => tracing::warn!(%url, %error, "relay unreachable"),}});}-pub fn notify(hub: &Hub, bot: &BotConfig, title: &str, body: &str, kind: &str) {+pub fn notify(hub: &Hub, bot: &BotConfig, title: &str, body: &str, kind: AlertKind) {if bot.notify == Some(false) || bot.hidden || hub.ios_connected() {return;}- // At most one alert per bot+kind every 5 s.- {- let mut last = LAST.lock().unwrap();- let map = last.get_or_insert_with(HashMap::new);- let key = format!("{}:{kind}", bot.id);- if map.get(&key).is_some_and(|t| t.elapsed() < Duration::from_secs(5)) {- return;- }- map.insert(key, Instant::now());+ if throttled((bot.id.clone(), Some(kind)), Duration::from_secs(5)) {+ return;}let Some(relay) = relay_url(hub) else { return };- for t in std::mem::take(&mut *GONE.lock().unwrap()) {- let _ = hub.store.remove_device(&t);+ for t in std::mem::take(&mut *GONE.locked()) {+ if let Err(error) = hub.store.remove_device(&t) {+ tracing::warn!(%error, "couldn't forget a dead push ticket");+ }}for ticket in hub.store.devices() {post(@@ -69,38 +90,35 @@ pub fn notify(hub: &Hub, bot: &BotConfig, title: &str, body: &str, kind: &str) {/// Throttled Live Activity content updates for bots the phone is watching.pub fn live_activity_update(hub: &Hub, bot_id: &str, rt: &Runtime) {- let tickets = hub.activities.lock().unwrap().get(bot_id).cloned().unwrap_or_default();+ let tickets = hub.activities.locked().get(bot_id).cloned().unwrap_or_default();if tickets.is_empty() {return;}- {- let mut last = LAST.lock().unwrap();- let map = last.get_or_insert_with(HashMap::new);- let key = format!("{bot_id}:la");- let urgent = rt.status != "working";- if !urgent && map.get(&key).is_some_and(|t| t.elapsed() < Duration::from_secs(8)) {- return;- }- map.insert(key, Instant::now());+ // Status changes always go out; activity-line churn at most every 8 s.+ let urgent = rt.status != BotStatus::Working;+ if !urgent && throttled((bot_id.to_owned(), None), Duration::from_secs(8)) {+ return;}let Some(relay) = relay_url(hub) else { return };- let state = json!({- "status": if rt.status.is_empty() { "idle" } else { &rt.status },- "activity": rt.activity,- "startedAt": rt.started_at.map(|ms| ms as f64 / 1000.0 - 978_307_200.0), // Swift Date reference epoch- });+ #[allow(clippy::cast_precision_loss)] // epoch milliseconds fit an f64 mantissa until year 287,396+ let started_at = rt.started_at.map(|ms| ms as f64 / 1000.0 - SWIFT_REFERENCE_EPOCH);+ let state = json!({"status": rt.status, "activity": rt.activity, "startedAt": started_at});for ticket in tickets {- post(format!("{relay}/push"), json!({"ticket": ticket, "liveActivity": {"event": "update", "contentState": state}}));+ post(+ format!("{relay}/push"),+ json!({"ticket": ticket, "liveActivity": {"event": "update", "contentState": state}}),+ );}}pub fn live_activity_end(hub: &Hub, bot_id: &str) {- let tickets = hub.activities.lock().unwrap().remove(bot_id).unwrap_or_default();+ let tickets = hub.activities.locked().remove(bot_id).unwrap_or_default();let Some(relay) = relay_url(hub) else { return };+ let state = json!({"status": BotStatus::Idle, "activity": "", "startedAt": null});for ticket in tickets {post(format!("{relay}/push"),- json!({"ticket": ticket, "liveActivity": {"event": "end", "contentState": {"status": "idle", "activity": "", "startedAt": null}}}),+ json!({"ticket": ticket, "liveActivity": {"event": "end", "contentState": state}}),);}}diff --git a/host/src/registry.rs b/host/src/registry.rsindex 53972ae0..2758d578 100644--- a/host/src/registry.rs+++ b/host/src/registry.rs@@ -1,25 +1,40 @@-//! The official ACP agent registry (https://agentclientprotocol.com/registry):+//! The official ACP agent registry (<https://agentclientprotocol.com/registry>)://! ~40 coding agents with a known-good way to launch each over ACP — an npx or//! uvx package, or a per-platform binary archive we download on first use.+//!+//! Registry JSON is untrusted input: ids, versions and commands become paths on+//! disk, so they're checked before use.+use crate::LockExt;use anyhow::{Context, Result, anyhow, bail};use serde_json::Value;use sha2::{Digest, Sha256};-use std::path::{Path, PathBuf};+use std::path::{Component, Path, PathBuf};use std::sync::Mutex;use std::time::Duration;const URL: &str = "https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json";+/// Upstream updates hourly; once a day is plenty for picking agents.+const REFRESH_EVERY: Duration = Duration::from_secs(24 * 60 * 60);static CACHE: Mutex<Option<Value>> = Mutex::new(None);+/// How this machine would launch a registry agent.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Launch {+ /// A per-platform archive, downloaded once into `~/.codync/agents`.+ Download,+ Npx,+ Uvx,+}+fn cache_file() -> PathBuf {crate::service::data_dir().join("registry.json")}/// Registry agents (from memory, else the on-disk copy).pub fn agents() -> Vec<Value> {- let mut cache = CACHE.lock().unwrap();+ let mut cache = CACHE.locked();if cache.is_none() {*cache = std::fs::read_to_string(cache_file()).ok().and_then(|s| serde_json::from_str(&s).ok());}@@ -30,29 +45,26 @@ pub fn agent(id: &str) -> Option<Value> {agents().into_iter().find(|a| a["id"] == id)}-/// Refreshes the registry once a day (it changes hourly upstream; daily is plenty).pub async fn refresh_loop() {loop {match fetch().await {Ok(v) => {- let _ = std::fs::write(cache_file(), v.to_string());- *CACHE.lock().unwrap() = Some(v);+ if let Err(error) = tokio::fs::write(cache_file(), v.to_string()).await {+ tracing::warn!(%error, "couldn't cache the ACP registry");+ }+ *CACHE.locked() = Some(v);+ }+ Err(error) => {+ tracing::info!(error = format!("{error:#}"), "ACP registry refresh failed; using the cached copy");}- Err(e) => tracing::info!("ACP registry refresh failed (using cache): {e}"),}- tokio::time::sleep(Duration::from_secs(24 * 3600)).await;+ tokio::time::sleep(REFRESH_EVERY).await;}}async fn fetch() -> Result<Value> {- let v: Value = reqwest::Client::new()- .get(URL)- .timeout(Duration::from_secs(20))- .send()- .await?- .error_for_status()?- .json()- .await?;+ let v: Value =+ crate::http().get(URL).timeout(Duration::from_secs(20)).send().await?.error_for_status()?.json().await?;if !v["agents"].is_array() {bail!("unexpected registry format");}@@ -69,20 +81,19 @@ pub fn platform() -> Option<&'static str> {})}-/// How this machine would launch the agent: `npx` / `uvx` / `download`, or None.-pub fn launch_kind(agent: &Value) -> Option<&'static str> {+pub fn launch_kind(agent: &Value) -> Option<Launch> {let d = &agent["distribution"];let on_path = crate::backends::on_path;if let Some(p) = platform()&& d["binary"][p].is_object(){- return Some("download");+ return Some(Launch::Download);}if d["npx"].is_object() && on_path("npx") {- return Some("npx");+ return Some(Launch::Npx);}if d["uvx"].is_object() && on_path("uvx") {- return Some("uvx");+ return Some(Launch::Uvx);}None}@@ -102,90 +113,133 @@ fn args_of(v: &Value) -> String {.unwrap_or_default()}+/// `KEY=value ` pairs; keys that aren't plain identifiers are dropped (they'd be shell syntax).fn env_prefix(v: &Value) -> String {v["env"].as_object().map(|m| {m.iter()+ .filter(|(k, _)| !k.is_empty() && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')).filter_map(|(k, v)| Some(format!("{k}={} ", shell_quote(v.as_str()?)))).collect::<String>()}).unwrap_or_default()}+/// One path component made only of `[A-Za-z0-9._-]` and not `.`/`..`.+fn safe_component(s: &str) -> Option<&str> {+ let ok = !s.is_empty()+ && s != "."+ && s != ".."+ && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'));+ ok.then_some(s)+}++/// A relative path that stays inside its base directory (no `..`, no root).+fn contained(rel: &str) -> Option<&Path> {+ let p = Path::new(rel);+ p.components().all(|c| matches!(c, Component::Normal(_) | Component::CurDir)).then_some(p)+}+/// Shell command that starts the agent over ACP stdio, downloading it first if needed./// `progress` receives short status lines ("Downloading Cursor…").pub async fn command(agent: &Value, progress: impl Fn(&str)) -> Result<String> {let name = agent["name"].as_str().unwrap_or("agent");let d = &agent["distribution"];match launch_kind(agent) {- Some("download") => {- let target = &d["binary"][platform().unwrap()];- let dir = install_binary(agent, target, &progress).await?;- let cmd = target["cmd"].as_str().ok_or_else(|| anyhow!("registry entry has no cmd"))?;- let exe = dir.join(cmd.trim_start_matches("./"));- Ok(format!("{}{} {}", env_prefix(target), shell_quote(&exe.to_string_lossy()), args_of(target)))+ Some(Launch::Download) => {+ let platform = platform().ok_or_else(|| anyhow!("no download for this platform"))?;+ let target = &d["binary"][platform];+ let cmd =+ target["cmd"].as_str().and_then(contained).ok_or_else(|| anyhow!("registry entry has a bad cmd"))?;+ let dir = install_binary(agent, target, cmd, &progress).await?;+ Ok(format!("{}{} {}", env_prefix(target), shell_quote(&dir.join(cmd).to_string_lossy()), args_of(target)))}- Some("npx") => Ok(format!(+ Some(Launch::Npx) => Ok(format!("{}npx -y {} {}",env_prefix(&d["npx"]),shell_quote(d["npx"]["package"].as_str().unwrap_or_default()),args_of(&d["npx"]))),- Some("uvx") => Ok(format!(+ Some(Launch::Uvx) => Ok(format!("{}uvx {} {}",env_prefix(&d["uvx"]),shell_quote(d["uvx"]["package"].as_str().unwrap_or_default()),args_of(&d["uvx"]))),- _ => bail!("{name} has no build for this computer (needs {}).", if d["uvx"].is_object() { "uv" } else { "Node.js" }),+ None => bail!(+ "{name} has no build for this computer (needs {})",+ if d["uvx"].is_object() { "uv" } else { "Node.js" }+ ),}}-/// Downloads + extracts a binary distribution into ~/.codync/agents/<id>/<version>.-async fn install_binary(agent: &Value, target: &Value, progress: &impl Fn(&str)) -> Result<PathBuf> {- let id = agent["id"].as_str().unwrap_or("agent");- let version = agent["version"].as_str().unwrap_or("latest");+fn sha256_hex(bytes: &[u8]) -> String {+ use std::fmt::Write as _;+ Sha256::digest(bytes).iter().fold(String::with_capacity(64), |mut s, b| {+ let _ = write!(s, "{b:02x}");+ s+ })+}++/// Downloads + extracts a binary distribution into `~/.codync/agents/<id>/<version>`.+async fn install_binary(agent: &Value, target: &Value, cmd: &Path, progress: &impl Fn(&str)) -> Result<PathBuf> {+ let id = agent["id"].as_str().and_then(safe_component).ok_or_else(|| anyhow!("registry entry has a bad id"))?;+ let version = agent["version"].as_str().and_then(safe_component).unwrap_or("latest");let dir = crate::service::data_dir().join("agents").join(id).join(version);- if dir.join(".installed").exists() {+ if tokio::fs::try_exists(dir.join(".installed")).await.unwrap_or(false) {return Ok(dir);}let url = target["archive"].as_str().ok_or_else(|| anyhow!("registry entry has no archive"))?;+ if !url.starts_with("https://") {+ bail!("refusing a non-HTTPS download for {id}");+ }progress(&format!("Downloading {}…", agent["name"].as_str().unwrap_or(id)));- let bytes = reqwest::Client::new()+ let bytes = crate::http().get(url).timeout(Duration::from_secs(600)).send().await?.error_for_status()?.bytes()- .await?;- if let Some(want) = target["sha256"].as_str() {- let got: String = Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect();- if !got.eq_ignore_ascii_case(want) {- bail!("download checksum mismatch for {id}");- }+ .await+ .with_context(|| format!("downloading {id}"))?;+ if let Some(want) = target["sha256"].as_str()+ && !sha256_hex(&bytes).eq_ignore_ascii_case(want)+ {+ bail!("download checksum mismatch for {id}");}- let _ = std::fs::remove_dir_all(&dir);- std::fs::create_dir_all(&dir)?;- let file_name = url.rsplit('/').next().unwrap_or("download").split('?').next().unwrap_or("download");- let archive = dir.join(file_name);- std::fs::write(&archive, &bytes)?;progress("Installing…");- extract(&archive, &dir, target["cmd"].as_str().unwrap_or_default())?;- std::fs::write(dir.join(".installed"), "")?;+ let file_name =+ url.rsplit('/').next().and_then(|f| f.split('?').next()).and_then(safe_component).unwrap_or("download");+ let (dir2, file_name, cmd) = (dir.clone(), file_name.to_owned(), cmd.to_owned());+ tokio::task::spawn_blocking(move || -> Result<()> {+ let _ = std::fs::remove_dir_all(&dir2);+ std::fs::create_dir_all(&dir2)?;+ let archive = dir2.join(file_name);+ std::fs::write(&archive, &bytes)?;+ extract(&archive, &dir2, &cmd)?;+ std::fs::write(dir2.join(".installed"), "")?;+ Ok(())+ })+ .await?+ .with_context(|| format!("installing {id}"))?;Ok(dir)}-fn extract(archive: &Path, dir: &Path, cmd: &str) -> Result<()> {- let name = archive.file_name().unwrap().to_string_lossy().to_lowercase();+/// Blocking: unpacks `archive` into `dir` and makes `cmd` executable.+fn extract(archive: &Path, dir: &Path, cmd: &Path) -> Result<()> {+ let name = archive.file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();+ // Multi-part extensions (`.tar.gz`) rule out `Path::extension`; `name` is already lowercased.+ #[allow(clippy::case_sensitive_file_extension_comparisons)]let status = if name.ends_with(".zip") {std::process::Command::new("unzip").arg("-q").arg("-o").arg(archive).arg("-d").arg(dir).status()} else if [".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".tar"].iter().any(|e| name.ends_with(e)) {+ // Both GNU tar and bsdtar refuse `..` members by default.std::process::Command::new("tar").arg("-xf").arg(archive).arg("-C").arg(dir).status()} else {// Raw binary: it *is* the command.- let exe = dir.join(cmd.trim_start_matches("./"));+ let exe = dir.join(cmd);if let Some(parent) = exe.parent() {std::fs::create_dir_all(parent)?;}@@ -198,7 +252,7 @@ fn extract(archive: &Path, dir: &Path, cmd: &str) -> Result<()> {bail!("couldn't extract {}", archive.display());}let _ = std::fs::remove_file(archive);- let exe = dir.join(cmd.trim_start_matches("./"));+ let exe = dir.join(cmd);if exe.exists() {chmod_x(&exe)?;}@@ -223,7 +277,7 @@ mod tests {#[tokio::test]async fn npx_command_is_quoted() {- let a = json!({"id": "x", "name": "X", "distribution": {"npx": {"package": "@s/[email protected]", "args": ["--acp", "a b"], "env": {"K": "v"}}}});+ let a = json!({"id": "x", "name": "X", "distribution": {"npx": {"package": "@s/[email protected]", "args": ["--acp", "a b"], "env": {"K": "v", "BAD;rm": "x"}}}});if crate::backends::on_path("npx") {assert_eq!(command(&a, |_| {}).await.unwrap(), "K=v npx -y @s/[email protected] --acp 'a b'");}@@ -235,8 +289,20 @@ mod tests {std::fs::create_dir_all(&dir).unwrap();let archive = dir.join("tool-darwin");std::fs::write(&archive, "#!/bin/sh\necho hi\n").unwrap();- extract(&archive, &dir, "./bin/tool").unwrap();+ extract(&archive, &dir, Path::new("./bin/tool")).unwrap();let out = std::process::Command::new(dir.join("bin/tool")).output().unwrap();assert_eq!(String::from_utf8_lossy(&out.stdout), "hi\n");}++ #[test]+ fn registry_paths_cannot_escape_the_agents_dir() {+ assert_eq!(safe_component("cursor"), Some("cursor"));+ assert_eq!(safe_component("1.0.3-beta"), Some("1.0.3-beta"));+ for bad in ["", ".", "..", "a/b", "../x", "x y"] {+ assert_eq!(safe_component(bad), None, "{bad:?}");+ }+ assert!(contained("./dist-package/cursor-agent").is_some());+ assert!(contained("../../bin/sh").is_none());+ assert!(contained("/bin/sh").is_none());+ }}diff --git a/host/src/service.rs b/host/src/service.rsindex e0bc90c4..7cf0c0c0 100644--- a/host/src/service.rs+++ b/host/src/service.rs@@ -1,39 +1,56 @@//! Platform glue: data dir, background service install (launchd / systemd),-//! keeping the machine awake during turns, and pairing addresses.+//! keeping the machine awake during turns, pairing addresses, and the Claude+//! Code settings we touch (1.x hook cleanup, status line).+//!+//! Everything here is blocking (`std::fs`, `std::process`): async callers go+//! through `spawn_blocking`.use anyhow::{Context, Result, bail};-use std::path::PathBuf;+use serde_json::{Value, json};+use std::path::{Path, PathBuf};use std::process::{Child, Command, Stdio};pub const DEFAULT_PORT: u16 = 19222;const LABEL: &str = "com.pokai.codync.host";+/// Marker between our command and a wrapped user status line.+const STATUSLINE_MARK: &str = " statusline --";++/// The user's home. Codync can't do anything useful without one, so its absence is fatal.+fn home() -> PathBuf {+ dirs::home_dir().expect("HOME must be set: Codync keeps its data and agent settings there")+}pub fn data_dir() -> PathBuf {- std::env::var_os("CODYNC_HOME")- .map(PathBuf::from)- .unwrap_or_else(|| dirs::home_dir().expect("no home dir").join(".codync"))+ std::env::var_os("CODYNC_HOME").map_or_else(|| home().join(".codync"), PathBuf::from)}fn launchd_plist() -> PathBuf {- dirs::home_dir().unwrap().join(format!("Library/LaunchAgents/{LABEL}.plist"))+ home().join(format!("Library/LaunchAgents/{LABEL}.plist"))}fn systemd_unit() -> PathBuf {- dirs::config_dir().unwrap().join("systemd/user/codync-host.service")+ dirs::config_dir().unwrap_or_else(|| home().join(".config")).join("systemd/user/codync-host.service")}fn xml_escape(s: &str) -> String {s.replace('&', "&").replace('<', "<").replace('>', ">")}+fn create_parent(file: &Path) -> Result<()> {+ if let Some(parent) = file.parent() {+ std::fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;+ }+ Ok(())+}+/// Installs and starts the host as a per-user background service. The current/// PATH is captured so the service finds `npx`, `claude`, `codex`, …pub fn install(port: u16) -> Result<()> {- let exe = std::env::current_exe()?.canonicalize()?;+ let exe = std::env::current_exe()?.canonicalize().context("locating the codync-host binary")?;let exe = exe.to_string_lossy();let path = std::env::var("PATH").unwrap_or_default();let log = data_dir().join("host.log");- std::fs::create_dir_all(data_dir())?;+ std::fs::create_dir_all(data_dir()).context("creating the data directory")?;if cfg!(target_os = "macos") {let plist = format!(r#"<?xml version="1.0" encoding="UTF-8"?>@@ -56,24 +73,19 @@ pub fn install(port: u16) -> Result<()> {log = xml_escape(&log.to_string_lossy()),);let file = launchd_plist();- std::fs::create_dir_all(file.parent().unwrap())?;- let uid = unsafe_uid();+ create_parent(&file)?;+ let uid = current_uid();+ // Not loaded yet is the normal case here.let _ = Command::new("launchctl").args(["bootout", &format!("gui/{uid}/{LABEL}")]).status();- std::fs::write(&file, plist)?;- let ok = Command::new("launchctl")- .args(["bootstrap", &format!("gui/{uid}"), &file.to_string_lossy()])- .status()?- .success();- if !ok {- bail!("launchctl bootstrap failed");- }+ std::fs::write(&file, plist).with_context(|| format!("writing {}", file.display()))?;+ run("launchctl", &["bootstrap", &format!("gui/{uid}"), &file.to_string_lossy()])?;} else {let unit = format!("[Unit]\nDescription=Codync host\nAfter=network-online.target\n\n[Service]\nExecStart={exe} serve --port {port}\nEnvironment=PATH={path}\nRestart=always\nRestartSec=3\n\n[Install]\nWantedBy=default.target\n");let file = systemd_unit();- std::fs::create_dir_all(file.parent().unwrap())?;- std::fs::write(&file, unit)?;+ create_parent(&file)?;+ std::fs::write(&file, unit).with_context(|| format!("writing {}", file.display()))?;run("systemctl", &["--user", "daemon-reload"])?;run("systemctl", &["--user", "enable", "--now", "codync-host.service"])?;println!("Tip: `loginctl enable-linger $USER` keeps the host running while you're logged out.");@@ -81,16 +93,16 @@ pub fn install(port: u16) -> Result<()> {Ok(())}-pub fn uninstall() -> Result<()> {+/// Best effort: every step tolerates "already gone".+pub fn uninstall() {if cfg!(target_os = "macos") {- let _ = Command::new("launchctl").args(["bootout", &format!("gui/{}/{LABEL}", unsafe_uid())]).status();+ let _ = Command::new("launchctl").args(["bootout", &format!("gui/{}/{LABEL}", current_uid())]).status();let _ = std::fs::remove_file(launchd_plist());} else {let _ = run("systemctl", &["--user", "disable", "--now", "codync-host.service"]);let _ = std::fs::remove_file(systemd_unit());let _ = run("systemctl", &["--user", "daemon-reload"]);}- Ok(())}pub fn installed() -> bool {@@ -105,14 +117,13 @@ fn run(cmd: &str, args: &[&str]) -> Result<()> {Ok(())}-fn unsafe_uid() -> String {+fn current_uid() -> String {Command::new("id").arg("-u").output().ok().and_then(|o| String::from_utf8(o.stdout).ok())- .map(|s| s.trim().to_owned())- .unwrap_or_else(|| "501".into())+ .map_or_else(|| "501".into(), |s| s.trim().to_owned())}/// Holds a sleep inhibitor while any bot is working.@@ -128,12 +139,19 @@ impl KeepAwake {Command::new("caffeinate").args(["-i", "-w", &pid]).stdout(Stdio::null()).spawn()} else {Command::new("systemd-inhibit")- .args(["--what=sleep:idle", "--who=Codync", "--why=A bot is working", "--mode=block", "sleep", "infinity"])+ .args([+ "--what=sleep:idle",+ "--who=Codync",+ "--why=A bot is working",+ "--mode=block",+ "sleep",+ "infinity",+ ]).stdout(Stdio::null()).stderr(Stdio::null()).spawn()};- self.0 = child.ok();+ self.0 = child.map_err(|error| tracing::warn!(%error, "can't keep the machine awake")).ok();}(false, true) => {if let Some(mut c) = self.0.take() {@@ -156,6 +174,7 @@ pub fn addresses(port: u16) -> Vec<String> {}if let std::net::IpAddr::V4(ip) = iface.ip() {let o = ip.octets();+ // 100.64.0.0/10 is Tailscale's CGNAT range.if o[0] == 100 && (64..128).contains(&o[1]) {tailscale.push(format!("http://{ip}:{port}"));} else if ip.is_private() {@@ -164,7 +183,7 @@ pub fn addresses(port: u16) -> Vec<String> {}}if let Ok(out) = Command::new("tailscale").args(["status", "--json"]).output()- && let Ok(v) = serde_json::from_slice::<serde_json::Value>(&out.stdout)+ && let Ok(v) = serde_json::from_slice::<Value>(&out.stdout)&& let Some(dns) = v["Self"]["DNSName"].as_str(){let dns = dns.trim_end_matches('.');@@ -184,45 +203,50 @@ pub fn host_name() -> String {n.trim_end_matches(".local").to_owned()}+/// RFC 3986 percent-encoding of everything but unreserved characters.fn pct(s: &str) -> String {- s.bytes()- .map(|b| match b {- b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => (b as char).to_string(),- _ => format!("%{b:02X}"),- })- .collect()+ use std::fmt::Write as _;+ let mut out = String::with_capacity(s.len());+ for b in s.bytes() {+ if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {+ out.push(char::from(b));+ } else {+ let _ = write!(out, "%{b:02X}");+ }+ }+ out}pub fn pairing_url(name: &str, token: &str, urls: &[String]) -> String {- format!(- "codync://pair?name={}&token={}&urls={}",- pct(name),- pct(token),- pct(&urls.join(","))- )+ format!("codync://pair?name={}&token={}&urls={}", pct(name), pct(token), pct(&urls.join(",")))}-#[cfg(test)]-mod tests {- #[test]- fn pairing_url_is_escaped() {- let u = super::pairing_url("Kevin's Mac", "t0k", &["http://100.1.2.3:19222".into(), "http://a:1".into()]);- assert_eq!(u, "codync://pair?name=Kevin%27s%20Mac&token=t0k&urls=http%3A%2F%2F100.1.2.3%3A19222%2Chttp%3A%2F%2Fa%3A1");+fn read_settings(settings: &Path) -> Result<Option<Value>> {+ match std::fs::read_to_string(settings) {+ Ok(text) => Ok(Some(serde_json::from_str(&text).context("parsing Claude settings")?)),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),+ Err(e) => Err(e).with_context(|| format!("reading {}", settings.display())),}}+fn write_settings(settings: &Path, v: &Value) -> Result<()> {+ create_parent(settings)?;+ std::fs::write(settings, serde_json::to_string_pretty(v)? + "\n")+ .with_context(|| format!("writing {}", settings.display()))+}+/// Codync 1.x installed `~/.codync/notify.sh` as Claude Code hooks. 2.x drives/// agents over ACP instead, so those hooks are dead weight; remove only them./// Returns how many hook commands were removed.-pub fn remove_legacy_hooks(settings: &std::path::Path) -> Result<usize> {- let Ok(text) = std::fs::read_to_string(settings) else { return Ok(0) };- let mut v: serde_json::Value = serde_json::from_str(&text).context("parsing Claude settings")?;+pub fn remove_legacy_hooks(settings: &Path) -> Result<usize> {+ let Some(mut v) = read_settings(settings)? else { return Ok(0) };+ let Some(root) = v.as_object_mut() else { return Ok(0) };let mut removed = 0;- if let Some(hooks) = v.get_mut("hooks").and_then(|h| h.as_object_mut()) {+ if let Some(hooks) = root.get_mut("hooks").and_then(Value::as_object_mut) {for groups in hooks.values_mut() {let Some(groups) = groups.as_array_mut() else { continue };for g in groups.iter_mut() {- if let Some(list) = g.get_mut("hooks").and_then(|l| l.as_array_mut()) {+ if let Some(list) = g.get_mut("hooks").and_then(Value::as_array_mut) {let before = list.len();list.retain(|h| !h["command"].as_str().is_some_and(|c| c.ends_with(".codync/notify.sh")));removed += before - list.len();@@ -231,25 +255,22 @@ pub fn remove_legacy_hooks(settings: &std::path::Path) -> Result<usize> {groups.retain(|g| g["hooks"].as_array().is_none_or(|l| !l.is_empty()));}hooks.retain(|_, groups| groups.as_array().is_none_or(|g| !g.is_empty()));- }- if v.get("hooks").and_then(|h| h.as_object()).is_some_and(|h| h.is_empty()) {- v.as_object_mut().unwrap().remove("hooks");+ if hooks.is_empty() {+ root.remove("hooks");+ }}if removed > 0 {- std::fs::copy(settings, settings.with_extension("json.codync-backup"))?;- std::fs::write(settings, serde_json::to_string_pretty(&v)? + "\n")?;+ std::fs::copy(settings, settings.with_extension("json.codync-backup")).context("backing up Claude settings")?;+ write_settings(settings, &v)?;}Ok(removed)}-const STATUSLINE_MARK: &str = " statusline --";-/// Routes Claude Code's status line through `codync-host statusline` so usage/// limits reach the host locally. An existing status line keeps working: it is/// wrapped (`codync-host statusline -- <original>`) and restored on uninstall.-pub fn ensure_statusline(settings: &std::path::Path) -> Result<bool> {- let text = std::fs::read_to_string(settings).unwrap_or_else(|_| "{}".into());- let mut v: serde_json::Value = serde_json::from_str(&text).context("parsing Claude settings")?;+pub fn ensure_statusline(settings: &Path) -> Result<bool> {+ let mut v = read_settings(settings)?.unwrap_or_else(|| json!({}));let current = v["statusLine"]["command"].as_str().map(str::to_owned);if current.as_deref().is_some_and(|c| c.contains(" statusline")) {return Ok(false);@@ -263,18 +284,14 @@ pub fn ensure_statusline(settings: &std::path::Path) -> Result<bool> {Some(original) => format!("{ours} -- {original}"),None => ours,};- v["statusLine"] = serde_json::json!({"type": "command", "command": command});- if let Some(parent) = settings.parent() {- std::fs::create_dir_all(parent)?;- }- std::fs::write(settings, serde_json::to_string_pretty(&v)? + "\n")?;+ v["statusLine"] = json!({"type": "command", "command": command});+ write_settings(settings, &v)?;Ok(true)}-/// Undoes `ensure_statusline`.-pub fn restore_statusline(settings: &std::path::Path) -> Result<()> {- let Ok(text) = std::fs::read_to_string(settings) else { return Ok(()) };- let mut v: serde_json::Value = serde_json::from_str(&text)?;+/// Undoes [`ensure_statusline`].+pub fn restore_statusline(settings: &Path) -> Result<()> {+ let Some(mut v) = read_settings(settings)? else { return Ok(()) };let Some(cmd) = v["statusLine"]["command"].as_str().map(str::to_owned) else { return Ok(()) };// Ours always starts with the quoted host path followed by ` statusline`.if !cmd.starts_with('\'') || !cmd.contains("' statusline") {@@ -283,45 +300,66 @@ pub fn restore_statusline(settings: &std::path::Path) -> Result<()> {match cmd.split_once(STATUSLINE_MARK) {Some((_, original)) => v["statusLine"]["command"] = original.trim().into(),None => {- v.as_object_mut().unwrap().remove("statusLine");+ if let Some(root) = v.as_object_mut() {+ root.remove("statusLine");+ }}}- std::fs::write(settings, serde_json::to_string_pretty(&v)? + "\n")?;- Ok(())+ write_settings(settings, &v)}#[cfg(test)]-mod legacy_tests {- #[test]- fn removes_only_codync_hooks() {- let dir = std::env::temp_dir().join(format!("codync-legacy-{}", uuid::Uuid::new_v4()));+mod tests {+ use super::*;++ fn temp_settings(contents: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!("codync-settings-{}", uuid::Uuid::new_v4()));std::fs::create_dir_all(&dir).unwrap();let f = dir.join("settings.json");- std::fs::write(- &f,+ std::fs::write(&f, contents).unwrap();+ f+ }++ fn read(f: &Path) -> Value {+ serde_json::from_str(&std::fs::read_to_string(f).unwrap()).unwrap()+ }++ #[test]+ fn pairing_url_is_escaped() {+ let u = pairing_url("Kevin's Mac", "t0k", &["http://100.1.2.3:19222".into(), "http://a:1".into()]);+ assert_eq!(+ u,+ "codync://pair?name=Kevin%27s%20Mac&token=t0k&urls=http%3A%2F%2F100.1.2.3%3A19222%2Chttp%3A%2F%2Fa%3A1"+ );+ }++ #[test]+ fn removes_only_codync_hooks() {+ let f = temp_settings(r#"{"model":"x","hooks":{"Stop":[{"hooks":[{"type":"command","command":"/Users/a/.codync/notify.sh"},{"type":"command","command":"say hi"}]}],"Notification":[{"hooks":[{"type":"command","command":"/Users/a/.codync/notify.sh"}]}]}}"#,- )- .unwrap();- assert_eq!(super::remove_legacy_hooks(&f).unwrap(), 2);- let v: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&f).unwrap()).unwrap();+ );+ assert_eq!(remove_legacy_hooks(&f).unwrap(), 2);+ let v = read(&f);assert_eq!(v["hooks"]["Stop"][0]["hooks"].as_array().unwrap().len(), 1);assert!(v["hooks"].get("Notification").is_none());assert_eq!(v["model"], "x");- assert!(dir.join("settings.json.codync-backup").exists());+ assert!(f.with_extension("json.codync-backup").exists());+ }++ #[test]+ fn missing_or_non_object_settings_are_left_alone() {+ let dir = std::env::temp_dir().join(format!("codync-none-{}", uuid::Uuid::new_v4()));+ assert_eq!(remove_legacy_hooks(&dir.join("settings.json")).unwrap(), 0);+ assert_eq!(remove_legacy_hooks(&temp_settings("[1, 2]")).unwrap(), 0);}#[test]fn statusline_wraps_and_restores() {- let dir = std::env::temp_dir().join(format!("codync-sl-{}", uuid::Uuid::new_v4()));- std::fs::create_dir_all(&dir).unwrap();- let f = dir.join("settings.json");- std::fs::write(&f, r#"{"statusLine":{"type":"command","command":"sh ~/mine.sh"}}"#).unwrap();- assert!(super::ensure_statusline(&f).unwrap());- assert!(!super::ensure_statusline(&f).unwrap(), "idempotent");- let v: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&f).unwrap()).unwrap();- assert!(v["statusLine"]["command"].as_str().unwrap().ends_with("statusline -- sh ~/mine.sh"));- super::restore_statusline(&f).unwrap();- let v: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&f).unwrap()).unwrap();- assert_eq!(v["statusLine"]["command"], "sh ~/mine.sh");+ let f = temp_settings(r#"{"statusLine":{"type":"command","command":"sh ~/mine.sh"}}"#);+ assert!(ensure_statusline(&f).unwrap());+ assert!(!ensure_statusline(&f).unwrap(), "idempotent");+ assert!(read(&f)["statusLine"]["command"].as_str().unwrap().ends_with("statusline -- sh ~/mine.sh"));+ restore_statusline(&f).unwrap();+ assert_eq!(read(&f)["statusLine"]["command"], "sh ~/mine.sh");}}diff --git a/host/src/store.rs b/host/src/store.rsindex b218c158..a87435b0 100644--- a/host/src/store.rs+++ b/host/src/store.rs@@ -1,6 +1,11 @@//! SQLite persistence. Every mutation stamps a global, monotonically increasing//! `rev`; clients sync with `since: rev` and never need a separate event log.+//!+//! Calls are synchronous. They're single-row or indexed queries measured in+//! microseconds, so async callers use them directly; the one bulk read (a fresh+//! client's catch-up) is capped per bot.+use crate::LockExt;use anyhow::Result;use rusqlite::{Connection, OptionalExtension, params};use serde::{Deserialize, Serialize};@@ -8,6 +13,43 @@ use serde_json::Value;use std::path::Path;use std::sync::Mutex;+/// How a bot handles the agent's permission requests (wire values `ask` / `auto`).+#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]+#[serde(rename_all = "lowercase")]+pub enum Permission {+ /// Every request becomes an approval card on the phone.+ #[default]+ Ask,+ /// Requests are approved once, automatically.+ Auto,+}++/// Transcript entry kinds (the `kind` column / wire field).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum EntryKind {+ User,+ Agent,+ Thought,+ Tool,+ Plan,+ Permission,+ Notice,+}++impl EntryKind {+ pub fn as_str(self) -> &'static str {+ match self {+ Self::User => "user",+ Self::Agent => "agent",+ Self::Thought => "thought",+ Self::Tool => "tool",+ Self::Plan => "plan",+ Self::Permission => "permission",+ Self::Notice => "notice",+ }+ }+}+#[derive(Serialize, Deserialize, Clone, Debug)]#[serde(rename_all = "camelCase")]pub struct BotConfig {@@ -24,9 +66,8 @@ pub struct BotConfig {#[serde(default)]pub command: Option<String>,pub cwd: String,- /// `ask` = every permission request goes to the phone; `auto` = approve once automatically.- #[serde(default = "default_permission")]- pub permission: String,+ #[serde(default)]+ pub permission: Permission,#[serde(default)]pub model: Option<String>,#[serde(default)]@@ -45,9 +86,6 @@ fn default_color() -> String {fn default_shape() -> String {"blob".into()}-fn default_permission() -> String {- "ask".into()-}#[derive(Serialize, Clone, Debug)]#[serde(rename_all = "camelCase")]@@ -71,6 +109,9 @@ pub struct BotRow {pub read_rev: i64,}+/// Raw `bots` row before the config JSON is parsed.+type RawBot = (String, String, i64, bool, Option<String>, i64);+pub struct Store {db: Mutex<Connection>,}@@ -78,8 +119,13 @@ pub struct Store {pub fn now_ms() -> i64 {std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)- .unwrap()- .as_millis() as i64+ .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX))+}++/// Logs a failed read and treats it as "nothing there" — for the read paths that feed+/// best-effort details (previews, unread badges), where one bad query mustn't fail a request.+fn logged<T>(what: &str, r: rusqlite::Result<T>) -> Option<T> {+ r.map_err(|error| tracing::warn!(%error, what, "database read failed")).ok()}fn next_rev(c: &Connection) -> Result<i64> {@@ -105,7 +151,23 @@ fn row_entry(r: &rusqlite::Row) -> rusqlite::Result<Entry> {})}+fn row_bot(r: &rusqlite::Row) -> rusqlite::Result<RawBot> {+ Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get::<_, i64>(3)? != 0, r.get(4)?, r.get(5)?))+}++/// A stored config that no longer parses is skipped (and logged) rather than failing every listing.+fn parse_bot((id, cfg, rev, deleted, session_id, read_rev): RawBot) -> Option<BotRow> {+ match serde_json::from_str(&cfg) {+ Ok(config) => Some(BotRow { config, rev, deleted, session_id, read_rev }),+ Err(error) => {+ tracing::warn!(bot = %id, %error, "skipping unreadable bot config");+ None+ }+ }+}+const ENTRY_COLS: &str = "seq, id, bot_id, rev, kind, turn, data, created_at, updated_at";+const BOT_COLS: &str = "id, config, rev, deleted, session_id, read_rev";impl Store {pub fn open(path: &Path) -> Result<Self> {@@ -129,19 +191,13 @@ impl Store {}pub fn kv_get(&self, k: &str) -> Option<String> {- let c = self.db.lock().unwrap();- c.query_row("SELECT v FROM kv WHERE k = ?", [k], |r| r.get(0))- .optional()- .ok()- .flatten()+ let c = self.db.locked();+ logged("kv", c.query_row("SELECT v FROM kv WHERE k = ?", [k], |r| r.get(0)).optional()).flatten()}pub fn kv_set(&self, k: &str, v: &str) -> Result<()> {- let c = self.db.lock().unwrap();- c.execute(- "INSERT INTO kv(k, v) VALUES(?1, ?2) ON CONFLICT(k) DO UPDATE SET v = ?2",- params![k, v],- )?;+ let c = self.db.locked();+ c.execute("INSERT INTO kv(k, v) VALUES(?1, ?2) ON CONFLICT(k) DO UPDATE SET v = ?2", params![k, v])?;Ok(())}@@ -152,33 +208,20 @@ impl Store {// MARK: botspub fn bots(&self) -> Result<Vec<BotRow>> {- let c = self.db.lock().unwrap();- let mut st = c.prepare("SELECT config, rev, deleted, session_id, read_rev FROM bots")?;- let rows = st- .query_map([], |r| {- let cfg: String = r.get(0)?;- Ok((cfg, r.get(1)?, r.get::<_, i64>(2)? != 0, r.get(3)?, r.get(4)?))- })?- .filter_map(|r| r.ok())- .filter_map(|(cfg, rev, deleted, session_id, read_rev)| {- Some(BotRow {- config: serde_json::from_str(&cfg).ok()?,- rev,- deleted,- session_id,- read_rev,- })- })- .collect();- Ok(rows)+ let c = self.db.locked();+ let mut st = c.prepare(&format!("SELECT {BOT_COLS} FROM bots"))?;+ let rows = st.query_map([], row_bot)?.collect::<rusqlite::Result<Vec<_>>>()?;+ Ok(rows.into_iter().filter_map(parse_bot).collect())}pub fn bot(&self, id: &str) -> Result<Option<BotRow>> {- Ok(self.bots()?.into_iter().find(|b| b.config.id == id))+ let c = self.db.locked();+ let row = c.query_row(&format!("SELECT {BOT_COLS} FROM bots WHERE id = ?1"), [id], row_bot).optional()?;+ Ok(row.and_then(parse_bot))}pub fn save_bot(&self, cfg: &BotConfig) -> Result<i64> {- let c = self.db.lock().unwrap();+ let c = self.db.locked();let rev = next_rev(&c)?;c.execute("INSERT INTO bots(id, rev, config) VALUES(?1, ?2, ?3)@@ -189,56 +232,50 @@ impl Store {}pub fn touch_bot(&self, id: &str) -> Result<i64> {- let c = self.db.lock().unwrap();+ let c = self.db.locked();let rev = next_rev(&c)?;c.execute("UPDATE bots SET rev = ?2 WHERE id = ?1", params![id, rev])?;Ok(rev)}pub fn delete_bot(&self, id: &str) -> Result<i64> {- let c = self.db.lock().unwrap();+ let c = self.db.locked();let rev = next_rev(&c)?;- c.execute(- "UPDATE bots SET rev = ?2, deleted = 1, session_id = NULL WHERE id = ?1",- params![id, rev],- )?;+ c.execute("UPDATE bots SET rev = ?2, deleted = 1, session_id = NULL WHERE id = ?1", params![id, rev])?;c.execute("DELETE FROM entries WHERE bot_id = ?1", [id])?;Ok(rev)}pub fn set_session(&self, id: &str, session: Option<&str>) -> Result<()> {- let c = self.db.lock().unwrap();+ let c = self.db.locked();c.execute("UPDATE bots SET session_id = ?2 WHERE id = ?1", params![id, session])?;Ok(())}pub fn mark_read(&self, id: &str) -> Result<i64> {- let c = self.db.lock().unwrap();+ let c = self.db.locked();let rev = next_rev(&c)?;- c.execute(- "UPDATE bots SET read_rev = ?2, rev = ?2 WHERE id = ?1",- params![id, rev],- )?;+ c.execute("UPDATE bots SET read_rev = ?2, rev = ?2 WHERE id = ?1", params![id, rev])?;Ok(rev)}/// Final agent messages + pending permission cards newer than what the user has read.pub fn unread(&self, id: &str, read_rev: i64) -> i64 {- let c = self.db.lock().unwrap();- c.query_row(+ let c = self.db.locked();+ let n = c.query_row("SELECT COUNT(*) FROM entries WHERE bot_id = ?1 AND rev > ?2 AND((kind = 'agent' AND json_extract(data, '$.final') = 1) OR(kind = 'permission' AND json_extract(data, '$.status') = 'pending'))",params![id, read_rev],|r| r.get(0),- )- .unwrap_or(0)+ );+ logged("unread", n).unwrap_or(0)}/// Newest chat-visible line for the roster preview.pub fn last_message(&self, id: &str) -> Option<(String, i64)> {- let c = self.db.lock().unwrap();- c.query_row(+ let c = self.db.locked();+ let row = c.query_row("SELECT kind, data, updated_at FROM entries WHERE bot_id = ?1 AND(kind = 'user' OR (kind = 'agent' AND json_extract(data, '$.final') = 1))ORDER BY seq DESC LIMIT 1",@@ -251,33 +288,31 @@ impl Store {.ok().and_then(|v| v["text"].as_str().map(str::to_owned)).unwrap_or_default();- let text = if kind == "user" { format!("You: {text}") } else { text };+ let text = if kind == EntryKind::User.as_str() { format!("You: {text}") } else { text };Ok((text, at))},- )- .optional()- .ok()- .flatten()+ );+ logged("last message", row.optional()).flatten()}// MARK: entries- pub fn insert_entry(&self, bot_id: &str, kind: &str, turn: i64, data: &Value) -> Result<Entry> {- let c = self.db.lock().unwrap();+ pub fn insert_entry(&self, bot_id: &str, kind: EntryKind, turn: i64, data: &Value) -> Result<Entry> {+ let c = self.db.locked();let rev = next_rev(&c)?;let now = now_ms();let id = uuid::Uuid::new_v4().to_string();c.execute("INSERT INTO entries(id, bot_id, rev, kind, turn, data, created_at, updated_at)VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7)",- params![id, bot_id, rev, kind, turn, data.to_string(), now],+ params![id, bot_id, rev, kind.as_str(), turn, data.to_string(), now],)?;Ok(Entry {id,seq: c.last_insert_rowid(),bot_id: bot_id.into(),rev,- kind: kind.into(),+ kind: kind.as_str().to_owned(),turn,data: data.clone(),created_at: now,@@ -286,60 +321,43 @@ impl Store {}pub fn update_entry(&self, id: &str, data: &Value) -> Result<Option<Entry>> {- let c = self.db.lock().unwrap();+ let c = self.db.locked();let rev = next_rev(&c)?;c.execute("UPDATE entries SET rev = ?2, data = ?3, updated_at = ?4 WHERE id = ?1",params![id, rev, data.to_string(), now_ms()],)?;- Ok(c.query_row(- &format!("SELECT {ENTRY_COLS} FROM entries WHERE id = ?1"),- [id],- row_entry,- )- .optional()?)+ Ok(c.query_row(&format!("SELECT {ENTRY_COLS} FROM entries WHERE id = ?1"), [id], row_entry).optional()?)}pub fn entry(&self, id: &str) -> Option<Entry> {- let c = self.db.lock().unwrap();- c.query_row(- &format!("SELECT {ENTRY_COLS} FROM entries WHERE id = ?1"),- [id],- row_entry,- )- .optional()- .ok()- .flatten()+ let c = self.db.locked();+ let row = c.query_row(&format!("SELECT {ENTRY_COLS} FROM entries WHERE id = ?1"), [id], row_entry);+ logged("entry", row.optional()).flatten()}pub fn find_by_nonce(&self, bot_id: &str, nonce: &str) -> Option<Entry> {- let c = self.db.lock().unwrap();- c.query_row(+ let c = self.db.locked();+ let row = c.query_row(&format!("SELECT {ENTRY_COLS} FROM entries WHERE bot_id = ?1 AND kind = 'user' AND json_extract(data, '$.clientNonce') = ?2"),params![bot_id, nonce],row_entry,- )- .optional()- .ok()- .flatten()+ );+ logged("entry by nonce", row.optional()).flatten()}pub fn max_turn(&self, bot_id: &str) -> i64 {- let c = self.db.lock().unwrap();- c.query_row(- "SELECT COALESCE(MAX(turn), 0) FROM entries WHERE bot_id = ?1",- [bot_id],- |r| r.get(0),- )- .unwrap_or(0)+ let c = self.db.locked();+ let n = c.query_row("SELECT COALESCE(MAX(turn), 0) FROM entries WHERE bot_id = ?1", [bot_id], |r| r.get(0));+ logged("max turn", n).unwrap_or(0)}/// Entries changed after `since`. A fresh client (`since == 0`) only gets the/// newest `cap` entries per bot and pages older ones in with `history`.pub fn entries_since(&self, since: i64, cap: i64) -> Result<Vec<Entry>> {- let c = self.db.lock().unwrap();+ let c = self.db.locked();let sql = if since == 0 {format!("SELECT {ENTRY_COLS} FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY bot_id ORDER BY seq DESC) AS rn FROM entries)@@ -349,50 +367,45 @@ impl Store {format!("SELECT {ENTRY_COLS} FROM entries WHERE rev > ?1 AND ?2 > 0 ORDER BY seq")};let mut st = c.prepare(&sql)?;- let rows = st.query_map(params![since, cap], row_entry)?.filter_map(|r| r.ok()).collect();- Ok(rows)+ Ok(st.query_map(params![since, cap], row_entry)?.collect::<rusqlite::Result<_>>()?)}pub fn history(&self, bot_id: &str, before_seq: i64, limit: i64) -> Result<Vec<Entry>> {- let c = self.db.lock().unwrap();+ let c = self.db.locked();let mut st = c.prepare(&format!("SELECT {ENTRY_COLS} FROM entries WHERE bot_id = ?1 AND seq < ?2 ORDER BY seq DESC LIMIT ?3"))?;- let mut rows: Vec<Entry> = st- .query_map(params![bot_id, before_seq, limit], row_entry)?- .filter_map(|r| r.ok())- .collect();+ let mut rows: Vec<Entry> =+ st.query_map(params![bot_id, before_seq, limit], row_entry)?.collect::<rusqlite::Result<_>>()?;rows.reverse();Ok(rows)}- /// Permission cards left `pending` by a crash or restart can never be answered.- pub fn expire_pending(&self) -> Result<Vec<Entry>> {+ /// Permission cards left `pending` (and sends left `queued`) by a crash or restart+ /// can never be honored; returns how many were closed out.+ pub fn expire_pending(&self) -> Result<usize> {let ids: Vec<String> = {- let c = self.db.lock().unwrap();+ let c = self.db.locked();let mut st = c.prepare("SELECT id FROM entries WHERE (kind = 'permission' AND json_extract(data, '$.status') = 'pending')OR (kind = 'user' AND json_extract(data, '$.status') = 'queued')",)?;- st.query_map([], |r| r.get(0))?.filter_map(|r| r.ok()).collect()+ st.query_map([], |r| r.get(0))?.collect::<rusqlite::Result<_>>()?};- let mut out = vec![];- for id in ids {- if let Some(mut e) = self.entry(&id) {- let status = if e.kind == "user" { "failed" } else { "expired" };+ for id in &ids {+ if let Some(mut e) = self.entry(id) {+ let status = if e.kind == EntryKind::User.as_str() { "failed" } else { "expired" };e.data["status"] = status.into();- if let Some(e) = self.update_entry(&id, &e.data)? {- out.push(e);- }+ self.update_entry(id, &e.data)?;}}- Ok(out)+ Ok(ids.len())}// MARK: devicespub fn add_device(&self, ticket: &str, name: &str) -> Result<()> {- let c = self.db.lock().unwrap();+ let c = self.db.locked();c.execute("INSERT INTO devices(ticket, name, created_at) VALUES(?1, ?2, ?3)ON CONFLICT(ticket) DO UPDATE SET name = ?2",@@ -402,16 +415,16 @@ impl Store {}pub fn remove_device(&self, ticket: &str) -> Result<()> {- self.db.lock().unwrap().execute("DELETE FROM devices WHERE ticket = ?1", [ticket])?;+ self.db.locked().execute("DELETE FROM devices WHERE ticket = ?1", [ticket])?;Ok(())}pub fn devices(&self) -> Vec<String> {- let c = self.db.lock().unwrap();- let Ok(mut st) = c.prepare("SELECT ticket FROM devices") else { return vec![] };- st.query_map([], |r| r.get(0))- .map(|rows| rows.filter_map(|r| r.ok()).collect())- .unwrap_or_default()+ let c = self.db.locked();+ let tickets = c+ .prepare("SELECT ticket FROM devices")+ .and_then(|mut st| st.query_map([], |r| r.get(0))?.collect::<rusqlite::Result<Vec<String>>>());+ logged("devices", tickets).unwrap_or_default()}}@@ -419,11 +432,15 @@ impl Store {mod tests {use super::*;- #[test]- fn rev_sync_and_unread() {+ fn temp_store() -> Store {let dir = std::env::temp_dir().join(format!("codync-test-{}", uuid::Uuid::new_v4()));std::fs::create_dir_all(&dir).unwrap();- let s = Store::open(&dir.join("t.db")).unwrap();+ Store::open(&dir.join("t.db")).unwrap()+ }++ #[test]+ fn rev_sync_and_unread() {+ let s = temp_store();let cfg = BotConfig {id: "b1".into(),name: "Rev".into(),@@ -433,7 +450,7 @@ mod tests {backend: "claude".into(),command: None,cwd: "/tmp".into(),- permission: "ask".into(),+ permission: Permission::Ask,model: None,pinned: false,hidden: false,@@ -441,8 +458,8 @@ mod tests {created_at: 0,};s.save_bot(&cfg).unwrap();- let u = s.insert_entry("b1", "user", 1, &serde_json::json!({"text": "hi"})).unwrap();- let a = s.insert_entry("b1", "agent", 1, &serde_json::json!({"text": "yo", "final": false})).unwrap();+ let u = s.insert_entry("b1", EntryKind::User, 1, &serde_json::json!({"text": "hi"})).unwrap();+ let a = s.insert_entry("b1", EntryKind::Agent, 1, &serde_json::json!({"text": "yo", "final": false})).unwrap();assert!(a.rev > u.rev);assert_eq!(s.unread("b1", 0), 0, "narration is not unread");let a2 = s.update_entry(&a.id, &serde_json::json!({"text": "yo!", "final": true})).unwrap().unwrap();@@ -453,5 +470,26 @@ mod tests {let r = s.mark_read("b1").unwrap();assert_eq!(s.unread("b1", r), 0);assert_eq!(s.history("b1", a.seq, 10).unwrap().len(), 1);+ assert_eq!(s.bot("b1").unwrap().unwrap().config.permission, Permission::Ask);+ assert!(s.bot("missing").unwrap().is_none());+ }++ #[test]+ fn restart_expires_pending_cards_and_queued_sends() {+ let s = temp_store();+ s.insert_entry("b1", EntryKind::Permission, 1, &serde_json::json!({"status": "pending"})).unwrap();+ let q = s.insert_entry("b1", EntryKind::User, 2, &serde_json::json!({"status": "queued"})).unwrap();+ s.insert_entry("b1", EntryKind::User, 1, &serde_json::json!({"status": "sent"})).unwrap();+ assert_eq!(s.expire_pending().unwrap(), 2);+ assert_eq!(s.entry(&q.id).unwrap().data["status"], "failed");+ assert_eq!(s.expire_pending().unwrap(), 0, "idempotent");+ }++ #[test]+ fn permission_wire_values_round_trip() {+ let p: Permission = serde_json::from_str("\"auto\"").unwrap();+ assert_eq!(p, Permission::Auto);+ assert_eq!(serde_json::to_string(&Permission::Ask).unwrap(), "\"ask\"");+ assert!(serde_json::from_str::<Permission>("\"yolo\"").is_err(), "unknown modes are rejected at the boundary");}}diff --git a/host/src/usage.rs b/host/src/usage.rsindex afc49855..d72c18cc 100644--- a/host/src/usage.rs+++ b/host/src/usage.rs@@ -5,64 +5,89 @@//! status line and the Claude ACP adapter's rate-limit events. Codex: the//! newest `rate_limits` event in `~/.codex/sessions` rollout files.+use crate::LockExt;use crate::hub::Hub;-use serde_json::{Value, json};+use serde::Serialize;+use serde_json::Value;use std::path::{Path, PathBuf};use std::sync::Arc;use std::time::Duration;-pub fn window(id: &str, label: &str, percent: f64, resets_at_ms: Option<i64>) -> Value {- json!({"id": id, "label": label, "percent": percent, "resetsAt": resets_at_ms})+const POLL_EVERY: Duration = Duration::from_secs(5 * 60);++/// Everything the apps show about limits (wire shape of the `usage` event).+#[derive(Serialize, Clone, Debug, Default, PartialEq)]+pub struct Usage {+ pub providers: Vec<Provider>,}-fn window_text(id: &str, label: &str, percent: f64, resets_text: &str) -> Value {- json!({"id": id, "label": label, "percent": percent, "resetsAt": null, "resetsText": resets_text})+#[derive(Serialize, Clone, Debug, PartialEq)]+#[serde(rename_all = "camelCase")]+pub struct Provider {+ pub id: &'static str,+ pub name: &'static str,+ pub windows: Vec<Window>,+ /// Where the numbers came from: `claude` (CLI), `statusline`, `agent`, `sessions`.+ pub source: &'static str,+ pub updated_at: i64,}-fn provider(id: &str, name: &str, windows: Vec<Value>, source: &str) -> Value {- json!({"id": id, "name": name, "windows": windows, "source": source, "updatedAt": crate::store::now_ms()})+#[derive(Serialize, Clone, Debug, PartialEq)]+#[serde(rename_all = "camelCase")]+pub struct Window {+ pub id: String,+ pub label: String,+ pub percent: f64,+ /// Epoch milliseconds, when known.+ pub resets_at: Option<i64>,+ /// Human text when only that is known ("Sep 26 at 12pm (Asia/Taipei)").+ #[serde(skip_serializing_if = "Option::is_none")]+ pub resets_text: Option<String>,}-fn merge(hub: &Hub, p: Value) {- let mut usage = hub.usage.lock().unwrap().clone();- let list = usage["providers"].as_array_mut().unwrap();- list.retain(|x| x["id"] != p["id"]);- list.push(p);- list.sort_by_key(|x| x["id"].as_str().unwrap_or_default().to_owned());- hub.set_usage(usage);+impl Window {+ fn new(id: impl Into<String>, label: impl Into<String>, percent: f64, resets_at: Option<i64>) -> Self {+ Self { id: id.into(), label: label.into(), percent, resets_at, resets_text: None }+ }}-/// Replaces or adds windows for one provider, keeping the others it already had.-fn merge_windows(hub: &Hub, id: &str, name: &str, source: &str, new: Vec<Value>) {- let existing = hub.usage.lock().unwrap()["providers"]- .as_array()- .and_then(|l| l.iter().find(|p| p["id"] == id))- .and_then(|p| p["windows"].as_array().cloned())- .unwrap_or_default();- let mut windows: Vec<Value> = existing.into_iter().filter(|w| !new.iter().any(|n| n["id"] == w["id"])).collect();- windows.extend(new);- windows.sort_by_key(|w| w["id"].as_str().unwrap_or_default().to_owned());- merge(hub, provider(id, name, windows, source));+impl Usage {+ /// Replaces `new` windows (by id) in provider `id`, keeping the provider's other windows.+ fn merge(&mut self, id: &'static str, name: &'static str, source: &'static str, new: Vec<Window>) {+ let mut windows = self.providers.iter().find(|p| p.id == id).map(|p| p.windows.clone()).unwrap_or_default();+ windows.retain(|w| !new.iter().any(|n| n.id == w.id));+ windows.extend(new);+ windows.sort_by(|a, b| a.id.cmp(&b.id));+ self.providers.retain(|p| p.id != id);+ self.providers.push(Provider { id, name, windows, source, updated_at: crate::store::now_ms() });+ self.providers.sort_by_key(|p| p.id);+ }+}++fn merge(hub: &Hub, id: &'static str, name: &'static str, source: &'static str, windows: Vec<Window>) {+ let mut usage = hub.usage.locked().clone();+ usage.merge(id, name, source, windows);+ hub.set_usage(usage);}pub async fn poll(hub: Arc<Hub>) {loop {refresh(&hub).await;- tokio::time::sleep(Duration::from_secs(300)).await;+ tokio::time::sleep(POLL_EVERY).await;}}pub async fn refresh(hub: &Hub) {- if let Some(p) = tokio::task::spawn_blocking(codex_usage).await.ok().flatten() {- merge(hub, p);+ if let Some(windows) = tokio::task::spawn_blocking(codex_usage).await.ok().flatten() {+ merge(hub, "codex", "Codex", "sessions", windows);}if let Some(windows) = claude_cli_usage().await {- merge_windows(hub, "claude", "Claude", "claude", windows);+ merge(hub, "claude", "Claude", "claude", windows);}}/// `claude -p /usage`: Claude Code's own local usage report, no model call.-async fn claude_cli_usage() -> Option<Vec<Value>> {+async fn claude_cli_usage() -> Option<Vec<Window>> {let bin = crate::backends::which("claude")?;let out = tokio::time::timeout(Duration::from_secs(60),@@ -70,6 +95,7 @@ async fn claude_cli_usage() -> Option<Vec<Value>> {.args(["-p", "/usage", "--output-format", "json", "--no-session-persistence"]).current_dir(dirs::home_dir()?).stdin(std::process::Stdio::null())+ .kill_on_drop(true).output(),).await@@ -81,12 +107,12 @@ async fn claude_cli_usage() -> Option<Vec<Value>> {}/// Lines like `Current week (all models): 53% used · resets Sep 26 at 12pm (Asia/Taipei)`.-pub fn parse_claude_usage(text: &str) -> Vec<Value> {+pub fn parse_claude_usage(text: &str) -> Vec<Window> {text.lines().filter_map(|line| {let (name, rest) = line.trim().split_once(": ")?;- let pct: f64 = rest.split_once("% used")?.0.trim().parse().ok()?;- let resets = rest.split_once("resets ").map(|(_, r)| r.trim()).unwrap_or_default();+ let percent: f64 = rest.split_once("% used")?.0.trim().parse().ok()?;+ let resets = rest.split_once("resets ").map(|(_, r)| r.trim().to_owned());let (id, label) = match name {"Current session" => ("five_hour".to_owned(), "5-hour".to_owned()),"Current week (all models)" => ("seven_day".to_owned(), "Weekly".to_owned()),@@ -95,7 +121,7 @@ pub fn parse_claude_usage(text: &str) -> Vec<Value> {(format!("seven_day_{}", model.to_lowercase()), format!("Weekly · {model}"))}};- Some(window_text(&id, &label, pct, resets))+ Some(Window { resets_text: resets, ..Window::new(id, label, percent, None) })}).collect()}@@ -103,25 +129,26 @@ pub fn parse_claude_usage(text: &str) -> Vec<Value> {/// `POST /ingest/statusline` body: Claude Code's statusline JSON.pub fn ingest_statusline(hub: &Hub, body: &Value) {let rl = &body["rate_limits"];- let mut windows = vec![];- for (key, label) in [("five_hour", "5-hour"), ("seven_day", "Weekly")] {- if let Some(p) = rl[key]["used_percentage"].as_f64() {- windows.push(window(key, label, p, rl[key]["resets_at"].as_i64().map(|s| s * 1000)));- }- }+ let windows: Vec<Window> = [("five_hour", "5-hour"), ("seven_day", "Weekly")]+ .into_iter()+ .filter_map(|(key, label)| {+ let percent = rl[key]["used_percentage"].as_f64()?;+ Some(Window::new(key, label, percent, rl[key]["resets_at"].as_i64().map(|s| s.saturating_mul(1000))))+ })+ .collect();if !windows.is_empty() {- merge_windows(hub, "claude", "Claude", "statusline", windows);+ merge(hub, "claude", "Claude", "statusline", windows);}}-/// Claude ACP adapter: `usage_update._meta["_claude/rateLimit"]` (the SDK's SDKRateLimitInfo).+/// Claude ACP adapter: `usage_update._meta["_claude/rateLimit"]` (the SDK's `SDKRateLimitInfo`).pub fn ingest_claude_rate_limit(hub: &Hub, info: &Value) {if let Some(w) = claude_window(info) {- merge_windows(hub, "claude", "Claude", "agent", vec![w]);+ merge(hub, "claude", "Claude", "agent", vec![w]);}}-fn claude_window(info: &Value) -> Option<Value> {+fn claude_window(info: &Value) -> Option<Window> {let kind = info["rateLimitType"].as_str()?;let label = match kind {"five_hour" => "5-hour",@@ -132,28 +159,31 @@ fn claude_window(info: &Value) -> Option<Value> {};let u = info["utilization"].as_f64()?;// The SDK reports a 0–1 fraction (from the unified rate-limit headers).- let pct = if u <= 1.0 { u * 100.0 } else { u };- let resets = info["resetsAt"].as_i64().map(|t| if t > 100_000_000_000 { t } else { t * 1000 });- Some(window(kind, label, pct, resets))+ let percent = if u <= 1.0 { u * 100.0 } else { u };+ // Seconds, but accept milliseconds too.+ let resets = info["resetsAt"].as_i64().map(|t| if t > 100_000_000_000 { t } else { t.saturating_mul(1000) });+ Some(Window::new(kind, label, percent, resets))}+/// Blocking. `sessions/YYYY/MM/DD/rollout-*.jsonl`: descend into the largest dir each level.fn newest_rollout(root: &Path) -> Option<PathBuf> {- // sessions/YYYY/MM/DD/rollout-*.jsonl — descend into the lexicographically largest dir each level.let mut dir = root.to_path_buf();for _ in 0..3 {- let mut subs: Vec<PathBuf> = std::fs::read_dir(&dir).ok()?.filter_map(|e| e.ok()).map(|e| e.path()).filter(|p| p.is_dir()).collect();+ let mut subs: Vec<PathBuf> =+ std::fs::read_dir(&dir).ok()?.filter_map(Result::ok).map(|e| e.path()).filter(|p| p.is_dir()).collect();subs.sort();dir = subs.pop()?;}std::fs::read_dir(&dir).ok()?- .filter_map(|e| e.ok())+ .filter_map(Result::ok).map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "jsonl")).max_by_key(|p| std::fs::metadata(p).and_then(|m| m.modified()).ok())}-fn codex_usage() -> Option<Value> {+/// Blocking: reads the newest Codex rollout file.+fn codex_usage() -> Option<Vec<Window>> {let path = newest_rollout(&dirs::home_dir()?.join(".codex/sessions"))?;let text = std::fs::read_to_string(&path).ok()?;let line = text.lines().rev().find(|l| l.contains("\"rate_limits\""))?;@@ -163,31 +193,29 @@ fn codex_usage() -> Option<Value> {.and_then(|m| m.modified()).ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())- .map(|d| d.as_millis() as i64)- .unwrap_or(0);+ .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX));let windows = parse_codex(rl, modified_ms);- (!windows.is_empty()).then(|| provider("codex", "Codex", windows, "sessions"))+ (!windows.is_empty()).then_some(windows)}-pub fn parse_codex(rl: &Value, observed_ms: i64) -> Vec<Value> {+pub fn parse_codex(rl: &Value, observed_ms: i64) -> Vec<Window> {["primary", "secondary"]- .iter()+ .into_iter().filter_map(|k| {- let w = &rl[*k];- let pct = w["used_percent"].as_f64()?;+ let w = &rl[k];+ let percent = w["used_percent"].as_f64()?;let minutes = w["window_minutes"].as_i64().unwrap_or(0);let label = match minutes {300 => "5-hour".to_owned(),10080 => "Weekly".to_owned(),m if m > 0 && m % 1440 == 0 => format!("{}-day", m / 1440),m if m > 0 => format!("{}-hour", m / 60),- _ => (*k).to_owned(),+ _ => k.to_owned(),};- let resets = w["resets_at"]- .as_i64()- .map(|s| s * 1000)- .or_else(|| w["resets_in_seconds"].as_i64().map(|s| observed_ms + s * 1000));- Some(window(k, &label, pct, resets))+ let resets = w["resets_at"].as_i64().map(|s| s.saturating_mul(1000)).or_else(|| {+ w["resets_in_seconds"].as_i64().map(|s| observed_ms.saturating_add(s.saturating_mul(1000)))+ });+ Some(Window::new(k, label, percent, resets))}).collect()}@@ -195,6 +223,7 @@ pub fn parse_codex(rl: &Value, observed_ms: i64) -> Vec<Value> {#[cfg(test)]mod tests {use super::*;+ use serde_json::json;#[test]fn parses_codex_rollout_limits() {@@ -203,9 +232,9 @@ mod tests {"secondary": {"used_percent": 40.0, "window_minutes": 10080, "resets_at": 100}}),1000,);- assert_eq!(x[0]["label"], "5-hour");- assert_eq!(x[0]["resetsAt"], 11_000);- assert_eq!(x[1]["resetsAt"], 100_000);+ assert_eq!(x[0].label, "5-hour");+ assert_eq!(x[0].resets_at, Some(11_000));+ assert_eq!(x[1].resets_at, Some(100_000));}#[test]@@ -214,18 +243,34 @@ mod tests {"You are currently using your subscription\n\nCurrent session: 11% used · resets Sep 25 at 5am (Asia/Taipei)\nCurrent week (all models): 53% used · resets Sep 26 at 12pm (Asia/Taipei)\nCurrent week (Fable): 83% used · resets Sep 26 at 12pm (Asia/Taipei)\n\nLast 24h · 794 requests",);assert_eq!(w.len(), 3);- assert_eq!(w[0]["id"], "five_hour");- assert_eq!(w[0]["percent"], 11.0);- assert_eq!(w[0]["resetsText"], "Sep 25 at 5am (Asia/Taipei)");- assert_eq!(w[2]["label"], "Weekly · Fable");+ assert_eq!(w[0].id, "five_hour");+ assert!((w[0].percent - 11.0).abs() < f64::EPSILON);+ assert_eq!(w[0].resets_text.as_deref(), Some("Sep 25 at 5am (Asia/Taipei)"));+ assert_eq!(w[2].label, "Weekly · Fable");}#[test]fn claude_rate_limit_fraction_becomes_percent() {- let w = claude_window(&json!({"rateLimitType": "five_hour", "utilization": 0.42, "resetsAt": 1_790_000_000}));- let w = w.unwrap();- assert_eq!(w["percent"], 42.0);- assert_eq!(w["resetsAt"], 1_790_000_000_000i64);+ let w = claude_window(&json!({"rateLimitType": "five_hour", "utilization": 0.42, "resetsAt": 1_790_000_000}))+ .unwrap();+ assert!((w.percent - 42.0).abs() < 1e-9);+ assert_eq!(w.resets_at, Some(1_790_000_000_000));assert!(claude_window(&json!({"rateLimitType": "overage", "utilization": 0.1})).is_none());}++ #[test]+ fn merge_replaces_only_matching_windows() {+ let mut u = Usage::default();+ u.merge(+ "claude",+ "Claude",+ "claude",+ vec![Window::new("five_hour", "5-hour", 10.0, None), Window::new("seven_day", "Weekly", 50.0, None)],+ );+ u.merge("claude", "Claude", "statusline", vec![Window::new("five_hour", "5-hour", 12.0, None)]);+ let c = &u.providers[0];+ assert_eq!((c.windows.len(), c.source), (2, "statusline"));+ assert!((c.windows[0].percent - 12.0).abs() < f64::EPSILON, "five_hour updated");+ assert_eq!(serde_json::to_value(&u).unwrap()["providers"][0]["windows"][1]["resetsAt"], Value::Null);+ }}