Skip to main content

agentmux_srv_core/ambient/
cli.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Claude CLI subprocess behind every ambient call: spawn it as bare text
5//! generation, race it against cancellation and a timeout, and parse its
6//! stream-json reply.
7
8use crate::backend::obj;
9use super::sanitize::sanitize_ambient_text;
10
11/// Where ambient side calls run: `<data dir>/ambient-calls`, created on
12/// demand; `None` (inherit srv's cwd, as before) only if it cannot be made.
13/// No agent works there, so no agent's history ever matches its transcripts
14/// (#3629).
15pub(crate) fn ambient_call_cwd() -> Option<std::path::PathBuf> {
16    let dir = crate::backend::base::get_mux_data_dir().join("ambient-calls");
17    std::fs::create_dir_all(&dir).ok()?;
18    Some(dir)
19}
20
21/// The model every ambient call runs on.
22pub const AMBIENT_MODEL: &str = "claude-haiku-5-5";
23
24/// Invoke the Claude CLI on [`AMBIENT_MODEL`] for one ambient call, within
25/// `timeout` (the purpose's own, `purpose::Purpose::timeout`).
26///
27/// `cancel` is this call's Ambient Model Call gateway cancellation token — if
28/// a newer request for the same `(entity, purpose)` key is admitted while
29/// this one is still running, `cancel` fires and the child process is killed
30/// immediately rather than left to run to completion (and keep burning
31/// tokens) only to have its result discarded on arrival.
32///
33/// Returns the response text plus token usage parsed from the CLI's `result`
34/// stream-json line (same `usage` shape the main turn pipeline parses —
35/// see `agents::translator::claude::parse_usage`), so ambient calls are
36/// never silently excluded from token accounting.
37pub async fn invoke_haiku(
38    cli_path: &str,
39    prompt: &str,
40    meta: &obj::MetaMapType,
41    cancel: tokio_util::sync::CancellationToken,
42    timeout: std::time::Duration,
43) -> Result<(String, Option<crate::agents::TokenCounts>), String> {
44    let auth_env = ambient_env(meta)?;
45    // Not on an identity whose first spawn is still refreshing its token (#6081): held until that
46    // spawn's first turn has ended, and over this call's own run. Gives up on cancel, or when the
47    // wait alone uses up the call's time.
48    let began = std::time::Instant::now();
49    let _identity = tokio::select! {
50        biased;
51        _ = cancel.cancelled() => return Err("cancelled: superseded by a newer request".to_string()),
52        held = tokio::time::timeout(timeout, crate::identity::token_warmup::ambient_gate(auth_env.get("CLAUDE_CONFIG_DIR").map(String::as_str))) => {
53            held.map_err(|_| format!("ambient CLI waited {}s for its identity's first turn", timeout.as_secs()))?
54        }
55    };
56
57    let mut cmd = crate::backend::pane_env::make_cli_cmd(cli_path);
58    // A bare text-generation call, not an agent session: no tools, one turn, no
59    // slash commands or MCP servers, nothing saved, and our own system prompt in
60    // place of Claude Code's. With the defaults the model answered as a
61    // conversational assistant ("I don't have access to...") whenever the
62    // digest was thin, and that text reached the UI.
63    cmd.args(["-p", "--output-format", "stream-json", "--verbose",
64              "--model", AMBIENT_MODEL,
65              "--tools", "", "--max-turns", "1",
66              "--no-session-persistence", "--disable-slash-commands",
67              "--strict-mcp-config",
68              "--system-prompt", crate::ambient::prompt::AMBIENT_SYSTEM_PROMPT])
69        .envs(&auth_env);
70    // Run in a scratch dir of our own, never srv's cwd (the user's home):
71    // Claude files each call's transcript under its cwd's project folder,
72    // and an agent working in that same dir would find every side call —
73    // whose prompts quote other agents' conversations — in its own history
74    // (#3629).
75    if let Some(dir) = ambient_call_cwd() {
76        cmd.current_dir(dir);
77    }
78    crate::backend::process_tracker::registry::own_process_group(&mut cmd);
79    let mut child = agentmux_common::process::KillGroupOnDrop(cmd
80        .stdin(std::process::Stdio::piped())
81        .stdout(std::process::Stdio::piped())
82        .stderr(std::process::Stdio::piped())
83        .kill_on_drop(true)
84        .spawn()
85        .map_err(|e| format!("failed to spawn the ambient CLI: {e}"))?);
86    crate::backend::process_tracker::registry::record_untracked_cli(child.id());
87
88    if let Some(mut stdin) = child.stdin.take() {
89        use tokio::io::AsyncWriteExt;
90        stdin.write_all(prompt.as_bytes()).await
91            .map_err(|e| format!("ambient CLI stdin write: {e}"))?;
92        stdin.shutdown().await
93            .map_err(|e| format!("ambient CLI stdin shutdown: {e}"))?;
94    }
95
96    // Drained to the end whatever it holds, so a chatty child can't block on a full pipe; only the end is kept, as the
97    // reason an exit that failed is logged with.
98    let stderr_task = child.stderr.take().map(|pipe| tokio::spawn(read_tail(pipe, STDERR_TAIL_BYTES)));
99
100    // What the gate wait left of the call's time is all the child gets.
101    let budget = timeout;
102    let timeout = budget.saturating_sub(began.elapsed());
103
104    // `child.wait()` only borrows (unlike `wait_with_output()`, which
105    // consumes `child` by value and would make the cancel branch's
106    // group kill below impossible). Drain stdout concurrently via a
107    // separate task — same rationale `wait_with_output()` itself uses
108    // internally — so a chatty response can't fill the OS pipe buffer and
109    // deadlock the child waiting to write while nothing is reading.
110    let stdout_pipe = child.stdout.take()
111        .ok_or_else(|| "ambient CLI: no stdout pipe".to_string())?;
112    let stdout_task = tokio::spawn(read_tail(stdout_pipe, usize::MAX));
113
114    let status = tokio::select! {
115        biased;
116        _ = cancel.cancelled() => {
117            let _ = agentmux_common::process::kill_child_and_group(&mut child).await;
118            return Err("cancelled: superseded by a newer request".to_string());
119        }
120        result = tokio::time::timeout(timeout, child.wait()) => match result {
121            Ok(status) => status.map_err(|e| format!("ambient CLI wait: {e}"))?,
122            Err(_) => {
123                let _ = agentmux_common::process::kill_child_and_group(&mut child).await;
124                return Err(format!("ambient CLI timed out after {}s", budget.as_secs()));
125            }
126        },
127    };
128
129    if !status.success() {
130        return Err(exit_error(&status.to_string(), &stderr_tail_of(stderr_task).await));
131    }
132
133    let stdout_bytes = stdout_task.await
134        .map_err(|e| format!("ambient CLI stdout reader task: {e}"))?;
135    let stdout = String::from_utf8_lossy(&stdout_bytes);
136    // An empty reply is a valid answer ("nothing to say"), and the call still cost
137    // tokens, so it comes back as `Ok` with empty text rather than an error that
138    // would drop the usage. Callers already treat empty text as "no result".
139    Ok(parse_cli_stream(&stdout))
140}
141
142/// How much of the end of the CLI's stderr is kept for a failed exit.
143const STDERR_TAIL_BYTES: usize = 2048;
144/// The most characters of it that go into the error (and so the log).
145const STDERR_LOGGED_CHARS: usize = 200;
146
147/// Read `pipe` to its end, keeping only the last `cap` bytes.
148async fn read_tail(mut pipe: impl tokio::io::AsyncRead + Unpin, cap: usize) -> Vec<u8> {
149    use tokio::io::AsyncReadExt;
150    let mut tail: Vec<u8> = Vec::new();
151    let mut chunk = [0u8; 4096];
152    loop {
153        match pipe.read(&mut chunk).await {
154            Ok(0) | Err(_) => return tail,
155            Ok(n) => {
156                tail.extend_from_slice(&chunk[..n]);
157                if tail.len() > cap {
158                    tail.drain(..tail.len() - cap);
159                }
160            }
161        }
162    }
163}
164
165/// What the stderr reader task kept, waiting at most a second for it (the child has exited, so its pipe is closed).
166async fn stderr_tail_of(task: Option<tokio::task::JoinHandle<Vec<u8>>>) -> Vec<u8> {
167    let Some(task) = task else { return Vec::new() };
168    tokio::time::timeout(std::time::Duration::from_secs(1), task).await.ok().and_then(Result::ok).unwrap_or_default()
169}
170
171/// The error for a CLI that exited unsuccessfully: its status, and the end of what it wrote to stderr on one line.
172fn exit_error(status: &str, stderr_tail: &[u8]) -> String {
173    let text = String::from_utf8_lossy(stderr_tail);
174    let line = text.split_whitespace().collect::<Vec<_>>().join(" ");
175    let count = line.chars().count();
176    if line.is_empty() {
177        return format!("ambient CLI exited with status {status}");
178    }
179    let shown: String = if count > STDERR_LOGGED_CHARS { format!("…{}", line.chars().skip(count - STDERR_LOGGED_CHARS).collect::<String>()) } else { line };
180    format!("ambient CLI exited with status {status}{}{shown}", super::outcome::CHILD_OUTPUT_MARK)
181}
182
183/// Whether the agent in this block is on a model server of its own, for which no ambient call is made (`ambient_env`).
184pub(crate) fn has_own_model_server(meta: &obj::MetaMapType) -> bool {
185    ambient_env(meta).is_err()
186}
187
188/// Whether the agent in this block runs on one of AgentMux's model routes. The route's variables are set at each spawn,
189/// not kept in the pane's saved environment, so the pane's record of the route it really runs on is what says so.
190pub(crate) fn on_model_route(meta: &obj::MetaMapType) -> bool {
191    meta.get(crate::backend::model_gateway::launch::BLOCK_META_KEY).is_some_and(|v| !v.is_null())
192}
193
194/// Whether the background title recovery leaves this agent alone: it is on a model server of its own or on a model
195/// route, and a recovery call would use the person's own sign-in, and send the conversation to Anthropic, instead.
196pub(crate) fn recovery_skips(meta: &obj::MetaMapType) -> bool {
197    has_own_model_server(meta) || on_model_route(meta)
198}
199
200/// The last assistant text block (sanitized) and the usage from a `claude -p
201/// --output-format stream-json` transcript. Text is empty when the model said
202/// nothing, or only wrapped nothing in a fence.
203fn parse_cli_stream(stdout: &str) -> (String, Option<crate::agents::TokenCounts>) {
204    let mut last_text = String::new();
205    let mut tokens: Option<crate::agents::TokenCounts> = None;
206    for line in stdout.lines() {
207        let Ok(val) = serde_json::from_str::<serde_json::Value>(line) else { continue };
208        match val.get("type").and_then(|v| v.as_str()) {
209            Some("assistant") => {
210                if let Some(content) = val.get("message")
211                    .and_then(|m| m.get("content"))
212                    .and_then(|c| c.as_array())
213                {
214                    for block in content {
215                        if block.get("type").and_then(|v| v.as_str()) == Some("text") {
216                            if let Some(text) = block.get("text").and_then(|v| v.as_str()) {
217                                last_text = text.trim().to_string();
218                            }
219                        }
220                    }
221                }
222            }
223            Some("result") => {
224                tokens = Some(crate::agents::translator::claude::parse_usage(val.get("usage")));
225            }
226            _ => {}
227        }
228    }
229    (sanitize_ambient_text(&last_text), tokens)
230}
231
232/// The environment of an ambient call: the pane's saved one. Not for an agent on a model server of its own:
233/// the call would read the person's stored sign-in from the shared config directory and send it, with a digest
234/// of the conversation, to that server (or send the digest to Anthropic, which is what pointing the agent
235/// elsewhere was meant to avoid). It makes no call at all.
236fn ambient_env(meta: &obj::MetaMapType) -> Result<std::collections::HashMap<String, String>, String> {
237    let env = crate::backend::blockcontroller::cmd_env_of(meta);
238    match crate::backend::spawn_env::endpoint::requested(&env) {
239        Some(_) => Err("no ambient call for an agent on a model server of its own".to_string()),
240        None => Ok(env),
241    }
242}
243
244#[cfg(test)]
245mod ambient_endpoint_tests {
246    use super::*;
247
248    /// The person's sign-in and the conversation stay off a server an agent was pointed at: the call is not made.
249    #[tokio::test]
250    async fn an_agent_on_a_server_of_its_own_gets_no_ambient_call() {
251        for env in [
252            serde_json::json!({ "CLAUDE_CONFIG_DIR": "C:/shared/providers/claude", "ANTHROPIC_BASE_URL": "http://192.0.2.68:11434" }),
253            serde_json::json!({ "anthropic_base_url": "http://192.0.2.68:11434" }),
254        ] {
255            let mut meta = obj::MetaMapType::new();
256            meta.insert("cmd:env".to_string(), env);
257            let out = invoke_haiku(
258                "a-cli-that-does-not-exist",
259                "prompt",
260                &meta,
261                tokio_util::sync::CancellationToken::new(),
262                std::time::Duration::from_secs(5),
263            )
264            .await;
265            assert_eq!(out.unwrap_err(), "no ambient call for an agent on a model server of its own");
266        }
267    }
268}
269
270#[cfg(test)]
271mod ambient_call_cwd_tests {
272    /// #3629: side calls run in a dir of their own under the data dir —
273    /// never srv's cwd (the user's home), where an agent may work.
274    #[test]
275    fn side_calls_run_in_their_own_scratch_dir() {
276        let dir = super::ambient_call_cwd().expect("the scratch dir can be made");
277        assert!(dir.is_dir());
278        assert!(dir.ends_with("ambient-calls"));
279        assert!(dir.starts_with(crate::backend::base::get_mux_data_dir()));
280        assert_ne!(Some(dir.as_path()), dirs::home_dir().as_deref());
281    }
282}
283
284#[cfg(test)]
285mod ambient_cli_failure_tests {
286    use super::*;
287
288    #[tokio::test]
289    async fn only_the_end_of_what_a_child_writes_is_kept() {
290        let long: Vec<u8> = (0..10_000u32).map(|i| b'a' + (i % 26) as u8).collect();
291        let tail = read_tail(&long[..], 100).await;
292        assert_eq!(tail, long[long.len() - 100..]);
293        assert_eq!(read_tail(&b"short"[..], 100).await, b"short");
294    }
295
296    #[test]
297    fn a_failed_exit_carries_the_end_of_stderr_on_one_line() {
298        let tail = b"Error: not logged in\n  run /login\n";
299        assert_eq!(exit_error("exit code: 1", tail), "ambient CLI exited with status exit code: 1 | stderr: Error: not logged in run /login");
300        assert_eq!(exit_error("exit code: 1", b""), "ambient CLI exited with status exit code: 1");
301        let long = "x ".repeat(500);
302        let e = exit_error("1", long.as_bytes());
303        assert!(e.chars().count() < 260, "{}", e.chars().count());
304        assert!(e.contains("…"));
305    }
306
307    #[test]
308    fn an_agent_on_a_model_server_of_its_own_is_known_from_its_block() {
309        let mut meta = obj::MetaMapType::new();
310        assert!(!has_own_model_server(&meta));
311        meta.insert("cmd:env".to_string(), serde_json::json!({ "ANTHROPIC_BASE_URL": "http://192.0.2.68:11434" }));
312        assert!(has_own_model_server(&meta));
313    }
314
315    #[test]
316    fn an_agent_on_a_model_route_is_known_from_the_route_its_pane_records() {
317        let mut meta = obj::MetaMapType::new();
318        assert!(!on_model_route(&meta) && !recovery_skips(&meta));
319        meta.insert("agent:route_model".to_string(), serde_json::json!(null));
320        assert!(!on_model_route(&meta), "a route left is recorded as null");
321        meta.insert("agent:route_model".to_string(), serde_json::json!({ "route": "openrouter", "model": "m" }));
322        assert!(on_model_route(&meta) && recovery_skips(&meta));
323    }
324}
325
326#[cfg(test)]
327mod ambient_cli_stream_tests {
328    use super::*;
329
330    #[test]
331    fn an_empty_fence_is_empty_text_but_the_usage_survives() {
332        let out = [
333            r#"{"type":"assistant","message":{"content":[{"type":"text","text":"```\n```"}]}}"#,
334            r#"{"type":"result","usage":{"input_tokens":235,"output_tokens":4}}"#,
335        ].join("\n");
336        let (text, tokens) = parse_cli_stream(&out);
337        assert_eq!(text, "");
338        assert!(tokens.is_some());
339    }
340
341    #[test]
342    fn the_last_assistant_text_wins_and_thinking_blocks_are_ignored() {
343        let out = [
344            r#"{"type":"assistant","message":{"content":[{"type":"thinking","thinking":"hmm"}]}}"#,
345            r#"{"type":"assistant","message":{"content":[{"type":"text","text":"Run the tests"}]}}"#,
346            r#"{"type":"result","usage":{"input_tokens":1,"output_tokens":2}}"#,
347        ].join("\n");
348        assert_eq!(parse_cli_stream(&out).0, "Run the tests");
349    }
350
351    #[test]
352    fn a_transcript_with_no_result_line_has_no_usage() {
353        let out = r#"{"type":"assistant","message":{"content":[{"type":"text","text":"x"}]}}"#;
354        assert!(parse_cli_stream(out).1.is_none());
355    }
356}
357
358/// The side call's CLI leads its own process group, so cancelling it ends the
359/// helpers it started, and a signal to its group can't reach srv.
360#[cfg(all(test, unix))]
361mod ambient_cli_group_tests {
362    use super::*;
363    use std::os::unix::fs::PermissionsExt as _;
364
365    #[tokio::test]
366    async fn the_cli_leads_its_own_group_and_cancel_ends_its_helper() {
367        let dir = std::env::temp_dir().join(format!("ambient-group-{}", uuid::Uuid::new_v4()));
368        std::fs::create_dir_all(&dir).unwrap();
369        let report = dir.join("report");
370        let stub = dir.join("claude-stub.sh");
371        std::fs::write(
372            &stub,
373            format!(
374                "#!/bin/sh\ncat >/dev/null\nsleep 30 &\necho \"$$ $(ps -o pgid= -p $$ | tr -d ' ') $!\" > {r}.tmp && mv {r}.tmp {r}\nwait\n",
375                r = report.display()
376            ),
377        )
378        .unwrap();
379        std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap();
380
381        let cancel = tokio_util::sync::CancellationToken::new();
382        let call = tokio::spawn({
383            let (stub, cancel) = (stub.to_string_lossy().into_owned(), cancel.clone());
384            async move {
385                invoke_haiku(&stub, "hi", &Default::default(), cancel, std::time::Duration::from_secs(30)).await
386            }
387        });
388        let mut fields = Vec::new();
389        for _ in 0..200 {
390            if let Ok(text) = std::fs::read_to_string(&report) {
391                fields = text.split_whitespace().filter_map(|f| f.parse::<u32>().ok()).collect();
392                if fields.len() == 3 {
393                    break;
394                }
395            }
396            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
397        }
398        assert_eq!(fields.len(), 3, "the stub reported");
399        let (pid, pgid, helper) = (fields[0], fields[1], fields[2]);
400        assert_eq!(pid, pgid, "the CLI leads its own process group");
401        assert_ne!(pgid as i32, unsafe { libc::getpgid(0) }, "not srv's group");
402
403        cancel.cancel();
404        assert!(call.await.unwrap().unwrap_err().starts_with("cancelled"));
405        let mut gone = false;
406        for _ in 0..100 {
407            if agentmux_common::process::process_start_time(helper).is_none() || is_zombie(helper) {
408                gone = true;
409                break;
410            }
411            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
412        }
413        assert!(gone, "the CLI's helper {helper} outlived the cancel");
414        let _ = std::fs::remove_dir_all(&dir);
415    }
416
417    fn is_zombie(pid: u32) -> bool {
418        std::fs::read_to_string(format!("/proc/{pid}/stat"))
419            .ok()
420            .and_then(|s| s.rfind(')').map(|i| s[i + 1..].trim_start().starts_with('Z')))
421            .unwrap_or(false)
422    }
423}
424
425/// Needs a logged-in `claude` on PATH and spends a few tokens, so it is not part
426/// of the default run: `cargo test --bin agentmux-srv live_cli -- --ignored`.
427/// It exercises the real argument list (`--tools ""`, `--system-prompt`, ...)
428/// that the stream-parsing tests above cannot.
429#[cfg(test)]
430mod live_cli_smoke {
431    use super::*;
432
433    #[tokio::test]
434    #[ignore = "spawns the real claude CLI"]
435    async fn live_cli_answers_a_thin_prompt_with_nothing_instead_of_a_refusal() {
436        let meta = obj::MetaMapType::new();
437        let prompt = crate::ambient::prompt::build_next_prompt_prompt("[user] hi");
438        let (text, tokens) = invoke_haiku(
439            "claude",
440            &prompt,
441            &meta,
442            tokio_util::sync::CancellationToken::new(),
443            crate::ambient::purpose::NEXT_PROMPT_SUGGESTION.timeout,
444        )
445        .await
446        .expect("the CLI ran");
447        assert!(tokens.is_some(), "usage is reported");
448        // A thin digest: the answer is SKIP, in the reply format, never prose.
449        assert_ne!(crate::ambient::reply::parse(&text), crate::ambient::reply::Parsed::Malformed, "unexpected reply: {text}");
450        assert!(!text.to_lowercase().contains("i don't have"), "{text}");
451    }
452
453    /// The reply format (`reply`) has to hold on the real model before it can be
454    /// relied on: every reply is `ANSWER: …` or `SKIP`, across activity that
455    /// clearly has a next step, finished work, and activity too thin to read.
456    /// `cargo test --bin agentmux-srv live_cli_reply_format -- --ignored --nocapture`
457    #[tokio::test]
458    #[ignore = "spawns the real claude CLI, about a dozen calls"]
459    async fn live_cli_reply_format_holds_across_digests() {
460        use crate::ambient::reply::{parse, Parsed};
461        let digests = [
462            // A clear next step.
463            "[user] fix the login redirect loop\n[assistant] Found it: the session cookie was set after the redirect. Fixed in auth.ts; the login flow works now.",
464            "[user] add a dark mode toggle\n[assistant] Added the toggle to the settings panel and wired it to the theme store. I haven't written tests yet.",
465            "[user] why is CI red\n[tool] Bash\n[error] npm test exited 1\n[assistant] Two snapshot tests fail after the button restyle; the snapshots need updating.",
466            "[user] profile the slow search\n[tool] Bash\n[assistant] Search spends 80% of its time re-sorting the whole index on every keystroke.",
467            "[user] bump the version\n[assistant] Bumped to 2.4.0 in package.json and the lockfile. The changelog still lists these changes under Unreleased.",
468            "[user] write the migration\n[assistant] The migration adds the column with a default and backfills in batches of 1000. It hasn't been run against staging.",
469            // Finished, nothing obvious left.
470            "[user] thanks, that's all\n[assistant] You're welcome. Everything is merged and deployed.",
471            "[user] merge it\n[assistant] Merged. The branch is deleted and main is green.",
472            // Thin or unreadable.
473            "[user] hi\n[assistant] Hello.",
474            "[user] ok\n[assistant] Done.",
475            "[tool] Read\n[tool] Read\n[tool] Grep\n[assistant] Looking.",
476            "[user] continue\n[assistant] Continuing with the next file.",
477        ];
478        let meta = obj::MetaMapType::new();
479        let mut bad = Vec::new();
480        let mut failed = 0;
481        for digest in digests {
482            let prompt = crate::ambient::prompt::build_next_prompt_prompt(digest);
483            // A CLI failure (most often the time limit) says nothing about the
484            // format; it is counted, not judged.
485            let text = match invoke_haiku(
486                "claude",
487                &prompt,
488                &meta,
489                tokio_util::sync::CancellationToken::new(),
490                crate::ambient::purpose::NEXT_PROMPT_SUGGESTION.timeout,
491            )
492            .await
493            {
494                Ok((text, _)) => text,
495                Err(e) => {
496                    println!("CLI failed: {e}");
497                    failed += 1;
498                    continue;
499                }
500            };
501            let parsed = parse(&text);
502            println!("{parsed:?} <- {text:?}");
503            if parsed == Parsed::Malformed {
504                bad.push(text);
505            }
506        }
507        println!("{failed} of {} calls failed in the CLI", digests.len());
508        assert!(failed < digests.len(), "no call completed");
509        assert!(bad.is_empty(), "replies not in the format: {bad:?}");
510    }
511
512    /// A message that waits for the user without a question mark passes the
513    /// turn-ending gate, so the prompt's SKIP case is what keeps a guess out of
514    /// the composer (#4476). Live, like the test above.
515    #[tokio::test]
516    #[ignore = "calls the real claude CLI; run with --ignored"]
517    async fn live_cli_skips_a_wait_the_gate_cannot_see() {
518        use crate::ambient::reply::{parse, Parsed};
519        let digests = [
520            "[user] pick a cache\n[assistant] Redis or an in-process LRU would both work. Tell me which one and I'll start.",
521            "[user] plan the refactor\n[assistant] Here's the plan: split the parser, then move the tests. Let me know if that works for you before I begin.",
522            "[user] deploy it\n[assistant] Ready to deploy to production. Waiting for your go-ahead.",
523        ];
524        let meta = obj::MetaMapType::new();
525        let mut answered = Vec::new();
526        for digest in digests {
527            let prompt = crate::ambient::prompt::build_next_prompt_prompt(digest);
528            let Ok((text, _)) = invoke_haiku(
529                "claude",
530                &prompt,
531                &meta,
532                tokio_util::sync::CancellationToken::new(),
533                crate::ambient::purpose::NEXT_PROMPT_SUGGESTION.timeout,
534            )
535            .await
536            else {
537                continue;
538            };
539            let parsed = parse(&text);
540            println!("{parsed:?} <- {text:?}");
541            if parsed != Parsed::Skip {
542                answered.push(text);
543            }
544        }
545        assert!(answered.is_empty(), "answered a message that waits for the user: {answered:?}");
546    }
547
548    /// The same check for every other one-line purpose: titles (create and
549    /// maintain), names (with an agent's task as the material, which Haiku used to
550    /// try to carry out), narration and previews.
551    /// `cargo test --bin agentmux-srv live_cli_reply_format_every -- --ignored --nocapture`
552    #[tokio::test]
553    #[ignore = "spawns the real claude CLI, about ten calls"]
554    async fn live_cli_reply_format_holds_for_every_purpose() {
555        use crate::ambient::prompt::*;
556        use crate::ambient::reply::{parse, Parsed};
557        let task = "Investigate the repository at C:\\work\\app. Read src/auth and report every place the session \
558                    cookie is set, with file:line references. Do not change any files.";
559        let prompts = [
560            ("title, create", build_session_title_prompt("", Some("fix the login redirect loop"), None, 7)),
561            ("title, create, nudge", build_session_title_prompt("", Some("continue"), None, 7)),
562            ("title, maintain, same goal", build_session_title_prompt("Fix login redirect loop", Some("also check the logout path"), None, 7)),
563            ("title, maintain, new goal", build_session_title_prompt("Fix login redirect loop", Some("now let's build the billing page"), None, 7)),
564            ("title, from activity", build_session_title_prompt("", None, Some("[user] add a dark mode toggle\n[assistant] Added it."), 7)),
565            ("subagent name", build_subagent_name_prompt(task)),
566            ("dispatch name", build_dispatch_name_prompt(task)),
567            ("narration", narration_prompt("background_task", "task dev").unwrap()),
568            ("preview", build_definition_summary_prompt("[user] add a dark mode toggle\n[assistant] Added it and its tests.")),
569            ("preview, thin", build_definition_summary_prompt("[user] hi\n[assistant] Hello.")),
570        ];
571        let meta = obj::MetaMapType::new();
572        let mut bad = Vec::new();
573        for (name, prompt) in prompts {
574            let text = match invoke_haiku(
575                "claude",
576                &prompt,
577                &meta,
578                tokio_util::sync::CancellationToken::new(),
579                crate::ambient::purpose::ACTIVITY_SUMMARY.timeout,
580            )
581            .await
582            {
583                Ok((text, _)) => text,
584                Err(e) => {
585                    println!("{name}: CLI failed: {e}");
586                    continue;
587                }
588            };
589            let parsed = parse(&text);
590            println!("{name}: {parsed:?} <- {text:?}");
591            if parsed == Parsed::Malformed {
592                bad.push(format!("{name}: {text}"));
593            }
594        }
595        assert!(bad.is_empty(), "replies not in the format: {bad:?}");
596    }
597}