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
feat(host): add a send command that can wait for the reply (#160)
Ryan TT4451b2665cdd
diff --git a/README.md b/README.mdindex e5cfa220..28f69269 100644--- a/README.md+++ b/README.md@@ -158,6 +158,7 @@ and computer identity; do not use **Reset all data**, a cleanup utility, or Home|---|---|| `codync-host install` / `uninstall` | background service (launchd on macOS, systemd `--user` on Linux, the sign-in Run key on Windows) || `codync-host tui [--url … --token …]` | message your bots from a terminal (this computer by default; SSH-friendly) |+| `codync-host send --bot <id-or-name> [--wait] [--json] <text>...` | send from a script, optionally waiting for the final reply || `codync-host pair [--json]` | pairing QR code / link || `codync-host status` | installed? running? || `codync-host serve [--port 19222]` | run in the foreground |@@ -168,7 +169,17 @@ and computer identity; do not use **Reset all data**, a cleanup utility, or Home| `codync-host devices` | list/revoke authorized remote devices || `codync-host access` | review device access requests |-Data lives in `~/.codync`. The local bearer token authorizes loopback helpers and SSH-forwarded callers. Remote devices use individual keys and grants over the encrypted channel; revoke a lost device through device management rather than rotating the loopback token. Host methods and caller permissions live in `host/src/api/`.+For non-interactive work, send a message and wait for a machine-readable result:++```powershell+codync-host send --bot reviewer --wait --json "Review the current diff without modifying files."+```++`--bot` accepts an ID or an exact, case-insensitive name; duplicate names require an ID. Use positional text or `--file request.txt` to read UTF-8 (`--file -` reads stdin). `--reply-to <id>` quotes a message of the bot's chat: the `entryId` or `replyId` of an earlier `--json` result. Without `--wait`, the command prints the accepted message's `id`, `seq` and `turn`; with `--wait`, it prints the reply once the bot is done (a reply in several messages comes joined; a turn that ends with no text, such as only a reaction, prints nothing). Group chats can't be waited on. Queued messages retain the host's batching behavior, so multiple sends can share one reply and turn.++`--timeout <seconds>` defaults to 1800 active seconds. Pending approval pauses the clock and prints a summary to stderr; the command never approves a request or stops the bot on timeout. Notices also go to stderr. `--json` emits one JSON object with `botId`, `entryId`, `entrySeq`, `turn`, `status` (`completed`, `failed`, or `timeout`), optional `stopReason`, `reply` and `replyId`, `notices`, `elapsedSeconds` (wall time), and `waitedForApprovalSeconds`. Without `--wait`, `completed` means the send was accepted. Errors before acceptance only use stderr. Exit codes are **0** completed/accepted, **1** stopped/limited/declined/failed, **2** invalid arguments, missing/ambiguous bot or `--wait` on a group chat, **3** unavailable host or refused API request, and **4** timeout. See `codync-host send --help` for all options.++Data lives in `~/.codync`. The local bearer token authorizes loopback helpers and SSH-forwarded callers. Use `--port` and `CODYNC_HOME` when targeting a host with a different port or data directory; development builds default to port 19223 and `~/.codync-dev`. Remote devices use individual keys and grants over the encrypted channel; revoke a lost device through device management rather than rotating the loopback token. Host methods and caller permissions live in `host/src/api/`.## FAQdiff --git a/docs/architecture/file-structure.md b/docs/architecture/file-structure.mdindex 2863d4b0..7ec81d9b 100644--- a/docs/architecture/file-structure.md+++ b/docs/architecture/file-structure.md@@ -9,6 +9,7 @@ Codync/├── host/ # Rust daemon and terminal client│ ├── src/│ │ ├── main.rs # CLI entry, shared helpers (LockExt, http)+│ │ ├── *_cli.rs # Subcommands with their own module: cloud, network, send (+ send_cli/: event feed, --wait)│ │ ├── hub.rs, store/ # Shared state + event fan-out / SQLite persistence (schema, model, bots, entries, devices)│ │ ├── service/ # Data dir, launchd/systemd/Windows install, keep-awake│ │ ├── usage/, mcp.rs # usage/: plan limits from each agent; mcp.rs: built-in stdio MCP servers; mcp/remote.rs: remote connector proxy@@ -86,7 +87,7 @@ Codync/| Responsibility | Source entry points ||---|---|-| CLI and background service | `host/src/main.rs`, `service/` |+| CLI and background service | `host/src/main.rs`, `service/`; subcommands `cloud_cli.rs`, `network_cli.rs`, `send_cli.rs` (+ `send_cli/events.rs`, `wait.rs`) || API, caller permissions, event ordering | `host/src/api/`, `hub.rs` || SQLite transcript, bots, lanes and sessions | `host/src/store/` (`entries.rs`, `bots.rs`, `model.rs`, `devices.rs`, `schema.rs`) || Agent process, ACP, queue and session lifecycle | `host/src/agent/bot/` (`launch.rs`, `queue.rs`, `session.rs`, `turn.rs`, `updates.rs`), `acp.rs` (+ `acp/codebuddy.rs`, CodeBuddy's ACP extensions), `process.rs` (process-tree ownership; `process_windows.rs` on Windows) |diff --git a/docs/guides/user-docs.md b/docs/guides/user-docs.mdindex 8f232d6d..2a40ff75 100644--- a/docs/guides/user-docs.md+++ b/docs/guides/user-docs.md@@ -20,7 +20,7 @@ the change.| `getting-started` | Install, pair, first bot | `README.md`, [updates](updates.md), [dev app](dev-app.md) for names only || `bots` | Creating, settings, workspaces, hiding, permissions, new session | [bot workspaces](../features/bot-workspaces.md), [conversation runtime](../architecture/conversation-runtime.md) || `agents` | Known agents, registry, custom command, Extensions, sign-in, models | [extensions](../features/marketplace.md), `host/src/agent/backends.rs` |-| `conversations` | Messages, files, approval cards, stop, replies, reactions, commands, fresh conversations, notifications | [chat messages](../features/chat-messages.md), [file attachments](../features/file-attachments.md), [context and memory](../features/context-and-memory.md), [notifications](../design/push-and-live-activity.md) |+| `conversations` | Messages, files, approval cards, stop, replies, reactions, commands, fresh conversations, notifications, sending from a script (`codync-host send`) | `README.md` (`codync-host send`), [chat messages](../features/chat-messages.md), [file attachments](../features/file-attachments.md), [context and memory](../features/context-and-memory.md), [notifications](../design/push-and-live-activity.md) || `groups` | Group chats | [groups and replies](../features/groups-and-replies.md) || `teamwork` | Bots messaging bots, bots on your other computers, Manage the team | [bot collaboration](../features/bot-collaboration.md), [codync-network](../features/codync-network.md) || `cloud-assistants` | The MCP connector for ChatGPT, Claude and other assistants: turning it on, adding it, what it can do, privacy | [cloud assistants](../features/cloud-assistants.md) |diff --git a/docs/reference/remote-relay.md b/docs/reference/remote-relay.mdindex 7e3259d1..5110b18b 100644--- a/docs/reference/remote-relay.md+++ b/docs/reference/remote-relay.md@@ -304,7 +304,7 @@ blob = epk(32) ‖ sig(64) ‖ ct- `id`:device 端遞增 u32,連線內唯一。- 每條 channel 最多 32 個進行中的 request、4 個訂閱;超過回 `err 429`。-- `events` 訂閱的語意與 SSE 完全相同(先 subscribe、再 catch-up、`hello` 在最前、落後時送 `{"type":"resync"}`);`client == "ios"` 時計入 `hub.ios_clients`(推播抑制)。+- `events` 訂閱的語意與 SSE 完全相同(先 subscribe、再 catch-up、`hello` 在最前且 `catchUp` 為其後 catch-up 事件數、落後時送 `{"type":"resync"}`);`client == "ios"` 時計入 `hub.ios_clients`(推播抑制)。- Bot 刪除標記會保留在 host 資料庫;增量同步與 `since = 0` 的全量同步都傳送它們。手機及桌面在版本更新或解碼重試時會保留快取並重設同步游標,必須收到刪除標記才能移除舊 Bot、對話與草稿;終端使用相同的事件串流。- 串流沒有額外的 keep-alive;存活由 WebSocket ping(§7.6)負責。diff --git a/host/src/agent/bot/fallback.rs b/host/src/agent/bot/fallback.rsindex 1d0a736d..52944611 100644--- a/host/src/agent/bot/fallback.rs+++ b/host/src/agent/bot/fallback.rs@@ -333,9 +333,10 @@ impl Actor {}/// The failure notice: with a failure that moves on, a bot without fallbacks offers to add one, and a bot whose- /// agents all failed this turn (`fall_back` ran out of them) says how each one is.- pub(super) fn failure_notice(&self, error: &anyhow::Error, text: &str) {- let mut data = json!({"text": text, "style": NoticeStyle::Error});+ /// agents all failed this turn (`fall_back` ran out of them) says how each one is. It carries the turn's stop+ /// `reason` (see `stop_notice`).+ pub(super) fn failure_notice(&self, error: &anyhow::Error, text: &str, reason: &str) {+ let mut data = json!({"text": text, "style": NoticeStyle::Error, "stopReason": reason});match fallback::reason::of(error) {Some(Reason::UsageLimit | Reason::OutOfCredits | Reason::RateLimited | Reason::Overloaded)if self.base.fallbacks.is_empty() =>diff --git a/host/src/agent/bot/mod.rs b/host/src/agent/bot/mod.rsindex 92b81793..6b8295cd 100644--- a/host/src/agent/bot/mod.rs+++ b/host/src/agent/bot/mod.rs@@ -423,13 +423,18 @@ impl Actor {/// A notice in the running turn's lane (or the bot's own chat between turns).fn notice(&self, text: &str, style: NoticeStyle) {+ self.notice_data(json!({"text": text, "style": style}));+ }++ /// `notice` with more fields than its text and style.+ fn notice_data(&self, data: Value) {let Some(turn) = self.turn else {let main = Lane::main(&self.cfg.id);let turn = self.hub.store.max_turn(&self.cfg.id);- self.hub.add_entry(&main, EntryKind::Notice, turn, &json!({"text": text, "style": style}));+ self.hub.add_entry(&main, EntryKind::Notice, turn, &data);return;};- self.add(EntryKind::Notice, turn, json!({"text": text, "style": style}));+ self.add(EntryKind::Notice, turn, data);}}diff --git a/host/src/agent/bot/queue.rs b/host/src/agent/bot/queue.rsindex ed7bcc68..7bbce246 100644--- a/host/src/agent/bot/queue.rs+++ b/host/src/agent/bot/queue.rs@@ -313,7 +313,7 @@ impl Actor {self.complete_group(Err(anyhow!("couldn't start: {e:#}")));if !self.invite_sign_in(e) {// `{:#}` keeps the reason ("starting `npx …`: EACCES"), not just "agent process exited".- self.failure_notice(e, &format!("Couldn't start the agent: {e:#}"));+ self.failure_notice(e, &format!("Couldn't start the agent: {e:#}"), "start_failed");}// What the chain carried in (a recap, a takeover) was this turn's; the user's handoff waits for the next.self.relay.carried = None;diff --git a/host/src/agent/bot/turn.rs b/host/src/agent/bot/turn.rsindex 134897ba..cbe7ea03 100644--- a/host/src/agent/bot/turn.rs+++ b/host/src/agent/bot/turn.rs@@ -295,13 +295,15 @@ impl Actor {let tail = self.exit_tail.take().filter(|t| !t.is_empty());if !self.invite_sign_in(e) {let detail = tail.map(|t| format!("\n\n{}", acp::truncate(&t, 1200))).unwrap_or_default();- self.failure_notice(e, &format!("The agent failed: {e}{detail}"));+ self.failure_notice(e, &format!("The agent failed: {e}{detail}"), "error");}}- (_, "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),+ (_, "cancelled") | (Err(_), _) => self.stop_notice("Stopped.", "cancelled"),+ (_, "max_tokens") => self.stop_notice("The agent hit its output limit.", "max_tokens"),+ (_, "max_turn_requests") => {+ self.stop_notice("The agent hit its step limit for this turn.", "max_turn_requests");+ }+ (_, "refusal") => self.stop_notice("The agent declined to continue.", "refusal"),(Ok(_), "end_turn") if !stopped => crate::market::agent_sign_in::answered(&self.hub, &self.cfg.backend),_ => {}}@@ -398,6 +400,11 @@ impl Actor {}impl Actor {+ /// Says why the running turn ended early; `stopReason` tells scripts (`codync-host send`) without the words.+ fn stop_notice(&self, text: &str, reason: &str) {+ self.notice_data(json!({"text": text, "style": NoticeStyle::Info, "stopReason": reason}));+ }+/// Ends what an attempt left open: file shares, the last text, unanswered permission cards (they can't be/// answered after the turn) and tool calls the agent never closed out (they'd spin forever in the trace).pub(super) fn close_attempt(&mut self, failed: bool) {diff --git a/host/src/api/events.rs b/host/src/api/events.rsindex acff56a6..7ec5d147 100644--- a/host/src/api/events.rs+++ b/host/src/api/events.rs@@ -68,6 +68,8 @@ pub fn events_stream(}catch_up.extend(crate::chat::artifacts::since(&hub.store, since));catch_up.sort_by_key(|v| v["rev"].as_i64().unwrap_or(0));+ // What the voice of a call this device holds should have heard while it was away.+ catch_up.extend(crate::chat::calls::replay(caller.device_key()));let hello = json!({"type": "hello","hostId": hub.host_id,@@ -77,10 +79,10 @@ pub fn events_stream("screen": hub.screen.state(),// Live state like the two above: a `network` event sent before this stream began is in it."network": crate::network::status(hub),+ // How many catch-up events follow: `rev` can be ahead of all of them (a write no event carries).+ "catchUp": catch_up.len(),});catch_up.insert(0, hello);- // What the voice of a call this device holds should have heard while it was away.- catch_up.extend(crate::chat::calls::replay(caller.device_key()));let local = matches!(caller, Caller::Local);let key = caller.device_key().to_owned();diff --git a/host/src/main.rs b/host/src/main.rsindex 6511433b..168e407f 100644--- a/host/src/main.rs+++ b/host/src/main.rs@@ -17,6 +17,7 @@ mod remote;mod routines;mod screen;mod secret_prompt;+mod send_cli;mod service;mod shell;mod store;@@ -161,6 +162,8 @@ enum Sub {},/// Rotate the local API token used by this computer's own apps and helpers.ResetToken,+ /// Send a message to a bot, optionally waiting for its reply.+ Send(send_cli::SendArgs),/// Message your bots from this terminal.Tui {/// Host to connect to (default: this computer). The API only answers local@@ -344,6 +347,7 @@ async fn main() -> Result<()> {Sub::Serve { port, bind } => serve(&bind, port).await,Sub::Pair { port, json } => pair(port, json).await,Sub::Info { port, json } => info(port, json).await,+ Sub::Send(args) => send_cli::run(args).await,Sub::Devices { port, action } => match action.unwrap_or(DevicesAction::List) {DevicesAction::List => {let v = local_call(port, "devices", json!({})).await?;@@ -567,10 +571,12 @@ async fn shutdown_signal() {}}+/// What a local command says when it can't reach the running host.+const NOT_RUNNING: &str = "codync-host isn't running here. Start it with `codync-host install` (or `serve`).";+/// Calls the running host's local API (`~/.codync/token` over loopback).async fn local_call(port: u16, method: &str, body: serde_json::Value) -> Result<serde_json::Value> {- let not_running =- || anyhow::anyhow!("codync-host isn't running here. Start it with `codync-host install` (or `serve`).");+ let not_running = || anyhow::anyhow!(NOT_RUNNING);let token = std::fs::read_to_string(service::data_dir().join("token")).map_err(|_| not_running())?;let res = http().post(format!("http://127.0.0.1:{port}/api/{method}"))diff --git a/host/src/send_cli.rs b/host/src/send_cli.rsnew file mode 100644index 00000000..1f21ae34--- /dev/null+++ b/host/src/send_cli.rs@@ -0,0 +1,284 @@+//! `codync-host send`: messages a bot through the running host, optionally waiting for its reply, without owning or+//! stopping the bot's work.++mod events;+mod wait;++use crate::tui::net::Client;+use anyhow::Result;+use events::BotFeed;+use serde::{Deserialize, Serialize};+use serde_json::{Value, json};+use std::io::Read;+use std::path::PathBuf;+use std::time::{Duration, Instant};++#[derive(clap::Args)]+#[command(+ after_long_help = "Exit codes:\n 0 Completed (or accepted, without --wait)\n 1 Stopped, limited, declined, or failed\n 2 Invalid arguments, missing bot, ambiguous name, or --wait on a group chat\n 3 Host unavailable or API request refused\n 4 Timed out; the bot is not stopped\n\nJSON is emitted after a message is accepted. Earlier errors go to stderr."+)]+pub struct SendArgs {+ /// Bot ID, or an exact name (case-insensitive; duplicate names require an ID).+ #[arg(long, value_name = "ID-OR-NAME")]+ bot: String,+ /// Read a UTF-8 message file; use - to read stdin instead.+ #[arg(long, value_name = "PATH", conflicts_with = "text")]+ file: Option<PathBuf>,+ /// Message words, joined by spaces; mutually exclusive with --file.+ #[arg(value_name = "TEXT", num_args = 1.., required_unless_present = "file", conflicts_with = "file")]+ text: Vec<String>,+ /// Wait for the turn that answers the message to end, and print its reply (not for group chats).+ #[arg(long)]+ wait: bool,+ /// Active wait limit in seconds; time waiting for approval is excluded.+ #[arg(long, default_value_t = 1800, value_parser = clap::value_parser!(u64).range(1..), value_name = "SECS")]+ timeout: u64,+ /// Print one JSON object instead of plain text.+ #[arg(long)]+ json: bool,+ /// Quote-reply to this message of the bot's chat: an `entryId` or `replyId` from an earlier --json result.+ #[arg(long, value_name = "ENTRY-ID")]+ reply_to: Option<String>,+ /// Local host port (development builds use their own default).+ #[arg(long, default_value_t = crate::service::DEFAULT_PORT)]+ port: u16,+}++/// The exit codes `--help` documents.+#[derive(Clone, Copy)]+enum Exit {+ Completed = 0,+ Failed = 1,+ Usage = 2,+ Unavailable = 3,+ Timeout = 4,+}++/// Why the command ends before it has a result to print.+struct Failure {+ exit: Exit,+ message: String,+}++impl Failure {+ /// The host can't be reached, or refused a request.+ fn host(message: impl Into<String>) -> Self {+ Self { exit: Exit::Unavailable, message: message.into() }+ }++ fn usage(message: impl Into<String>) -> Self {+ Self { exit: Exit::Usage, message: message.into() }+ }+}++#[derive(Serialize)]+#[serde(rename_all = "lowercase")]+enum Status {+ Completed,+ Failed,+ Timeout,+}++/// Why a turn ended: the agent's stop reason as the host's notices carry it (`stopReason`).+#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+enum StopReason {+ EndTurn,+ Cancelled,+ MaxTokens,+ MaxTurnRequests,+ Refusal,+ StartFailed,+ Error,+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+struct Report {+ bot_id: String,+ entry_id: String,+ entry_seq: i64,+ turn: i64,+ status: Status,+ #[serde(skip_serializing_if = "Option::is_none")]+ stop_reason: Option<StopReason>,+ #[serde(skip_serializing_if = "Option::is_none")]+ reply: Option<String>,+ /// The reply's last message, which `--reply-to` can quote.+ #[serde(skip_serializing_if = "Option::is_none")]+ reply_id: Option<String>,+ notices: Vec<String>,+ elapsed_seconds: f64,+ waited_for_approval_seconds: f64,+}++impl Report {+ fn accepted(bot: &str, entry: &Value, started: Instant) -> Result<Self, Failure> {+ let invalid = || Failure::host("the host returned an invalid message");+ Ok(Self {+ bot_id: bot.to_owned(),+ entry_id: entry["id"].as_str().ok_or_else(invalid)?.to_owned(),+ entry_seq: entry["seq"].as_i64().ok_or_else(invalid)?,+ turn: entry["turn"].as_i64().ok_or_else(invalid)?,+ status: Status::Completed,+ stop_reason: None,+ reply: None,+ reply_id: None,+ notices: Vec::new(),+ elapsed_seconds: started.elapsed().as_secs_f64(),+ waited_for_approval_seconds: 0.0,+ })+ }++ /// Records a notice and says it on stderr.+ fn note(&mut self, text: String) {+ eprintln!("{text}");+ self.notices.push(text);+ }++ fn emit(&self, args: &SendArgs, token: &str) -> Exit {+ if args.json {+ let Ok(text) = serde_json::to_string(self) else {+ eprintln!("couldn't encode the send result");+ return Exit::Failed;+ };+ println!("{}", redact(&text, token));+ } else if args.wait {+ if let Some(reply) = &self.reply {+ println!("{}", redact(reply.trim_end_matches(['\r', '\n']), token));+ }+ } else {+ println!("id={} seq={} turn={}", self.entry_id, self.entry_seq, self.turn);+ }+ match self.status {+ Status::Completed => Exit::Completed,+ Status::Failed => Exit::Failed,+ Status::Timeout => Exit::Timeout,+ }+ }+}++/// `codync-host send`: exits with the code `--help` documents.+pub async fn run(args: SendArgs) -> Result<()> {+ let exit = execute(&args).await.unwrap_or_else(|e| {+ eprintln!("{}", e.message);+ e.exit+ });+ if !matches!(exit, Exit::Completed) {+ std::process::exit(exit as i32);+ }+ Ok(())+}++async fn execute(args: &SendArgs) -> Result<Exit, Failure> {+ // A file or stdin read blocks: off the async workers.+ let (file, words) = (args.file.clone(), args.text.clone());+ let text = tokio::task::spawn_blocking(move || read_message(file.as_deref(), &words))+ .await+ .map_err(|_| Failure::usage("couldn't read the message"))??;+ let base = format!("http://127.0.0.1:{}", args.port);+ let token = Client::new(&base, None).token().ok_or_else(|| Failure::host(crate::NOT_RUNNING))?;+ let mut feed = BotFeed::connect(&base, &token).await?;+ let bots = feed.bots();+ let bot = resolve_bot(&args.bot, &bots)?;+ if args.wait && bot["kind"] == "group" {+ return Err(Failure::usage("--wait doesn't support group chats"));+ }+ let bot = bot["id"].as_str().unwrap_or_default();+ let started = Instant::now();+ if args.wait {+ feed.track(bot);+ }+ let mut body = json!({"botId": bot, "text": text, "clientNonce": uuid::Uuid::new_v4().to_string()});+ if let Some(id) = &args.reply_to {+ body["replyTo"] = id.as_str().into();+ }+ let answer = send(&base, &token, &body).await?;+ let mut report = Report::accepted(bot, &answer["entry"], started)?;+ if args.wait+ && let Err(e) = wait::reply(args, &token, &mut feed, &mut report).await+ {+ // The message was accepted: the result still says which one, and why the wait ended.+ let (elapsed, approval) = feed.timing();+ report.elapsed_seconds = elapsed.as_secs_f64();+ report.waited_for_approval_seconds = approval.as_secs_f64();+ report.status = Status::Failed;+ report.stop_reason = Some(StopReason::Error);+ report.note(redact(&e.message, &token));+ report.emit(args, &token);+ return Ok(e.exit);+ }+ Ok(report.emit(args, &token))+}++/// Sends the message. The host keeps one message per `clientNonce`, so one whose answer never came back (the host was+/// restarting, or the connection dropped) is sent again with the same nonce; one the host refused is not.+async fn send(base: &str, token: &str, body: &Value) -> Result<Value, Failure> {+ let mut attempts = 1;+ loop {+ let sent = crate::http()+ .post(format!("{base}/api/send"))+ .bearer_auth(token)+ .json(body)+ .timeout(Duration::from_secs(20))+ .send()+ .await;+ let answer = match sent {+ Ok(res) if !res.status().is_success() => {+ let refused: Value = res.json().await.unwrap_or_default();+ return Err(Failure::host(redact(refused["error"].as_str().unwrap_or("the host refused"), token)));+ }+ Ok(res) => res.json::<Value>().await.ok(),+ Err(_) => None,+ };+ match answer {+ Some(answer) => return Ok(answer),+ None if attempts == 3 => return Err(Failure::host(crate::NOT_RUNNING)),+ None => attempts += 1,+ }+ tokio::time::sleep(Duration::from_millis(250)).await;+ }+}++fn read_message(file: Option<&std::path::Path>, words: &[String]) -> Result<String, Failure> {+ let message = match file {+ Some(path) if path.as_os_str() == "-" => {+ let mut text = String::new();+ std::io::stdin()+ .read_to_string(&mut text)+ .map_err(|_| Failure::usage("couldn't read a UTF-8 message from stdin"))?;+ text+ }+ Some(path) => {+ std::fs::read_to_string(path).map_err(|_| Failure::usage("couldn't read the UTF-8 message file"))?+ }+ None => words.join(" "),+ };+ if message.trim().is_empty() {+ return Err(Failure::usage("a nonempty message is required"));+ }+ Ok(message)+}++/// The bot `query` names: by ID, or else by its exact name ignoring case when no other bot has that name.+fn resolve_bot<'a>(query: &str, bots: &'a [Value]) -> Result<&'a Value, Failure> {+ if let Some(bot) = bots.iter().find(|bot| bot["id"] == query) {+ return Ok(bot);+ }+ let name = query.to_lowercase();+ let named: Vec<&Value> =+ bots.iter().filter(|b| b["name"].as_str().is_some_and(|n| n.to_lowercase() == name)).collect();+ match named.as_slice() {+ [] => Err(Failure::usage("no bot matches that ID or name")),+ [bot] => Ok(bot),+ _ => {+ let ids: Vec<&str> = named.iter().filter_map(|b| b["id"].as_str()).collect();+ Err(Failure::usage(format!("ambiguous bot name; use an ID: {}", ids.join(", "))))+ }+ }+}++/// `text` without this computer's API token, which nothing the command prints may reveal.+fn redact(text: &str, token: &str) -> String {+ text.replace(token, "[redacted]")+}diff --git a/host/src/send_cli/events.rs b/host/src/send_cli/events.rsnew file mode 100644index 00000000..fb99daf0--- /dev/null+++ b/host/src/send_cli/events.rs@@ -0,0 +1,301 @@+//! The host's event stream as the apps read it: bot snapshots, approval cards and the tracked bot's chat.++use super::{Failure, redact};+use futures::StreamExt;+use serde_json::Value;+use std::collections::{BTreeMap, HashMap, HashSet};+use std::time::{Duration, Instant};+use tokio::sync::watch;++#[derive(Default, PartialEq, Eq)]+enum Phase {+ /// Reading the catch-up.+ #[default]+ Loading,+ Ready,+ /// The running host is older than this command: its `hello` doesn't say how long the catch-up is.+ Outdated,+ /// Why the event stream ended.+ Disconnected(String),+}++/// How a tracked turn ended, as the bot's status said.+#[derive(Clone, Copy, PartialEq, Eq)]+pub(super) enum Settled {+ Idle,+ Error,+}++#[derive(Default)]+struct State {+ phase: Phase,+ bots: BTreeMap<String, Value>,+ permissions: HashMap<String, Value>,+ tracking: Option<Tracking>,+}++/// The bot `--wait` follows: its chat since tracking began, and which turn took each sent message.+struct Tracking {+ bot: String,+ started: Instant,+ entries: BTreeMap<i64, Value>,+ /// Messages seen waiting in the queue: only one of these going out starts a turn (a reaction or edit to an older+ /// message re-sends it as `sent`).+ queued: HashSet<String>,+ starting: Vec<(String, i64)>,+ assigned: HashMap<String, i64>,+ active_turn: Option<i64>,+ settled: HashMap<i64, Settled>,+ paused: Duration,+ pause_started: Option<Instant>,+}++impl Tracking {+ fn new(bot: &str) -> Self {+ Self {+ bot: bot.to_owned(),+ started: Instant::now(),+ entries: BTreeMap::new(),+ queued: HashSet::new(),+ starting: Vec::new(),+ assigned: HashMap::new(),+ active_turn: None,+ settled: HashMap::new(),+ paused: Duration::ZERO,+ pause_started: None,+ }+ }++ /// Time since tracking began, and how much of it an approval held.+ fn timing(&self) -> (Duration, Duration) {+ let approval = self.paused + self.pause_started.map_or(Duration::ZERO, |start| start.elapsed());+ (self.started.elapsed(), approval)+ }+}++pub(super) struct Progress {+ pub bot: Value,+ pub entries: Vec<Value>,+ pub approvals: Vec<Value>,+ pub turn: Option<i64>,+ pub settled: Option<Settled>,+ pub elapsed: Duration,+ pub approval: Duration,+ /// Waiting for an approval (the timeout's clock is stopped).+ pub pending: bool,+}++pub(super) struct BotFeed {+ sender: watch::Sender<State>,+ receiver: watch::Receiver<State>,+ task: tokio::task::JoinHandle<()>,+}++impl Drop for BotFeed {+ fn drop(&mut self) {+ self.task.abort();+ }+}++impl BotFeed {+ /// Opens the event stream and reads its catch-up.+ pub async fn connect(base: &str, token: &str) -> Result<Self, Failure> {+ let request = crate::http().get(format!("{base}/events?since=0&client=cli-send")).bearer_auth(token).send();+ let response = tokio::time::timeout(Duration::from_secs(20), request)+ .await+ .ok()+ .and_then(Result::ok)+ .ok_or_else(|| Failure::host(crate::NOT_RUNNING))?;+ if !response.status().is_success() {+ let body: Value = response.json().await.unwrap_or_default();+ return Err(Failure::host(redact(body["error"].as_str().unwrap_or("the host refused"), token)));+ }+ let (sender, receiver) = watch::channel(State::default());+ let writer = sender.clone();+ let task = tokio::spawn(async move {+ let why = read_events(response, &writer).await;+ writer.send_modify(|s| s.phase = Phase::Disconnected(why));+ });+ let mut feed = Self { sender, receiver, task };+ tokio::time::timeout(Duration::from_secs(20), async {+ loop {+ match &feed.receiver.borrow().phase {+ Phase::Ready => return Ok(()),+ Phase::Outdated => {+ return Err(Failure::host("the running host is older than this command; restart it"));+ }+ Phase::Disconnected(why) => return Err(disconnected(why)),+ Phase::Loading => {}+ }+ feed.changed().await?;+ }+ })+ .await+ .map_err(|_| Failure::host("couldn't read the host's bot snapshot"))??;+ Ok(feed)+ }++ pub fn bots(&self) -> Vec<Value> {+ self.receiver.borrow().bots.values().filter(|b| b["deleted"] != true).cloned().collect()+ }++ pub fn track(&self, bot: &str) {+ self.sender.send_modify(|s| {+ s.tracking = Some(Tracking::new(bot));+ s.update_pause();+ });+ }++ /// Where the turn answering sent message `entry` stands.+ pub fn progress(&self, entry: &str) -> Result<Progress, Failure> {+ let state = self.receiver.borrow();+ if let Phase::Disconnected(why) = &state.phase {+ return Err(disconnected(why));+ }+ let tracked = state.tracking.as_ref().expect("track is called before waiting");+ let turn = tracked.assigned.get(entry).copied();+ let (elapsed, approval) = tracked.timing();+ Ok(Progress {+ bot: state.bots.get(&tracked.bot).cloned().unwrap_or(Value::Null),+ entries: tracked.entries.values().cloned().collect(),+ approvals: state+ .permissions+ .values()+ .filter(|p| p["botId"] == tracked.bot && p["data"]["status"] == "pending")+ .cloned()+ .collect(),+ turn,+ settled: turn.and_then(|turn| tracked.settled.get(&turn).copied()),+ elapsed,+ approval,+ pending: tracked.pause_started.is_some(),+ })+ }++ pub fn timing(&self) -> (Duration, Duration) {+ self.receiver.borrow().tracking.as_ref().expect("track is called before waiting").timing()+ }++ pub async fn changed(&mut self) -> Result<(), Failure> {+ self.receiver.changed().await.map_err(|_| Failure::host("the host event stream disconnected"))+ }+}++impl State {+ fn entry(&mut self, entry: &Value) {+ let kind = entry["kind"].as_str().unwrap_or_default();+ if kind == "permission"+ && let Some(id) = entry["id"].as_str()+ && self.permissions.get(id).is_none_or(|old| old["rev"].as_i64() <= entry["rev"].as_i64())+ {+ self.permissions.insert(id.to_owned(), entry.clone());+ }+ let Some(tracked) = self.tracking.as_mut().filter(|t| entry["botId"] == t.bot) else { return };+ if !matches!(kind, "user" | "agent" | "notice") {+ return;+ }+ if kind == "user"+ && let Some(id) = entry["id"].as_str()+ {+ match entry["data"]["status"].as_str() {+ Some("queued") => {+ tracked.queued.insert(id.to_owned());+ }+ Some("sent") if tracked.queued.remove(id) => {+ if let Some(turn) = entry["turn"].as_i64() {+ tracked.starting.push((id.to_owned(), turn));+ }+ }+ _ => {}+ }+ }+ if let Some(seq) = entry["seq"].as_i64()+ && tracked.entries.get(&seq).is_none_or(|old| old["rev"].as_i64() <= entry["rev"].as_i64())+ {+ tracked.entries.insert(seq, entry.clone());+ }+ }++ fn event(&mut self, event: &Value) {+ match event["type"].as_str() {+ Some("bot") => self.bot(&event["bot"]),+ Some("entry") => self.entry(&event["entry"]),+ _ => {}+ }+ self.update_pause();+ }++ fn bot(&mut self, bot: &Value) {+ let Some(id) = bot["id"].as_str() else { return };+ if self.bots.get(id).is_some_and(|old| old["rev"].as_i64() > bot["rev"].as_i64()) {+ return;+ }+ self.bots.insert(id.to_owned(), bot.clone());+ let Some(t) = self.tracking.as_mut().filter(|t| t.bot == id) else { return };+ let settled = match bot["status"].as_str() {+ Some("idle") => Some(Settled::Idle),+ Some("error") => Some(Settled::Error),+ _ => None,+ };+ if bot["status"] == "working" && !t.starting.is_empty() {+ // Consecutive queued messages in one lane become one host turn: the last one's (`start_turn`), whose `sent`+ // comes last. Not the highest: two sends at once can queue in the other order than their turns.+ let turn = t.starting.last().map(|(_, turn)| *turn).expect("nonempty batch");+ for (id, _) in t.starting.drain(..) {+ t.assigned.insert(id, turn);+ }+ t.active_turn = Some(turn);+ } else if let Some(settled) = settled+ && let Some(turn) = t.active_turn.take()+ {+ t.settled.insert(turn, settled);+ }+ }++ fn update_pause(&mut self) {+ let Some(t) = self.tracking.as_mut() else { return };+ let pending = self.bots.get(&t.bot).is_some_and(|b| b["status"] == "needsInput")+ && self.permissions.values().any(|p| p["botId"] == t.bot && p["data"]["status"] == "pending");+ if pending {+ t.pause_started.get_or_insert_with(Instant::now);+ } else if let Some(start) = t.pause_started.take() {+ t.paused += start.elapsed();+ }+ }+}++fn disconnected(why: &str) -> Failure {+ Failure::host(format!("the host event stream disconnected: {why}"))+}++/// Reads events into `sender` until the stream ends, and says why it did.+async fn read_events(response: reqwest::Response, sender: &watch::Sender<State>) -> String {+ let mut events = std::pin::pin!(crate::tui::net::sse_values(response));+ // Catch-up events still to come, once `hello` has said how many.+ let mut left = None;+ while let Some(event) = events.next().await {+ let event = match event {+ Ok(event) => event,+ Err(e) => return e.to_string(),+ };+ // A lagged stream lost turn transitions that a current bot snapshot can't bring back.+ if event["type"] == "resync" {+ return "it fell behind".to_owned();+ }+ sender.send_modify(|s| {+ if event["type"] == "hello" {+ left = event["catchUp"].as_u64();+ if left.is_none() {+ s.phase = Phase::Outdated;+ }+ } else {+ s.event(&event);+ left = left.map(|n| n.saturating_sub(1));+ }+ if left == Some(0) {+ s.phase = Phase::Ready;+ }+ });+ }+ "the host closed it".to_owned()+}diff --git a/host/src/send_cli/wait.rs b/host/src/send_cli/wait.rsnew file mode 100644index 00000000..e489f6e0--- /dev/null+++ b/host/src/send_cli/wait.rs@@ -0,0 +1,128 @@+//! `--wait`: follows the turn that answers the sent message until the bot settles, and never stops it.++use super::events::{BotFeed, Progress, Settled};+use super::{Failure, Report, SendArgs, Status, StopReason, redact};+use serde_json::Value;+use std::collections::HashSet;+use std::time::Duration;++pub(super) async fn reply(+ args: &SendArgs,+ token: &str,+ feed: &mut BotFeed,+ report: &mut Report,+) -> Result<(), Failure> {+ let mut printed = HashSet::new();+ loop {+ let progress = feed.progress(&report.entry_id)?;+ report.elapsed_seconds = progress.elapsed.as_secs_f64();+ report.waited_for_approval_seconds = progress.approval.as_secs_f64();+ if let Some(turn) = progress.turn {+ report.turn = turn;+ }+ print_new(&progress, report, token, &mut printed);+ if finish(&progress, report) {+ return Ok(());+ }+ // An approval the bot waits for stops the clock.+ let left = (!progress.pending).then(|| {+ Duration::from_secs(args.timeout).saturating_sub(progress.elapsed.saturating_sub(progress.approval))+ });+ if left.is_some_and(|left| left.is_zero()) {+ report.status = Status::Timeout;+ eprintln!("timed out after {}s (the bot is still working; nothing was stopped)", args.timeout);+ return Ok(());+ }+ let deadline = async {+ match left {+ Some(left) => tokio::time::sleep(left).await,+ None => std::future::pending().await,+ }+ };+ tokio::select! {+ result = feed.changed() => result?,+ () = deadline => {}+ }+ }+}++/// Says, once each, the approvals the bot waits for and the notices of the answering turn.+fn print_new(progress: &Progress, report: &mut Report, token: &str, printed: &mut HashSet<String>) {+ for card in progress.approvals.iter().filter(|_| progress.pending) {+ if let Some(id) = card["id"].as_str()+ && printed.insert(id.to_owned())+ {+ let title =+ card["data"]["title"].as_str().or_else(|| card["data"]["command"].as_str()).unwrap_or("Use a tool");+ let summary: String = title.lines().next().unwrap_or("Use a tool").chars().take(180).collect();+ eprintln!("waiting for approval: {}", redact(&summary, token));+ }+ }+ for notice in turn_entries(progress, report.entry_seq).filter(|e| e["kind"] == "notice") {+ if let (Some(id), Some(text)) = (notice["id"].as_str(), notice["data"]["text"].as_str())+ && printed.insert(id.to_owned())+ {+ report.note(redact(text, token));+ }+ }+}++/// Whether the wait is over, with the report filled in: the bot is gone, the message left the queue unsent, or the+/// turn that took it ended.+fn finish(progress: &Progress, report: &mut Report) -> bool {+ if progress.bot.is_null() || progress.bot["deleted"] == true {+ return failed(report, StopReason::Error, "The bot was deleted while waiting.");+ }+ let own = progress.entries.iter().find(|e| e["id"] == report.entry_id.as_str());+ if own.is_some_and(|e| e["data"]["status"] == "cancelled") {+ return failed(report, StopReason::Cancelled, "The queued message was cancelled.");+ }+ let Some(settled) = progress.settled else { return false };+ let entries: Vec<&Value> = turn_entries(progress, report.entry_seq).collect();+ // Several messages (send_message bubbles, an artifact card) make one reply, as the host joins them.+ let replies: Vec<&Value> =+ entries.iter().copied().filter(|e| e["kind"] == "agent" && e["data"]["final"] == true).collect();+ let texts: Vec<&str> = replies.iter().filter_map(|e| e["data"]["text"].as_str()).collect();+ report.reply = (!texts.is_empty()).then(|| texts.join("\n\n"));+ report.reply_id = replies.last().and_then(|e| e["id"].as_str()).map(str::to_owned);+ let reason = entries+ .iter()+ .rev()+ .find_map(|e| serde_json::from_value(e["data"]["stopReason"].clone()).ok())+ .unwrap_or(if settled == Settled::Error { StopReason::Error } else { StopReason::EndTurn });+ report.stop_reason = Some(reason);+ if reason != StopReason::EndTurn {+ report.status = Status::Failed;+ if report.notices.is_empty() {+ report.note("The bot entered an error state.".into());+ }+ return true;+ }+ report.status = Status::Completed;+ // A reaction can be the bot's whole answer.+ let reaction = own+ .and_then(|e| e["data"]["botReactions"].as_array())+ .and_then(|reactions| reactions.iter().find(|r| r["bot"] == report.bot_id.as_str()))+ .and_then(|r| r["emoji"].as_str());+ if report.reply.is_none()+ && let Some(emoji) = reaction+ {+ report.note(format!("Reacted {emoji} to the message."));+ }+ true+}++fn failed(report: &mut Report, reason: StopReason, notice: &str) -> bool {+ report.status = Status::Failed;+ report.stop_reason = Some(reason);+ report.note(notice.to_owned());+ true+}++/// The entries of the turn that took the sent message (`sent` its seq), after it, oldest first.+fn turn_entries(progress: &Progress, sent: i64) -> impl Iterator<Item = &Value> {+ let turn = progress.turn;+ progress.entries.iter().filter(move |e| {+ turn.is_some() && e["turn"].as_i64() == turn && e["seq"].as_i64().is_some_and(|seq| seq > sent)+ })+}diff --git a/host/src/tui/mod.rs b/host/src/tui/mod.rsindex e474e5ef..6763ad5b 100644--- a/host/src/tui/mod.rs+++ b/host/src/tui/mod.rs@@ -10,7 +10,7 @@ mod drafts;mod l10n;mod manage;mod md;-mod net;+pub(crate) mod net;mod sheets;mod view;diff --git a/host/src/tui/net.rs b/host/src/tui/net.rsindex bd768296..999bb5fa 100644--- a/host/src/tui/net.rs+++ b/host/src/tui/net.rs@@ -173,19 +173,12 @@ impl Client {let _ = tx.send(Msg::Term(id, json!({"type": "exit", "code": -1})));return;};- let mut body = res.bytes_stream();- let mut buf = Vec::new();- while let Some(Ok(chunk)) = body.next().await {- buf.extend_from_slice(&chunk);- while let Some(i) = buf.iter().position(|&b| b == b'\n') {- let line: Vec<u8> = buf.drain(..=i).collect();- let line = String::from_utf8_lossy(&line);- let Some(data) = line.trim_end().strip_prefix("data:") else { continue };- if let Ok(v) = serde_json::from_str::<Value>(data.trim_start())- && tx.send(Msg::Term(id.clone(), v)).is_err()- {- return;- }+ let mut events = std::pin::pin!(sse_values(res));+ while let Some(v) = events.next().await {+ if let Ok(v) = v+ && tx.send(Msg::Term(id.clone(), v)).is_err()+ {+ return;}}});@@ -237,29 +230,27 @@ impl Client {if tx.send(Msg::Online(true)).is_err() || tx.send(Msg::Connected { since }).is_err() {return;}- let mut body = res.bytes_stream();- let mut buf = Vec::new();- 'read: while let Some(Ok(chunk)) = body.next().await {- buf.extend_from_slice(&chunk);- while let Some(i) = buf.iter().position(|&b| b == b'\n') {- let line: Vec<u8> = buf.drain(..=i).collect();- let line = String::from_utf8_lossy(&line);- let Some(data) = line.trim_end().strip_prefix("data:") else { continue };- let Ok(v) = serde_json::from_str::<Value>(data.trim_start()) else {+ let mut events = std::pin::pin!(sse_values(res));+ while let Some(v) = events.next().await {+ let v = match v {+ Ok(v) => v,+ // A dropped connection reconnects from the last rev, like the stream ending.+ Err(SseError::Read(_)) => break,+ Err(SseError::Json(_)) => {// Never skip what we can't read: start over from scratch.c.rev.store(0, Ordering::Relaxed);let _ = tx.send(Msg::Rewind);- break 'read;- };- if v["type"] == "resync" {- break 'read;- }- if let Some(rev) = v["rev"].as_i64() {- c.rev.fetch_max(rev, Ordering::Relaxed);- }- if tx.send(Msg::Event(v)).is_err() {- return;+ break;}+ };+ if v["type"] == "resync" {+ break;+ }+ if let Some(rev) = v["rev"].as_i64() {+ c.rev.fetch_max(rev, Ordering::Relaxed);+ }+ if tx.send(Msg::Event(v)).is_err() {+ return;}}}@@ -272,6 +263,51 @@ impl Client {}}+/// Why an event stream gave something other than an event.+pub enum SseError {+ /// The connection failed; the stream ends after it.+ Read(reqwest::Error),+ /// An event that isn't JSON.+ Json(serde_json::Error),+}++impl std::fmt::Display for SseError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Self::Read(e) => write!(f, "{e}"),+ Self::Json(e) => write!(f, "an event that isn't JSON ({e})"),+ }+ }+}++/// The JSON of each `data:` line of a server-sent event stream until it ends.+pub fn sse_values(res: reqwest::Response) -> impl futures::Stream<Item = Result<Value, SseError>> {+ let body = Box::pin(res.bytes_stream());+ let lines = futures::stream::unfold(Some((body, Vec::new())), |state| async move {+ let (mut body, mut buf) = state?;+ loop {+ if let Some(i) = buf.iter().position(|&b| b == b'\n') {+ let line: Vec<u8> = buf.drain(..=i).collect();+ return Some((Ok(line), Some((body, buf))));+ }+ match body.next().await? {+ Ok(chunk) => buf.extend_from_slice(&chunk),+ Err(e) => return Some((Err(SseError::Read(e)), None)),+ }+ }+ });+ lines.filter_map(|line| async move {+ let line = match line {+ Ok(line) => line,+ Err(e) => return Some(Err(e)),+ };+ let line = String::from_utf8_lossy(&line);+ line.trim_end()+ .strip_prefix("data:")+ .map(|data| serde_json::from_str(data.trim_start()).map_err(SseError::Json))+ })+}+/// `dir/name`, or `name (2)` … when that's taken. The name is only its last part (no `../`).fn free_path(dir: &std::path::Path, name: &str) -> PathBuf {// Only the last plain component: a drive prefix ("C:x") or parent can't escape `dir`.diff --git a/host/tests/common/host.rs b/host/tests/common/host.rsindex f11ae30f..b7c0d853 100644--- a/host/tests/common/host.rs+++ b/host/tests/common/host.rs@@ -14,8 +14,9 @@ pub struct Host {child: Child,/// The host's `CODYNC_HOME`.pub home: PathBuf,- base: String,- token: String,+ /// `http://127.0.0.1:<port>`.+ pub base: String,+ pub token: String,}impl Drop for Host {diff --git a/host/tests/fixtures/send_cli_agent.py b/host/tests/fixtures/send_cli_agent.pynew file mode 100644index 00000000..08b8430f--- /dev/null+++ b/host/tests/fixtures/send_cli_agent.py@@ -0,0 +1,97 @@+"""Small ACP fixture for non-interactive send, permission, and cancellation tests."""++import json+import re+import sys+import threading+import time++sys.stdin.reconfigure(encoding="utf-8")+sys.stdout.reconfigure(encoding="utf-8")+lock = threading.Lock()+permissions = {}+prompts = {}+sessions = 0+++def send(value):+ with lock:+ print(json.dumps({"jsonrpc": "2.0", **value}), flush=True)+++def update(session, kind, text):+ send({"method": "session/update", "params": {+ "sessionId": session,+ "update": {"sessionUpdate": kind, "content": {"type": "text", "text": text}},+ }})+++def turn(message):+ rid = message["id"]+ session = message["params"]["sessionId"]+ text = "\n".join(block.get("text", "") for block in message["params"]["prompt"])+ # A quote reply's note repeats the quoted message; only the latest command is current.+ modes = re.findall(r"CLI_MODE=([a-z_]+)", text)+ mode = modes[-1] if modes else "normal"+ event = threading.Event()+ prompts[rid] = (session, event)+ if mode == "hang":+ update(session, "agent_thought_chunk", "Waiting indefinitely")+ event.wait(120)+ return+ if mode == "error":+ send({"id": rid, "error": {"code": -32000, "message": "fixture failure"}})+ prompts.pop(rid, None)+ return+ if mode == "silent":+ send({"id": rid, "result": {"stopReason": "end_turn"}})+ prompts.pop(rid, None)+ return+ if mode == "hold":+ update(session, "agent_thought_chunk", "OLD is working")+ time.sleep(3)+ reply = "OLD reply"+ elif mode == "permission":+ permission_id = f"permission-{rid}"+ permissions[permission_id] = event+ send({"id": permission_id, "method": "session/request_permission", "params": {+ "sessionId": session,+ "toolCall": {"toolCallId": "permission-tool", "title": "Read fixture files", "kind": "read"},+ "options": [+ {"optionId": "allow", "name": "Allow once", "kind": "allow_once"},+ {"optionId": "reject", "name": "Reject once", "kind": "reject_once"},+ ],+ }})+ if not event.wait(90):+ return+ reply = "Approved reply"+ elif mode == "echo":+ reply = re.findall(r"CLI_TEXT=([^\n]+)", text)[-1]+ else:+ reply = "CLI reply"+ update(session, "agent_message_chunk", reply)+ reason = mode if mode in {"max_tokens", "max_turn_requests", "refusal"} else "end_turn"+ send({"id": rid, "result": {"stopReason": reason}})+ prompts.pop(rid, None)+++for line in sys.stdin:+ message = json.loads(line)+ method = message.get("method")+ if method is None:+ event = permissions.pop(message.get("id"), None)+ if event:+ event.set()+ elif method == "initialize":+ send({"id": message["id"], "result": {"protocolVersion": 1, "agentCapabilities": {}}})+ elif method == "session/new":+ sessions += 1+ send({"id": message["id"], "result": {"sessionId": f"cli-session-{sessions}"}})+ elif method == "session/prompt":+ threading.Thread(target=turn, args=(message,), daemon=True).start()+ elif method == "session/cancel":+ for rid, (session, event) in list(prompts.items()):+ if session == message["params"]["sessionId"]:+ prompts.pop(rid, None)+ send({"id": rid, "result": {"stopReason": "cancelled"}})+ event.set()diff --git a/host/tests/fixtures/wire-shape.json b/host/tests/fixtures/wire-shape.jsonindex 1fc2d405..b05e103b 100644--- a/host/tests/fixtures/wire-shape.json+++ b/host/tests/fixtures/wire-shape.json@@ -179,6 +179,7 @@"event:entry(user).rev": "number","event:entry(user).type": "string","event:hello": "object",+ "event:hello.catchUp": "number","event:hello.computerId": "string","event:hello.hostId": "string","event:hello.network": "object",diff --git a/host/tests/send_cli_e2e.rs b/host/tests/send_cli_e2e.rsnew file mode 100644index 00000000..f911d6b5--- /dev/null+++ b/host/tests/send_cli_e2e.rs@@ -0,0 +1,284 @@+//! A real host and fake ACP agent exercised through the non-interactive CLI.++#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]++mod common;+#[path = "send_cli_e2e/support.rs"]+mod support;+#[path = "send_cli_e2e/transport.rs"]+mod transport;++use serde_json::json;+use std::time::{Duration, Instant};+use support::{Host, json_output};+use transport::{MockHost, Mode};++#[tokio::test]+async fn sends_plain_text_json_and_an_unwaited_acknowledgement() {+ let host = Host::start().await;+ let bot = host.bot("Worker").await;+ let plain = host.run(&["--bot", &bot, "--wait", "CLI_MODE=normal"]).await;+ assert_eq!(plain.status.code(), Some(0), "{}", String::from_utf8_lossy(&plain.stderr));+ assert_eq!(String::from_utf8(plain.stdout).unwrap(), "CLI reply\n");+ let output = host.run(&["--bot", &bot, "--wait", "--json", "CLI_MODE=normal"]).await;+ let result = json_output(&output, 0);+ assert_eq!(result["botId"], bot);+ assert_eq!(result["status"], "completed");+ assert_eq!(result["stopReason"], "end_turn");+ assert_eq!(result["reply"], "CLI reply");+ assert!(result["entrySeq"].as_i64().unwrap() > 0);+ assert!(result["turn"].as_i64().unwrap() > 0);+ assert_eq!(result["notices"].as_array().unwrap().as_slice(), [] as [serde_json::Value; 0]);+ assert!(result["elapsedSeconds"].as_f64().unwrap() >= 0.0);+ assert_eq!(result["waitedForApprovalSeconds"], 0.0);+ assert!(result["entryId"].is_string() && result["replyId"].is_string());+ let ack = host.run(&["--bot", &bot, "CLI_MODE=normal"]).await;+ assert_eq!(ack.status.code(), Some(0));+ let ack = String::from_utf8(ack.stdout).unwrap();+ assert!(ack.starts_with("id=") && ack.contains(" seq=") && ack.contains(" turn="), "{ack}");+}++#[tokio::test]+async fn a_turn_without_a_text_reply_completes_when_the_bot_is_idle() {+ let host = Host::start().await;+ let bot = host.bot("Silent").await;+ let result =+ json_output(&host.run(&["--bot", &bot, "--wait", "--json", "--timeout", "20", "CLI_MODE=silent"]).await, 0);+ assert_eq!(result["status"], "completed");+ assert_eq!(result["stopReason"], "end_turn");+ assert!(result["reply"].is_null() && result["replyId"].is_null());+}++#[tokio::test]+async fn waiting_on_a_group_chat_is_refused_before_sending() {+ let host = Host::start().await;+ let bot = host.bot("Member").await;+ let group = host.call("createBot", json!({"name": "Room", "kind": "group", "members": [bot]})).await["bot"]["id"]+ .as_str()+ .unwrap()+ .to_owned();+ let output = host.run(&["--bot", &group, "--wait", "hello"]).await;+ assert_eq!(output.status.code(), Some(2));+ assert!(String::from_utf8_lossy(&output.stderr).contains("group chats"));+ let history = host.call("history", json!({"botId": group})).await;+ assert!(history["entries"].as_array().unwrap().iter().all(|e| e["kind"] != "user"));+}++#[tokio::test]+async fn returns_failure_for_limits_refusals_agent_errors_and_a_stopped_turn() {+ let host = Host::start().await;+ let bot = host.bot("Failures").await;+ for reason in ["max_turn_requests", "max_tokens", "refusal", "error"] {+ let message = format!("CLI_MODE={reason}");+ let result = json_output(&host.run(&["--bot", &bot, "--wait", "--json", &message]).await, 1);+ assert_eq!(result["status"], "failed");+ assert_eq!(result["stopReason"], reason);+ assert_ne!(result["notices"].as_array().unwrap().as_slice(), [] as [serde_json::Value; 0]);+ }+ let child = host.command(&["--bot", &bot, "--wait", "--json", "CLI_MODE=hang"]).spawn().unwrap();+ host.entry(&bot, |e| e["data"]["text"] == "Waiting indefinitely").await;+ host.call("stop", json!({"botId":bot})).await;+ let output = tokio::time::timeout(Duration::from_secs(30), child.wait_with_output()).await.unwrap().unwrap();+ let result = json_output(&output, 1);+ assert_eq!(result["status"], "failed");+ assert_eq!(result["stopReason"], "cancelled");+}++#[tokio::test]+async fn a_timeout_leaves_the_bot_working() {+ let host = Host::start().await;+ let bot = host.bot("Timeout").await;+ json_output(&host.run(&["--bot", &bot, "--wait", "--json", "CLI_MODE=normal"]).await, 0);+ let started = Instant::now();+ let output = host.run(&["--bot", &bot, "--wait", "--json", "--timeout", "2", "CLI_MODE=hang"]).await;+ let result = json_output(&output, 4);+ assert_eq!(result["status"], "timeout");+ assert!(started.elapsed() < Duration::from_secs(8));+ assert!(+ String::from_utf8_lossy(&output.stderr)+ .contains("timed out after 2s (the bot is still working; nothing was stopped)")+ );+ assert_eq!(common::bot(&host.snapshot().await, &bot)["status"], "working");+ host.call("stop", json!({"botId":bot})).await;+}++#[tokio::test]+async fn approval_wait_is_reported_and_excluded_from_the_timeout() {+ let host = Host::start().await;+ let bot = host.bot("Approval").await;+ json_output(&host.run(&["--bot", &bot, "--wait", "--json", "CLI_MODE=normal"]).await, 0);+ let child =+ host.command(&["--bot", &bot, "--wait", "--json", "--timeout", "2", "CLI_MODE=permission"]).spawn().unwrap();+ let card = host.entry(&bot, |e| e["kind"] == "permission" && e["data"]["status"] == "pending").await;+ tokio::time::sleep(Duration::from_secs(3)).await;+ host.call("respondPermission", json!({"entryId":card["id"],"optionId":"allow"})).await;+ let output = tokio::time::timeout(Duration::from_secs(30), child.wait_with_output()).await.unwrap().unwrap();+ let result = json_output(&output, 0);+ assert_eq!(result["reply"], "Approved reply");+ assert!(result["waitedForApprovalSeconds"].as_f64().unwrap() >= 2.5);+ assert!(result["elapsedSeconds"].as_f64().unwrap() >= 3.0);+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert_eq!(stderr.matches("waiting for approval:").count(), 1);+ assert!(stderr.contains("Read fixture files"));+}++#[tokio::test]+async fn resolves_exact_names_and_rejects_missing_or_ambiguous_names() {+ let host = Host::start().await;+ let first = host.bot("Reviewer").await;+ let result = json_output(&host.run(&["--bot", "rEvIeWeR", "--wait", "--json", "CLI_MODE=normal"]).await, 0);+ assert_eq!(result["botId"], first);+ let missing = host.run(&["--bot", "missing-name", "test"]).await;+ assert_eq!(missing.status.code(), Some(2));+ assert_eq!(missing.stdout, [] as [u8; 0]);+ let second = host.bot("REVIEWER").await;+ let ambiguous = host.run(&["--bot", "reviewer", "test"]).await;+ assert_eq!(ambiguous.status.code(), Some(2));+ let stderr = String::from_utf8_lossy(&ambiguous.stderr);+ assert!(stderr.contains(&first) && stderr.contains(&second));+ json_output(&host.run(&["--bot", &first, "--wait", "--json", "CLI_MODE=normal"]).await, 0);+}++#[tokio::test]+async fn accepts_utf8_files_stdin_and_quote_replies_without_exposing_the_token() {+ let host = Host::start().await;+ let bot = host.bot("Input").await;+ let file = host.home.join("message.txt");+ std::fs::write(&file, "CLI_MODE=echo\nCLI_TEXT=Read-only UTF-8: 測試").unwrap();+ let output = host.run(&["--bot", &bot, "--wait", "--file", file.to_str().unwrap()]).await;+ assert_eq!(output.status.code(), Some(0), "{}", String::from_utf8_lossy(&output.stderr));+ assert_eq!(String::from_utf8(output.stdout).unwrap(), "Read-only UTF-8: 測試\n");+ let output = host.stdin(&bot, "CLI_MODE=echo\nCLI_TEXT=stdin reply").await;+ assert_eq!(output.status.code(), Some(0));+ assert_eq!(String::from_utf8(output.stdout).unwrap(), "stdin reply\n");+ // Quote the reply an earlier result named.+ let earlier = json_output(&host.run(&["--bot", &bot, "--wait", "--json", "CLI_MODE=normal"]).await, 0);+ let quoted = earlier["replyId"].as_str().unwrap();+ let result =+ json_output(&host.run(&["--bot", &bot, "--wait", "--json", "--reply-to", quoted, "CLI_MODE=normal"]).await, 0);+ assert_eq!(result["reply"], "CLI reply");+ let sent = host.entry(&bot, |e| e["id"] == result["entryId"]).await;+ assert_eq!(sent["data"]["replyTo"]["id"], quoted);+ let message = format!("CLI_MODE=echo\nCLI_TEXT={}", host.token);+ let output = host.run(&["--bot", &bot, "--wait", "--json", &message]).await;+ let result = json_output(&output, 0);+ assert_eq!(result["reply"], "[redacted]");+ assert!(!String::from_utf8_lossy(&output.stderr).contains(&host.token));+ assert!(!String::from_utf8_lossy(&output.stdout).contains(&host.token));+}++#[tokio::test]+async fn queued_calls_wait_for_their_combined_turn_instead_of_an_older_reply() {+ let host = Host::start().await;+ let bot = host.bot("Queue").await;+ host.call("send", json!({"botId":bot,"text":"CLI_MODE=hold"})).await;+ host.entry(&bot, |e| e["data"]["text"] == "OLD is working").await;+ let first = host.command(&["--bot", &bot, "--wait", "--json", "CLI_MODE=normal"]).spawn().unwrap();+ let second = host.command(&["--bot", &bot, "--wait", "--json", "CLI_MODE=normal"]).spawn().unwrap();+ let (first, second) = tokio::time::timeout(Duration::from_secs(30), async {+ tokio::join!(first.wait_with_output(), second.wait_with_output())+ })+ .await+ .unwrap();+ let first = json_output(&first.unwrap(), 0);+ let second = json_output(&second.unwrap(), 0);+ assert_eq!(first["reply"], "CLI reply");+ assert_eq!(second["reply"], "CLI reply");+ assert_eq!(first["turn"], second["turn"]);+ assert_ne!(first["entrySeq"], second["entrySeq"]);+}++#[tokio::test]+async fn help_arguments_and_unreachable_hosts_use_the_documented_exit_codes() {+ let host = Host::start().await;+ let help = host.run(&["--help"]).await;+ assert_eq!(help.status.code(), Some(0));+ let help = String::from_utf8(help.stdout).unwrap();+ for flag in ["--bot", "--file", "--wait", "--timeout", "--json", "--reply-to", "--port", "Exit codes:"] {+ assert!(help.contains(flag), "help must describe {flag}");+ }+ for args in [+ vec!["--bot", "missing"],+ vec!["--bot", "missing", "--file", "-", "text"],+ vec!["--bot", "missing", "--timeout", "0", "text"],+ ] {+ assert_eq!(host.run(&args).await.status.code(), Some(2));+ }+ let invalid = host.home.join("invalid.txt");+ std::fs::write(&invalid, [0xff]).unwrap();+ assert_eq!(host.run(&["--bot", "missing", "--file", invalid.to_str().unwrap()]).await.status.code(), Some(2));+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let port = listener.local_addr().unwrap().port().to_string();+ drop(listener);+ let output = host.run(&["--port", &port, "--bot", "missing", "text"]).await;+ assert_eq!(output.status.code(), Some(3));+ assert_eq!(output.stdout, [] as [u8; 0]);+ assert!(String::from_utf8_lossy(&output.stderr).contains("codync-host isn't running here. Start it with"));+ assert!(!String::from_utf8_lossy(&output.stderr).contains(&host.token));+}++#[tokio::test]+async fn a_reply_joins_its_messages_once_the_working_turn_is_idle() {+ let host = Host::start().await;+ let mock = MockHost::start(Mode::EarlyFinal, &host.token).await;+ let started = Instant::now();+ let output = host.run(&["--port", &mock.port, "--bot", "Transport", "--wait", "--json", "test"]).await;+ let result = json_output(&output, 0);+ assert_eq!(result["reply"], "Early final\n\nSecond bubble");+ assert_eq!(result["replyId"], "second");+ assert!(started.elapsed() >= Duration::from_millis(1100));+ assert!(result["elapsedSeconds"].as_f64().unwrap() >= 1.1);+}++#[tokio::test]+async fn an_ambiguous_send_response_is_retried_with_the_same_nonce() {+ let host = Host::start().await;+ let mock = MockHost::start(Mode::DroppedResponse, &host.token).await;+ json_output(&host.run(&["--port", &mock.port, "--bot", "Transport", "--json", "test"]).await, 0);+ let requests = mock.requests();+ assert_eq!(requests.len(), 2);+ assert_eq!(requests[0]["clientNonce"], requests[1]["clientNonce"]);+ assert!(uuid::Uuid::parse_str(requests[0]["clientNonce"].as_str().unwrap()).is_ok());+}++#[tokio::test]+async fn a_refused_request_does_not_retry_or_reveal_the_token() {+ let host = Host::start().await;+ let mock = MockHost::start(Mode::Rejected, &host.token).await;+ let output = host.run(&["--port", &mock.port, "--bot", "Transport", "--json", "test"]).await;+ assert_eq!(output.status.code(), Some(3));+ assert_eq!(output.stdout, [] as [u8; 0]);+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(stderr.contains("denied [redacted]"));+ assert!(!stderr.contains(&host.token));+ assert_eq!(mock.requests().len(), 1);+}++#[tokio::test]+async fn lost_events_fail_after_acceptance_without_stopping_the_bot() {+ let host = Host::start().await;+ let mock = MockHost::start(Mode::Resync, &host.token).await;+ let output = host.run(&["--port", &mock.port, "--bot", "Transport", "--wait", "--json", "test"]).await;+ let result = json_output(&output, 3);+ assert_eq!(result["status"], "failed");+ assert_eq!(result["stopReason"], "error");+ assert_eq!(result["notices"][0], "the host event stream disconnected: it fell behind");+ assert!(!String::from_utf8_lossy(&output.stderr).contains(&host.token));+ assert!(!String::from_utf8_lossy(&output.stdout).contains(&host.token));+ assert_eq!(mock.requests().len(), 1);+}++#[tokio::test]+async fn an_approval_from_before_the_send_is_reported_and_pauses_the_clock() {+ let host = Host::start().await;+ let mock = MockHost::start(Mode::PriorApproval, &host.token).await;+ let output =+ host.run(&["--port", &mock.port, "--bot", "Transport", "--wait", "--json", "--timeout", "2", "test"]).await;+ let result = json_output(&output, 0);+ assert_eq!(result["status"], "completed");+ assert!(result["waitedForApprovalSeconds"].as_f64().unwrap() >= 2.5);+ assert_eq!(+ String::from_utf8_lossy(&output.stderr).matches("waiting for approval: Approve earlier work").count(),+ 1+ );+}diff --git a/host/tests/send_cli_e2e/support.rs b/host/tests/send_cli_e2e/support.rsnew file mode 100644index 00000000..db5a5643--- /dev/null+++ b/host/tests/send_cli_e2e/support.rs@@ -0,0 +1,93 @@+//! A real host (`common::host::Host`) and `codync-host send` run against it.++use super::common::host::Host as RealHost;+use serde_json::{Value, json};+use std::path::PathBuf;+use std::process::{Output, Stdio};+use std::sync::{Arc, LazyLock};+use std::time::{Duration, Instant};+use tokio::io::AsyncWriteExt;+use tokio::sync::{OwnedSemaphorePermit, Semaphore};++static HOSTS: LazyLock<Arc<Semaphore>> = LazyLock::new(|| Arc::new(Semaphore::new(1)));++pub struct Host {+ host: RealHost,+ // Dropped after the host has stopped.+ _serial: OwnedSemaphorePermit,+}++impl std::ops::Deref for Host {+ type Target = RealHost;++ fn deref(&self) -> &RealHost {+ &self.host+ }+}++impl Host {+ pub async fn start() -> Self {+ // Isolate process-heavy cases from each other on small Windows runners.+ let serial = HOSTS.clone().acquire_owned().await.unwrap();+ let host = RealHost::start().await;+ host.call("setAnalytics", json!({"enabled":false})).await;+ Self { host, _serial: serial }+ }++ /// A bot running `send_cli_agent.py` that asks before using tools.+ pub async fn bot(&self, name: &str) -> String {+ let fixture = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/send_cli_agent.py");+ let bot = json!({"name":name,"backend":"custom","command":super::common::python_agent(&fixture),+ "permission":"ask","connectors":[],"notify":false});+ self.call("createBot", bot).await["bot"]["id"].as_str().unwrap().to_owned()+ }++ pub fn command(&self, args: &[&str]) -> tokio::process::Command {+ let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_codync-host"));+ command.arg("send");+ if !args.contains(&"--port") {+ command.args(["--port", self.base.rsplit(':').next().unwrap()]);+ }+ command+ .env("CODYNC_HOME", &self.home)+ .env("CODYNC_CLOUD", "off")+ .args(args)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .kill_on_drop(true);+ command+ }++ pub async fn run(&self, args: &[&str]) -> Output {+ tokio::time::timeout(Duration::from_secs(45), self.command(args).output()).await.unwrap().unwrap()+ }++ pub async fn stdin(&self, bot: &str, message: &str) -> Output {+ let mut command = self.command(&["--bot", bot, "--file", "-", "--wait"]);+ command.stdin(Stdio::piped());+ let mut child = command.spawn().unwrap();+ child.stdin.take().unwrap().write_all(message.as_bytes()).await.unwrap();+ tokio::time::timeout(Duration::from_secs(45), child.wait_with_output()).await.unwrap().unwrap()+ }++ /// The newest entry of `bot`'s chat that matches, once there is one.+ pub async fn entry(&self, bot: &str, predicate: impl Fn(&Value) -> bool) -> Value {+ let deadline = Instant::now() + Duration::from_secs(30);+ loop {+ let value = self.call("history", json!({"botId":bot})).await;+ if let Some(entry) = value["entries"].as_array().unwrap().iter().rev().find(|entry| predicate(entry)) {+ return entry.clone();+ }+ assert!(Instant::now() < deadline, "missing expected fixture entry");+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ }+}++pub fn json_output(output: &Output, code: i32) -> Value {+ assert_eq!(output.status.code(), Some(code), "stderr: {}", String::from_utf8_lossy(&output.stderr));+ let text = String::from_utf8(output.stdout.clone()).unwrap();+ assert_eq!(text.lines().count(), 1, "JSON output must occupy one line");+ serde_json::from_str(&text).unwrap()+}diff --git a/host/tests/send_cli_e2e/transport.rs b/host/tests/send_cli_e2e/transport.rsnew file mode 100644index 00000000..2eda1e9e--- /dev/null+++ b/host/tests/send_cli_e2e/transport.rs@@ -0,0 +1,134 @@+//! Controlled transport failures and event ordering that a fast real host cannot guarantee.++use axum::body::{Body, Bytes};+use axum::extract::State;+use axum::http::StatusCode;+use axum::response::{IntoResponse, Response, Sse, sse::Event};+use axum::routing::{get, post};+use axum::{Json, Router};+use futures::{Stream, StreamExt};+use serde_json::{Value, json};+use std::convert::Infallible;+use std::sync::{Arc, Mutex};+use std::time::Duration;+use tokio::sync::broadcast;+use tokio_stream::wrappers::BroadcastStream;++#[derive(Clone, Copy, PartialEq, Eq)]+pub enum Mode {+ DroppedResponse,+ EarlyFinal,+ Rejected,+ Resync,+ PriorApproval,+}++#[derive(Clone)]+struct Shared {+ mode: Mode,+ token: String,+ requests: Arc<Mutex<Vec<Value>>>,+ events: broadcast::Sender<Value>,+}++pub struct MockHost {+ pub port: String,+ state: Shared,+ task: tokio::task::JoinHandle<()>,+}++impl Drop for MockHost {+ fn drop(&mut self) {+ self.task.abort();+ }+}++impl MockHost {+ pub async fn start(mode: Mode, token: &str) -> Self {+ let (events, _) = broadcast::channel(32);+ let state = Shared { mode, token: token.to_owned(), requests: Arc::new(Mutex::new(Vec::new())), events };+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = listener.local_addr().unwrap().port().to_string();+ let app =+ Router::new().route("/events", get(events_stream)).route("/api/send", post(send)).with_state(state.clone());+ let task = tokio::spawn(async move {+ axum::serve(listener, app).await.unwrap();+ });+ Self { port, state, task }+ }++ pub fn requests(&self) -> Vec<Value> {+ self.state.requests.lock().unwrap().clone()+ }+}++fn bot(status: &str, rev: i64) -> Value {+ json!({"type":"bot","rev":rev,"bot":{"id":"transport-bot","name":"Transport","rev":rev,"deleted":false,"status":status}})+}++fn entry(status: &str, rev: i64) -> Value {+ json!({"id":"message","botId":"transport-bot","seq":2,"turn":1,"kind":"user","rev":rev,"data":{"status":status}})+}++fn reply(id: &str, seq: i64, text: &str, rev: i64) -> Value {+ let reply = json!({"id":id,"botId":"transport-bot","seq":seq,"turn":1,"kind":"agent","rev":rev,"data":{"final":true,"text":text}});+ json!({"type":"entry","rev":rev,"entry":reply})+}++fn permission(status: &str, rev: i64) -> Value {+ json!({"type":"entry","rev":rev,"entry":{"id":"prior-approval","botId":"transport-bot","seq":1,"turn":0,"kind":"permission","rev":rev,"data":{"status":status,"title":"Approve earlier work"}}})+}++async fn events_stream(State(state): State<Shared>) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {+ let receiver = state.events.subscribe();+ // `rev` is ahead of the catch-up, as after a write no event carries (a memory file, say).+ let head = if state.mode == Mode::PriorApproval {+ vec![json!({"type":"hello","rev":9,"catchUp":2}), bot("needsInput", 1), permission("pending", 2)]+ } else {+ vec![json!({"type":"hello","rev":9,"catchUp":1}), bot("idle", 1)]+ };+ let head = futures::stream::iter(head);+ let tail = BroadcastStream::new(receiver).filter_map(|event| async move { event.ok() });+ Sse::new(head.chain(tail).map(|event| Ok(Event::default().data(event.to_string()))))+}++async fn send(State(state): State<Shared>, Json(body): Json<Value>) -> Response {+ let attempt = {+ let mut requests = state.requests.lock().unwrap();+ requests.push(body);+ requests.len()+ };+ if state.mode == Mode::Rejected {+ return (StatusCode::FORBIDDEN, Json(json!({"error":format!("denied {}", state.token)}))).into_response();+ }+ if state.mode == Mode::DroppedResponse && attempt == 1 {+ let broken =+ futures::stream::once(async { Err::<Bytes, _>(std::io::Error::other("fixture dropped response")) });+ return Response::new(Body::from_stream(broken));+ }+ if state.mode == Mode::Resync {+ let _ = state.events.send(json!({"type":"resync"}));+ }+ if matches!(state.mode, Mode::EarlyFinal | Mode::PriorApproval) {+ tokio::spawn(async move {+ if state.mode == Mode::PriorApproval {+ tokio::time::sleep(Duration::from_secs(3)).await;+ let _ = state.events.send(permission("approved", 3));+ }+ let _ = state.events.send(json!({"type":"entry","rev":3,"entry":entry("queued", 3)}));+ let _ = state.events.send(json!({"type":"entry","rev":4,"entry":entry("sent", 4)}));+ // A reaction to an older message re-sends it as `sent`: it mustn't take over the waited turn.+ let older = json!({"id":"older","botId":"transport-bot","seq":1,"turn":0,"kind":"user","rev":4,"data":{"status":"sent","reaction":"👍"}});+ let _ = state.events.send(json!({"type":"entry","rev":4,"entry":older}));+ let _ = state.events.send(bot("working", 5));+ let _ = state.events.send(reply("first", 3, "Early final", 6));+ if state.mode == Mode::EarlyFinal {+ tokio::time::sleep(Duration::from_millis(1200)).await;+ // A second message of the same reply (send_message).+ let _ = state.events.send(reply("second", 4, "Second bubble", 7));+ }+ let _ = state.events.send(bot("idle", 8));+ });+ }+ Json(json!({"entry":entry("queued", 2)})).into_response()+}diff --git a/web/content/docs/conversations.mdx b/web/content/docs/conversations.mdxindex d04521b3..a89dd999 100644--- a/web/content/docs/conversations.mdx+++ b/web/content/docs/conversations.mdx@@ -153,3 +153,30 @@ Codync reads plan limits from the agents installed on your computer. Claude Code- **iPhone:** the **State** tab, then **Usage limits**. There's also a Usage widget.- **Desktop:** the menu bar or tray menu, or **Usage** in the account menu at the bottom of the sidebar.- **Terminal UI:** press `U`.++## From a script++`codync-host send` messages a bot from a terminal or a script on the computer the host runs on:++```sh+codync-host send --bot Reviewer "Review the current diff without changing files."+codync-host send --bot Reviewer --wait --json --file request.txt+git diff | codync-host send --bot Reviewer --wait --file -+```++- `--bot` takes the bot's name (any letter case) or its ID. When two bots share a name, use the ID.+- The message is the words after the options, or a UTF-8 file with `--file`. `--file -` reads it from the input.+- Without `--wait`, the command prints the message's `id`, `seq` and `turn` once the host has it. With `--wait`, it waits until the bot is done and prints its reply. A reply in several messages comes joined. A turn that ends with no text, such as only a reaction, prints nothing. Group chats can't be waited on.+- `--json` prints one line of JSON instead: `botId`, `entryId`, `entrySeq`, `turn`, `status` (`completed`, `failed` or `timeout`), `stopReason`, `reply`, `replyId`, `notices`, `elapsedSeconds` and `waitedForApprovalSeconds`.+- `--reply-to <id>` quotes a message, like [Reply](#replying-to-a-message): pass the `entryId` or `replyId` of an earlier `--json` result.+- `--timeout <seconds>` (30 minutes by default) is how long `--wait` waits. Time waiting for an [approval](#approval-cards) doesn't count, and the command never approves anything. When the time runs out, the bot keeps working.++Notices and approvals the bot waits for go to the error output. The exit code says how it went:++| Code | Meaning |+| --- | --- |+| 0 | Done (without `--wait`: the host took the message) |+| 1 | The turn was stopped, hit a limit, was declined or failed |+| 2 | Wrong options, no bot or more than one with that name, or `--wait` on a group chat |+| 3 | The host isn't running or refused the message |+| 4 | `--wait` ran out of time |diff --git a/web/content/docs/linux-servers.mdx b/web/content/docs/linux-servers.mdxindex 30f9a67b..c3962b37 100644--- a/web/content/docs/linux-servers.mdx+++ b/web/content/docs/linux-servers.mdx@@ -35,6 +35,7 @@ codync-host status| `codync-host status` | Whether the service is installed and running || `codync-host pair` | Shows a pairing QR code || `codync-host tui` | Opens the terminal UI |+| `codync-host send --bot <name> "…"` | Messages a bot from a script ([more](/docs/conversations#from-a-script)) || `codync-host stop` | Stops the service and keeps its setup and data || `codync-host uninstall` | Removes the service and keeps your data in `~/.codync` || `journalctl --user -u codync-host -f` | Follows the host's log |