1use crate::backend::obj;
9use super::sanitize::sanitize_ambient_text;
10
11pub(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
21pub const AMBIENT_MODEL: &str = "claude-haiku-5-5";
23
24pub 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 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 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 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 let stderr_task = child.stderr.take().map(|pipe| tokio::spawn(read_tail(pipe, STDERR_TAIL_BYTES)));
99
100 let budget = timeout;
102 let timeout = budget.saturating_sub(began.elapsed());
103
104 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 Ok(parse_cli_stream(&stdout))
140}
141
142const STDERR_TAIL_BYTES: usize = 2048;
144const STDERR_LOGGED_CHARS: usize = 200;
146
147async 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
165async 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
171fn 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
183pub(crate) fn has_own_model_server(meta: &obj::MetaMapType) -> bool {
185 ambient_env(meta).is_err()
186}
187
188pub(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
194pub(crate) fn recovery_skips(meta: &obj::MetaMapType) -> bool {
197 has_own_model_server(meta) || on_model_route(meta)
198}
199
200fn 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
232fn 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 #[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 #[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#[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#[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 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 #[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 "[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 "[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 "[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 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 #[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 #[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}