1use std::collections::BTreeMap;
33use std::path::{Path, PathBuf};
34use std::process::Stdio;
35use std::time::{Duration, Instant};
36
37use anyhow::{Context as _, Result, bail};
38use serde::{Deserialize, Serialize};
39use std::sync::{Arc, Mutex};
40
41use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
42use tokio::process::Command;
43
44use crate::config::{AgentChoice, AgentKind, AgentSpec, Delivery};
45use crate::proc::Quiet as _;
46use crate::rng::SplitMix64;
47
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51pub struct SeatState {
52 pub key: String,
54 pub agent: String,
56 pub turns: usize,
58 pub claude_session: Option<String>,
61 pub captured_session: Option<String>,
63}
64
65impl SeatState {
66 pub fn new(key: &str, agent: &str, run_seed: u64) -> Self {
68 let mut rng = SplitMix64::new(run_seed ^ crate::rng::fnv1a(key));
69 Self {
70 key: key.to_owned(),
71 agent: agent.to_owned(),
72 turns: 0,
73 claude_session: Some(rng.uuid_v4()),
74 captured_session: None,
75 }
76 }
77}
78
79pub fn has_session(kind: AgentKind, seat: &SeatState, sessions_enabled: bool) -> bool {
81 if !sessions_enabled || seat.turns == 0 {
82 return false;
83 }
84 match kind {
85 AgentKind::Claude => seat.claude_session.is_some(),
86 AgentKind::Opencode | AgentKind::Antigravity | AgentKind::Codex | AgentKind::Omp => {
87 seat.captured_session.is_some()
88 }
89 AgentKind::Command => true,
90 }
91}
92
93#[derive(Debug, Clone)]
95pub struct Invocation<'a> {
96 pub coordination: Option<&'a crate::config::Coordination>,
98 pub fetched_base: Option<&'a crate::run::FetchedBase>,
100 pub cwd: &'a Path,
103 pub prompt: &'a str,
105 pub timeout: Duration,
107 pub allow_write: bool,
112 pub sessions: bool,
114 pub artifacts: &'a Path,
116 pub stem: &'a str,
118 pub run: &'a str,
122 pub node: &'a str,
126 pub cache_dir: Option<&'a Path>,
132 pub attachments: &'a [PathBuf],
139 pub writable: &'a [PathBuf],
146}
147
148fn repository_writer(inv: &Invocation<'_>) -> bool {
157 inv.allow_write
158 && (matches!(
159 inv.node,
160 "implement" | "fix" | "graft" | "gate-fix" | "land" | "rebase" | "base-conflict"
161 ) || inv.node == crate::queue::CHAT_NODE)
162}
163
164fn repository_seat(inv: &Invocation<'_>) -> bool {
165 !matches!(
171 inv.node,
172 crate::queue::CHAT_NODE | "talk-title" | "deputy" | "conduct" | "dupes"
173 )
174}
175
176pub async fn worktree_writable_roots(cwd: &Path, home: &Path) -> Result<Vec<PathBuf>> {
183 let mut roots = Vec::new();
184 if let Some(common) = crate::repo_lock::common_dir(cwd).await? {
185 let cwd = std::fs::canonicalize(cwd).context("canonicalize seat working directory")?;
186 if !common.starts_with(&cwd) {
187 roots.push(common);
188 }
189 }
190 for name in ["questions", "notifications"] {
194 let dir = home.join(name);
195 std::fs::create_dir_all(&dir).with_context(|| format!("prepare seat {name} directory"))?;
196 roots.push(std::fs::canonicalize(dir)?);
197 }
198 Ok(roots)
199}
200
201fn editing_access_note(base: Option<&crate::run::FetchedBase>) -> String {
203 let mut note = String::from(
204 "Launcher repository access contract (applies to this turn and overrides earlier fetch instructions):\n",
205 );
206 if let Some(base) = base {
207 note.push_str(&format!(
208 "The launcher successfully fetched `{}/{}` at {} and pinned the run base to `{}`. Use this exact local commit as the verified fetched base; this is a snapshot, not a claim that the remote has not moved since. Do not fetch again as a prerequisite, move the base, or refresh it on resume. Base updates belong to the launcher's existing base-sync path.\n",
209 base.remote, base.branch, base.fetched_at, base.commit,
210 ));
211 } else {
212 note.push_str("No successful launcher fetch evidence is supplied for this invocation. Do not describe local tracking refs as freshly fetched. If fresh remote evidence is essential, report an infrastructure blocker requiring a launcher fetch and a new prepared turn.\n");
213 }
214 note
215}
216
217#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
224pub struct Quota {
225 #[serde(default)]
227 pub cause: QuotaCause,
228 #[serde(default)]
230 pub agent: String,
231 #[serde(default)]
233 pub reset: Option<String>,
234}
235
236#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
238#[serde(rename_all = "snake_case")]
239pub enum QuotaCause {
240 #[default]
242 UsageLimit,
243 Authentication,
245}
246
247#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
254pub struct Dropped {
255 pub why: String,
257 pub output_tokens: u64,
260}
261
262#[derive(Debug, Clone, Serialize, Deserialize)]
276pub struct CommandEvidence {
277 pub id: String,
279 pub description: String,
281 pub exit_code: Option<i32>,
283 pub result_summary: String,
285 pub source: String,
287}
288
289#[derive(Debug, Clone, Serialize, Deserialize)]
291pub struct AgentOutput {
292 pub text: String,
294 pub exit_code: Option<i32>,
296 pub timed_out: bool,
298 pub duration_ms: u64,
300 pub artifacts: Vec<String>,
302 #[serde(default)]
306 pub quota: Option<Quota>,
307 #[serde(default)]
311 pub dropped: Option<Dropped>,
312 #[serde(default)]
316 pub commands: Vec<CommandEvidence>,
317 #[serde(default)]
322 pub context_tokens: Option<u64>,
323}
324
325impl AgentOutput {
326 pub fn usable(&self) -> bool {
328 !self.quota_exhausted()
329 && !self.timed_out
330 && self.exit_code == Some(0)
331 && !self.text.trim().is_empty()
332 }
333
334 pub fn quota_exhausted(&self) -> bool {
336 self.quota.is_some()
337 }
338
339 pub fn work_undelivered(&self) -> bool {
344 self.dropped.is_some()
345 }
346}
347
348#[derive(Debug)]
351pub(crate) struct ExecutionInterrupted(pub String);
352
353impl std::fmt::Display for ExecutionInterrupted {
354 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
355 write!(f, "execution interrupted: {}", self.0)
356 }
357}
358
359impl std::error::Error for ExecutionInterrupted {}
360
361const PIPE_GRACE: Duration = Duration::from_secs(3);
366
367pub(crate) type Captured = Arc<Mutex<Vec<u8>>>;
369
370pub(crate) fn drain<R>(pipe: Option<R>) -> (Captured, Option<tokio::task::JoinHandle<()>>)
380where
381 R: tokio::io::AsyncRead + Unpin + Send + 'static,
382{
383 let buf: Captured = Arc::new(Mutex::new(Vec::new()));
384 let Some(mut pipe) = pipe else {
385 return (buf, None);
386 };
387 let sink = Arc::clone(&buf);
388 let handle = tokio::spawn(async move {
389 let mut chunk = [0u8; 8192];
390 loop {
391 match pipe.read(&mut chunk).await {
392 Ok(0) | Err(_) => break,
393 Ok(n) => {
394 if let Ok(mut guard) = sink.lock() {
395 guard.extend_from_slice(&chunk[..n]);
396 }
397 }
398 }
399 }
400 });
401 (buf, Some(handle))
402}
403
404pub(crate) async fn collect(
409 buf: &Captured,
410 handle: Option<tokio::task::JoinHandle<()>>,
411 grace: Duration,
412) -> String {
413 if let Some(handle) = handle {
414 if tokio::time::timeout(grace, handle).await.is_err() {
415 tracing::debug!("a pipe is still held open after the child exited");
416 }
417 }
418 let bytes = buf.lock().map(|g| g.clone()).unwrap_or_default();
419 String::from_utf8_lossy(&bytes).into_owned()
420}
421
422pub async fn invoke(
424 spec: &AgentSpec,
425 seat: &mut SeatState,
426 inv: &Invocation<'_>,
427) -> Result<AgentOutput> {
428 let lease = if repository_seat(inv) {
433 crate::repo_lock::SeatLease::for_checkout(inv.cwd, inv.allow_write, inv.coordination)
434 .await?
435 } else {
436 None
437 };
438 let inv = &Invocation {
439 timeout: spec.turn_timeout(inv.timeout),
440 ..inv.clone()
441 };
442 let mut outputs = Vec::new();
443 if repository_writer(inv) {
444 let min_free = crate::run::RunState::load_under(inv.run, &crate::run::home())
445 .map_or(0, |state| state.config.disk.min_free_bytes);
446 let mut paths = vec![inv.cwd.to_owned()];
447 if let Some(cache) = inv.cache_dir {
448 paths.push(cache.to_owned());
449 }
450 outputs.extend(
451 crate::retention::OutputLease::admit(&crate::run::home(), &paths, min_free)
452 .map_err(|e| crate::repo_lock::ResourceBlocked(format!("disk admission: {e:#}")))?,
453 );
454 }
455 if repository_seat(inv) {
456 if let Some(guard) = crate::retention::OutputLease::borrow(inv.cwd).map_err(|e| {
457 crate::repo_lock::ResourceBlocked(format!("worktree output ownership: {e:#}"))
458 })? {
459 outputs.push(guard);
460 }
461 if let Some(cache) = inv.cache_dir {
462 outputs.push(crate::retention::OutputLease::cache(
463 &crate::run::home(),
464 cache,
465 false,
466 )?);
467 }
468 }
469
470 let mut prompt = inv.prompt.to_owned();
471 if inv.node == crate::queue::CHAT_NODE {
472 prompt.push_str("\n\n");
473 prompt.push_str(crate::prompt::CHAT_FOLLOW_THROUGH);
474 }
475 if let Some(lease) = lease.as_ref().filter(|lease| lease.delegated) {
476 prompt.push_str(&format!("\n\nRepository coordination: the launcher holds the exclusive repository lock at {} for this invocation. Do not acquire a second lock or release/delete it. Repository access remains read-only.", lease.path.display()));
477 }
478 let home = repository_writer(inv).then(crate::run::home);
481 let mut writable = inv.writable.to_vec();
482 if let Some(home) = &home {
483 for root in worktree_writable_roots(inv.cwd, home).await? {
484 if !writable.contains(&root) {
485 writable.push(root);
486 }
487 }
488 }
489 if repository_writer(inv) {
490 prompt.push_str("\n\n");
491 prompt.push_str(&editing_access_note(inv.fetched_base));
492 }
493 let inv = &Invocation {
494 writable: &writable,
495 prompt: &prompt,
496 ..inv.clone()
497 };
498 tokio::fs::create_dir_all(inv.artifacts)
499 .await
500 .with_context(|| format!("create {}", inv.artifacts.display()))?;
501 let prompt_path = inv.artifacts.join(format!("{}.prompt.md", inv.stem));
502 tokio::fs::write(&prompt_path, inv.prompt)
503 .await
504 .with_context(|| format!("write {}", prompt_path.display()))?;
505
506 let plan = build_command(spec, seat, inv, &prompt_path)?;
507 tracing::debug!(seat = %seat.key, agent = %spec.id, argv = ?plan.logged_argv(), "spawning agent");
508 tokio::fs::write(
510 inv.artifacts.join(format!("{}.access.json", inv.stem)),
511 serde_json::to_vec_pretty(&serde_json::json!({
512 "launcher_version": env!("CARGO_PKG_VERSION"),
513 "kind": spec.kind,
514 "allow_write": inv.allow_write,
515 "unsandboxed": repository_writer(inv),
516 "writable_roots": inv.writable,
517 "fetched_base": inv.fetched_base,
518 }))?,
519 )
520 .await
521 .context("write seat access evidence")?;
522
523 let started = Instant::now();
524 let child_path = spec
527 .env
528 .iter()
529 .find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
530 .map(|(_, v)| std::ffi::OsString::from(v))
531 .or_else(|| std::env::var_os("PATH"))
532 .unwrap_or_default();
533 let program = crate::config::find_program_on(&plan.argv[0], &child_path).map_or_else(
534 || plan.argv[0].clone().into(),
535 std::path::PathBuf::into_os_string,
536 );
537 let mut cmd = Command::new(program);
538 cmd.args(&plan.argv[1..])
539 .current_dir(inv.cwd)
540 .envs(&spec.env)
541 .env("MAGI_SEAT", &seat.key)
542 .env("MAGI_TURN", seat.turns.to_string())
543 .env("MAGI_RUN", inv.run)
544 .env("MAGI_NODE", inv.node)
545 .env("MAGI_PROMPT_FILE", &prompt_path)
546 .env("MAGI_ALLOW_WRITE", if inv.allow_write { "1" } else { "0" })
547 .env("GIT_TERMINAL_PROMPT", "0")
548 .stdin(if plan.stdin.is_some() {
549 Stdio::piped()
550 } else {
551 Stdio::null()
552 })
553 .stdout(Stdio::piped())
554 .stderr(Stdio::piped())
555 .kill_on_drop(true)
556 .quiet();
559 crate::incremental::default_environment(&mut cmd);
560 if repository_writer(inv) {
561 crate::incremental::configure(&mut cmd, inv.cwd)?;
562 }
563 if let Some(home) = home {
564 cmd.env("MAGI_HOME", std::fs::canonicalize(home)?);
567 }
568 if let Some(cache) = inv.cache_dir {
569 cmd.env("CARGO_TARGET_DIR", cache);
572 } else {
573 cmd.env_remove("CARGO_TARGET_DIR");
581 }
582
583 #[cfg(any(unix, windows))]
584 let _chat_controls = {
585 use crate::chat_control::bridge::{self, Bridge};
586 bridge::clear_environment(&mut cmd);
587 let bridge = if inv.node == crate::queue::CHAT_NODE {
588 crate::run::try_home().and_then(|home| {
589 match Bridge::start(&home, inv.run, inv.artifacts) {
590 Ok(bridge) => Some(bridge),
591 Err(error) => {
592 tracing::warn!(%error, "chat controls unavailable; continuing conversation");
593 None
594 }
595 }
596 })
597 } else {
598 None
599 };
600 if let Some(bridge) = &bridge {
601 cmd.env("MAGI_HOME", std::fs::canonicalize(crate::run::home())?);
605 bridge.attach(&mut cmd);
606 }
607 bridge
608 };
609
610 let mut running = crate::seat_process::Running::spawn(cmd, lease, outputs)
611 .with_context(|| format!("spawn `{}` for seat {}", plan.argv[0], seat.key))?;
612 if let (Some(body), Some(mut sink)) = (plan.stdin.clone(), running.child().stdin.take()) {
616 tokio::spawn(async move {
617 sink.write_all(body.as_bytes()).await.ok();
618 sink.shutdown().await.ok();
619 });
620 }
621
622 let (out_buf, out_reader) = drain(running.child().stdout.take());
639 let (err_buf, err_reader) = drain(running.child().stderr.take());
640
641 let min_free = crate::run::RunState::load_under(inv.run, &crate::run::home())
642 .ok()
643 .map_or(0, |state| state.config.disk.min_free_bytes);
644 #[cfg(all(test, unix))]
645 let min_free = test_watchdog::floor(inv.run, min_free);
646 let mut paths = vec![inv.cwd.to_owned()];
647 if let Some(cache) = inv.cache_dir {
648 paths.push(cache.to_owned());
649 }
650 let mut pressure = None;
651 let waited = tokio::select! {
652 waited = tokio::time::timeout(inv.timeout, running.child().wait()) => Some(waited),
653 reason = crate::retention::emergency(paths, min_free) => {
654 pressure = Some(reason);
655 None
656 }
657 };
658 let (code, timed_out) = match waited {
659 Some(Ok(res)) => {
660 let status = res.with_context(|| format!("wait for seat {}", seat.key))?;
661 (status.code(), false)
662 }
663 Some(Err(_)) | None => {
664 if let Some(reason) = &pressure {
665 tracing::warn!(seat = %seat.key, %reason, "agent execution interrupted");
666 } else {
667 tracing::warn!(seat = %seat.key, secs = inv.timeout.as_secs(), "agent timed out");
668 }
669 if !running.coordinated() {
671 running
672 .child()
673 .kill()
674 .await
675 .context("stop timed-out seat")?;
676 }
677 (None, true)
678 }
679 };
680 running.finish().await;
681
682 let stdout = collect(&out_buf, out_reader, PIPE_GRACE).await;
687 let stderr = collect(&err_buf, err_reader, PIPE_GRACE).await;
688
689 let out_path = inv.artifacts.join(format!("{}.out", inv.stem));
690 let err_path = inv.artifacts.join(format!("{}.err", inv.stem));
691 tokio::fs::write(&out_path, &stdout).await.ok();
692 tokio::fs::write(&err_path, &stderr).await.ok();
693 if let Some(reason) = pressure {
694 return Err(
695 anyhow::Error::new(crate::repo_lock::ResourceBlocked(reason.clone()))
696 .context(ExecutionInterrupted(reason)),
697 );
698 }
699
700 if code != Some(0)
701 && (stdout.contains(crate::incremental::BLOCKED)
702 || stderr.contains(crate::incremental::BLOCKED))
703 {
704 let detail = if stderr.contains(crate::incremental::BLOCKED) {
705 &stderr
706 } else {
707 &stdout
708 };
709 return Err(crate::repo_lock::ResourceBlocked(tail_chars(detail, 2000)).into());
710 }
711
712 let mut extracted = extract(spec.kind, &stdout);
713 if spec.kind == AgentKind::Antigravity && extracted.quota.is_none() {
714 extracted.quota = agy_quota(&stdout, &stderr);
715 }
716 if let Some(quota) = &mut extracted.quota {
717 quota.agent.clone_from(&spec.id);
718 if quota.cause == QuotaCause::Authentication {
719 let _ = crate::notices::Notices::open().raise(crate::notices::Notice::warn(
720 &format!("agent-authentication:{}", spec.id),
721 format!("Agent `{}` cannot authenticate. Re-authenticate this agent, then resume the held task.", spec.id),
722 ));
723 }
724 extracted.dropped = None;
727 tracing::warn!(
728 seat = %seat.key,
729 agent = %spec.id,
730 reset = ?quota.reset,
731 cause = ?quota.cause,
732 "agent needs machine-side recovery"
733 );
734 }
735 if let Some(session) = extracted.session {
736 match spec.kind {
737 AgentKind::Claude => seat.claude_session = Some(session),
738 AgentKind::Opencode | AgentKind::Antigravity | AgentKind::Codex | AgentKind::Omp => {
739 seat.captured_session = Some(session);
740 }
741 AgentKind::Command => {}
742 }
743 }
744 if let Some(status) = &extracted.status
745 && !status.eq_ignore_ascii_case("success")
746 {
747 tracing::warn!(seat = %seat.key, status = %status, "agent reported a non-success status");
748 }
749 let text = if extracted.text.trim().is_empty() {
750 if stdout.trim().is_empty() {
752 stderr.trim().to_owned()
753 } else {
754 stdout.trim().to_owned()
755 }
756 } else {
757 extracted.text
758 };
759 seat.turns += 1;
760
761 Ok(AgentOutput {
762 text,
763 exit_code: code,
764 timed_out,
765 duration_ms: started.elapsed().as_millis() as u64,
766 artifacts: vec![
767 file_name(&prompt_path),
768 file_name(&out_path),
769 file_name(&err_path),
770 ],
771 quota: extracted.quota,
772 dropped: extracted.dropped,
773 commands: extracted.commands,
774 context_tokens: extracted.context_tokens,
775 })
776}
777
778fn file_name(p: &Path) -> String {
779 p.file_name()
780 .unwrap_or_default()
781 .to_string_lossy()
782 .into_owned()
783}
784
785#[derive(Debug)]
787struct Plan {
788 argv: Vec<String>,
789 stdin: Option<String>,
790}
791
792impl Plan {
793 fn logged_argv(&self) -> Vec<&str> {
796 let mut settings_value = false;
797 self.argv
798 .iter()
799 .map(|arg| {
800 if settings_value {
801 settings_value = false;
802 "[redacted]"
803 } else if arg == "--settings" {
804 settings_value = true;
805 arg.as_str()
806 } else if arg.starts_with("--settings=") {
807 "--settings=[redacted]"
808 } else {
809 arg.as_str()
810 }
811 })
812 .collect()
813 }
814}
815
816fn pointer(kind: AgentKind, prompt_path: &Path) -> String {
827 if matches!(kind, AgentKind::Antigravity) {
828 return format!("@{}", prompt_path.display());
829 }
830 format!(
831 "Read the file at {} and follow every instruction in it exactly. That \
832 file is your complete task description; this message contains nothing \
833 else.",
834 prompt_path.display()
835 )
836}
837
838fn build_command(
839 spec: &AgentSpec,
840 seat: &SeatState,
841 inv: &Invocation<'_>,
842 prompt_path: &Path,
843) -> Result<Plan> {
844 let mut argv: Vec<String> = Vec::new();
845 let mut stdin: Option<String> = None;
846 let delivery = spec.delivery();
847 let resuming = has_session(spec.kind, seat, inv.sessions);
848
849 match spec.kind {
850 AgentKind::Claude => {
851 argv.push("claude".to_owned());
856 argv.push("-p".to_owned());
857 argv.push("--output-format".to_owned());
858 argv.push("json".to_owned());
859 if let Some(m) = &spec.model {
860 argv.push("--model".to_owned());
861 argv.push(m.clone());
862 }
863 if inv.sessions {
864 let uuid = seat
865 .claude_session
866 .as_deref()
867 .context("claude seat is missing its session uuid")?;
868 argv.push(if resuming { "--resume" } else { "--session-id" }.to_owned());
869 argv.push(uuid.to_owned());
870 }
871 argv.push("--permission-mode".to_owned());
872 argv.push("bypassPermissions".to_owned());
873 if !inv.allow_write {
874 argv.push("--disallowed-tools".to_owned());
875 argv.push("Edit,Write,MultiEdit,NotebookEdit".to_owned());
876 }
877 }
878 AgentKind::Opencode => {
879 argv.push("opencode".to_owned());
883 argv.push("run".to_owned());
884 argv.push("--format".to_owned());
885 argv.push("json".to_owned());
886 argv.push("--dir".to_owned());
887 argv.push(inv.cwd.to_string_lossy().into_owned());
888 argv.push("--auto".to_owned());
897 if let Some(m) = &spec.model {
898 argv.push("-m".to_owned());
899 argv.push(m.clone());
900 }
901 if resuming {
902 argv.push("-s".to_owned());
903 argv.push(
904 seat.captured_session
905 .clone()
906 .expect("has_session checked the id is present"),
907 );
908 }
909 }
910 AgentKind::Antigravity => {
911 argv.push("agy".to_owned());
912 argv.push("--output-format".to_owned());
913 argv.push("json".to_owned());
914 argv.push("--print-timeout".to_owned());
917 argv.push(format!("{}s", inv.timeout.as_secs()));
918 argv.push("--mode".to_owned());
919 argv.push(
920 if inv.allow_write {
921 "accept-edits"
922 } else {
923 "plan"
924 }
925 .to_owned(),
926 );
927 if inv.allow_write {
928 argv.push("--dangerously-skip-permissions".to_owned());
929 }
930 if let Some(m) = &spec.model {
931 argv.push("--model".to_owned());
932 argv.push(m.clone());
933 }
934 if resuming {
935 argv.push("--conversation".to_owned());
936 argv.push(
937 seat.captured_session
938 .clone()
939 .expect("has_session checked the id is present"),
940 );
941 }
942 let mut add_dirs: Vec<String> = Vec::new();
952 if delivery == Delivery::File || !inv.attachments.is_empty() {
953 add_dirs.push(inv.artifacts.to_string_lossy().into_owned());
954 }
955 for path in inv.attachments {
956 let Some(parent) = path.parent() else {
957 continue;
958 };
959 if parent.starts_with(inv.artifacts) {
960 continue;
961 }
962 let dir = parent.to_string_lossy().into_owned();
963 if !add_dirs.contains(&dir) {
964 add_dirs.push(dir);
965 }
966 }
967 if inv.allow_write {
968 for path in inv.writable {
969 let dir = path.to_string_lossy().into_owned();
970 if !add_dirs.contains(&dir) {
971 add_dirs.push(dir);
972 }
973 }
974 }
975 for dir in add_dirs {
976 argv.push("--add-dir".to_owned());
977 argv.push(dir);
978 }
979 }
980 AgentKind::Codex => {
981 argv.push("codex".to_owned());
987 argv.push("exec".to_owned());
988 argv.push("--json".to_owned());
989 argv.push("--skip-git-repo-check".to_owned());
992 argv.push("-C".to_owned());
993 argv.push(inv.cwd.to_string_lossy().into_owned());
994 if repository_writer(inv) {
1004 argv.push("--dangerously-bypass-approvals-and-sandbox".to_owned());
1005 } else {
1006 argv.push("--sandbox".to_owned());
1007 argv.push(
1008 if inv.allow_write {
1009 "workspace-write"
1010 } else {
1011 "read-only"
1012 }
1013 .to_owned(),
1014 );
1015 argv.push("-c".to_owned());
1018 argv.push("approval_policy=\"never\"".to_owned());
1019 if inv.allow_write && !inv.writable.is_empty() {
1020 let roots: Vec<String> = inv
1021 .writable
1022 .iter()
1023 .map(|p| p.to_string_lossy().into_owned())
1024 .collect();
1025 argv.push("-c".to_owned());
1026 argv.push(format!(
1027 "sandbox_workspace_write.writable_roots={}",
1028 serde_json::to_string(&roots).unwrap_or_else(|_| "[]".to_owned())
1029 ));
1030 }
1031 }
1032 if let Some(m) = &spec.model {
1033 argv.push("-m".to_owned());
1034 argv.push(m.clone());
1035 }
1036 if resuming {
1042 argv.push("resume".to_owned());
1043 argv.push(
1044 seat.captured_session
1045 .clone()
1046 .expect("has_session checked the id is present"),
1047 );
1048 }
1049 }
1050 AgentKind::Omp => {
1051 argv.push("omp".to_owned());
1055 argv.push("-p".to_owned());
1056 argv.push("--mode=json".to_owned());
1057 argv.push("--auto-approve".to_owned());
1067 if let Some(m) = &spec.model {
1068 argv.push("--model".to_owned());
1069 argv.push(m.clone());
1070 }
1071 if resuming {
1077 argv.push("--resume".to_owned());
1078 argv.push(
1079 seat.captured_session
1080 .clone()
1081 .expect("has_session checked the id is present"),
1082 );
1083 }
1084 }
1085 AgentKind::Command => {
1086 if spec.command.is_empty() {
1091 bail!("agent `{}` has kind = \"command\" but no command", spec.id);
1092 }
1093 let vars: BTreeMap<&str, String> = BTreeMap::from([
1094 ("{prompt_file}", prompt_path.to_string_lossy().into_owned()),
1095 ("{cwd}", inv.cwd.to_string_lossy().into_owned()),
1096 ("{label}", seat.key.clone()),
1097 ("{session}", seat.claude_session.clone().unwrap_or_default()),
1098 ]);
1099 for raw in &spec.command {
1100 let mut arg = raw.clone();
1101 for (k, v) in &vars {
1102 if arg.contains(k) {
1103 arg = arg.replace(k, v);
1104 }
1105 }
1106 argv.push(arg);
1107 }
1108 }
1109 }
1110
1111 argv.extend(spec.extra_args.iter().cloned());
1112
1113 if spec.kind == AgentKind::Antigravity {
1116 argv.push("-p".to_owned());
1117 }
1118 if spec.kind == AgentKind::Codex && delivery == Delivery::Stdin {
1121 argv.push("-".to_owned());
1122 }
1123 match delivery {
1124 Delivery::Stdin if spec.kind == AgentKind::Antigravity => {
1125 argv.push(pointer(spec.kind, prompt_path));
1127 }
1128 Delivery::Stdin => stdin = Some(inv.prompt.to_owned()),
1129 Delivery::Argv => argv.push(inv.prompt.to_owned()),
1130 Delivery::File => argv.push(pointer(spec.kind, prompt_path)),
1131 }
1132
1133 Ok(Plan { argv, stdin })
1134}
1135
1136#[derive(Debug, Default)]
1138struct Extracted {
1139 text: String,
1140 session: Option<String>,
1141 status: Option<String>,
1142 quota: Option<Quota>,
1143 dropped: Option<Dropped>,
1144 commands: Vec<CommandEvidence>,
1145 context_tokens: Option<u64>,
1146}
1147
1148fn extract(kind: AgentKind, stdout: &str) -> Extracted {
1150 let mut extracted = extract_answer(kind, stdout);
1151 extracted.context_tokens = context_tokens(kind, stdout);
1152 extracted
1153}
1154
1155fn uint(v: &serde_json::Value, key: &str) -> Option<u64> {
1157 v.get(key).and_then(serde_json::Value::as_u64)
1158}
1159
1160fn input_side(usage: &serde_json::Value, input: &[&str], cache: &[&str]) -> Option<u64> {
1165 let first = |keys: &[&str]| keys.iter().find_map(|k| uint(usage, k));
1166 let base = first(input)?;
1167 let cached: u64 = cache.iter().filter_map(|k| uint(usage, k)).sum();
1168 Some(base.saturating_add(cached))
1169}
1170
1171fn context_tokens(kind: AgentKind, stdout: &str) -> Option<u64> {
1192 use serde_json::Value;
1193 let lines = || {
1194 stdout
1195 .lines()
1196 .filter_map(|l| serde_json::from_str::<Value>(l.trim()).ok())
1197 };
1198 match kind {
1199 AgentKind::Claude => None,
1200 AgentKind::Opencode => lines()
1201 .filter(|v| {
1202 v.get("type").and_then(|t| t.as_str()) == Some("step_finish")
1204 || v.get("part")
1205 .and_then(|p| p.get("type"))
1206 .and_then(|t| t.as_str())
1207 == Some("step-finish")
1208 })
1209 .filter_map(|v| {
1210 let tokens = v.get("part")?.get("tokens")?;
1211 let base = uint(tokens, "input")?;
1212 let cache = tokens.get("cache");
1213 let cached = ["read", "write"]
1214 .iter()
1215 .filter_map(|k| cache.and_then(|c| uint(c, k)))
1216 .sum::<u64>();
1217 Some(base.saturating_add(cached))
1218 })
1219 .next_back(),
1220 AgentKind::Antigravity => None,
1221 AgentKind::Codex => None,
1222 AgentKind::Omp => lines()
1223 .flat_map(|v| {
1224 match v.get("type").and_then(|t| t.as_str()) {
1227 Some("agent_end") => v
1228 .get("messages")
1229 .and_then(|m| m.as_array())
1230 .cloned()
1231 .unwrap_or_default(),
1232 Some("turn_end") | Some("message_end") => {
1233 v.get("message").cloned().into_iter().collect()
1234 }
1235 _ => Vec::new(),
1236 }
1237 })
1238 .filter(|m| m.get("role").and_then(|r| r.as_str()) == Some("assistant"))
1239 .filter_map(|m| {
1240 input_side(
1241 m.get("usage")?,
1242 &["input", "input_tokens"],
1243 &[
1244 "cacheRead",
1245 "cacheWrite",
1246 "cache_read_tokens",
1247 "cache_write_tokens",
1248 ],
1249 )
1250 })
1251 .next_back(),
1252 AgentKind::Command => None,
1253 }
1254}
1255
1256pub(crate) fn answer_text(kind: AgentKind, stdout: &str) -> String {
1259 extract_answer(kind, stdout).text
1260}
1261
1262fn extract_answer(kind: AgentKind, stdout: &str) -> Extracted {
1263 match kind {
1264 AgentKind::Claude => {
1265 let Ok(v) = serde_json::from_str::<serde_json::Value>(stdout.trim()) else {
1266 return Extracted {
1267 text: stdout.trim().to_owned(),
1268 ..Extracted::default()
1269 };
1270 };
1271 Extracted {
1272 text: v
1273 .get("result")
1274 .and_then(|r| r.as_str())
1275 .unwrap_or_default()
1276 .to_owned(),
1277 session: v
1278 .get("session_id")
1279 .and_then(|s| s.as_str())
1280 .map(str::to_owned),
1281 status: v.get("is_error").and_then(|e| e.as_bool()).map(|e| {
1282 if e {
1283 "error".to_owned()
1284 } else {
1285 "success".to_owned()
1286 }
1287 }),
1288 quota: claude_quota(&v),
1289 dropped: None,
1292 commands: Vec::new(),
1293 context_tokens: None,
1294 }
1295 }
1296 AgentKind::Opencode => {
1297 let mut text = String::new();
1299 let mut session = None;
1300 for line in stdout.lines() {
1301 let Ok(v) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
1302 continue;
1303 };
1304 if session.is_none() {
1305 session = v
1306 .get("sessionID")
1307 .and_then(|s| s.as_str())
1308 .map(str::to_owned);
1309 }
1310 let part = v.get("part").unwrap_or(&serde_json::Value::Null);
1311 if part.get("type").and_then(|t| t.as_str()) == Some("text")
1312 && let Some(t) = part.get("text").and_then(|t| t.as_str())
1313 {
1314 if !text.is_empty() {
1315 text.push('\n');
1316 }
1317 text.push_str(t);
1318 }
1319 }
1320 Extracted {
1321 text,
1322 session,
1323 status: None,
1324 quota: None,
1325 dropped: None,
1326 commands: Vec::new(),
1327 context_tokens: None,
1328 }
1329 }
1330 AgentKind::Antigravity => {
1331 let obj = stdout
1334 .lines()
1335 .rev()
1336 .find_map(|l| serde_json::from_str::<serde_json::Value>(l.trim()).ok());
1337 let Some(v) = obj else {
1338 return Extracted {
1339 text: stdout.trim().to_owned(),
1340 ..Extracted::default()
1341 };
1342 };
1343 Extracted {
1344 text: v
1345 .get("response")
1346 .and_then(|r| r.as_str())
1347 .unwrap_or_default()
1348 .trim()
1349 .to_owned(),
1350 session: v
1351 .get("conversation_id")
1352 .and_then(|s| s.as_str())
1353 .map(str::to_owned),
1354 status: v.get("status").and_then(|s| s.as_str()).map(str::to_owned),
1355 quota: None,
1356 dropped: dropped_stream(&v),
1357 commands: Vec::new(),
1358 context_tokens: None,
1359 }
1360 }
1361 AgentKind::Codex => {
1362 let mut text = String::new();
1384 let mut session = None;
1385 let mut status = None;
1386 let mut commands = Vec::new();
1387 for line in stdout.lines() {
1388 let Ok(v) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
1389 continue;
1390 };
1391 match v.get("type").and_then(|t| t.as_str()) {
1392 Some("thread.started") => {
1393 session = v
1394 .get("thread_id")
1395 .and_then(|s| s.as_str())
1396 .map(str::to_owned);
1397 }
1398 Some("item.completed") => {
1399 let item = v.get("item").unwrap_or(&serde_json::Value::Null);
1400 match item.get("type").and_then(|t| t.as_str()) {
1401 Some("agent_message") => {
1402 if let Some(t) = item.get("text").and_then(|t| t.as_str()) {
1403 text = t.trim().to_owned();
1404 }
1405 }
1406 Some("command_execution") => {
1407 commands.push(command_evidence(item));
1408 }
1409 _ => {}
1410 }
1411 }
1412 Some("turn.completed") => status = Some("success".to_owned()),
1413 Some("turn.failed") => status = Some("error".to_owned()),
1414 _ => {}
1415 }
1416 }
1417 Extracted {
1418 text,
1419 session,
1420 status,
1421 quota: codex_quota(stdout),
1422 dropped: None,
1423 commands,
1424 context_tokens: None,
1425 }
1426 }
1427 AgentKind::Omp => {
1428 let mut text = String::new();
1449 let mut session = None;
1450 for line in stdout.lines() {
1451 let Ok(v) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
1452 continue;
1453 };
1454 if v.get("type").and_then(|t| t.as_str()) == Some("session") {
1455 session = v.get("id").and_then(|s| s.as_str()).map(str::to_owned);
1456 continue;
1457 }
1458 let messages: Vec<&serde_json::Value> = match v.get("type").and_then(|t| t.as_str())
1462 {
1463 Some("agent_end") => v
1464 .get("messages")
1465 .and_then(|m| m.as_array())
1466 .map(|m| m.iter().collect())
1467 .unwrap_or_default(),
1468 Some("turn_end") | Some("message_end") => {
1469 v.get("message").into_iter().collect()
1470 }
1471 _ => continue,
1472 };
1473 for message in messages {
1474 if message.get("role").and_then(|r| r.as_str()) != Some("assistant") {
1475 continue;
1476 }
1477 let Some(parts) = message.get("content").and_then(|c| c.as_array()) else {
1478 continue;
1479 };
1480 for part in parts {
1481 if part.get("type").and_then(|t| t.as_str()) != Some("text") {
1482 continue;
1483 }
1484 if let Some(t) = part.get("text").and_then(|t| t.as_str())
1485 && !t.trim().is_empty()
1486 {
1487 text = t.trim().to_owned();
1488 }
1489 }
1490 }
1491 }
1492 Extracted {
1493 text,
1494 session,
1495 status: None,
1496 quota: None,
1497 dropped: None,
1498 commands: Vec::new(),
1499 context_tokens: None,
1500 }
1501 }
1502 AgentKind::Command => {
1503 let parsed = serde_json::from_str::<serde_json::Value>(stdout.trim()).ok();
1508 let quota = parsed.as_ref().and_then(claude_quota);
1509 let dropped = parsed.as_ref().and_then(dropped_stream);
1512 Extracted {
1513 text: stdout.trim().to_owned(),
1514 session: None,
1515 status: None,
1516 quota,
1517 dropped,
1518 commands: Vec::new(),
1519 context_tokens: None,
1520 }
1521 }
1522 }
1523}
1524
1525fn command_evidence(item: &serde_json::Value) -> CommandEvidence {
1532 let description = match item.get("command") {
1533 Some(serde_json::Value::String(s)) => s.clone(),
1534 Some(serde_json::Value::Array(parts)) => parts
1535 .iter()
1536 .filter_map(|p| p.as_str())
1537 .collect::<Vec<_>>()
1538 .join(" "),
1539 _ => String::new(),
1540 };
1541 let result_summary = item
1542 .get("aggregated_output")
1543 .and_then(|o| o.as_str())
1544 .map(|s| tail_chars(s.trim(), 400))
1545 .unwrap_or_default();
1546 CommandEvidence {
1547 id: item
1548 .get("id")
1549 .and_then(|s| s.as_str())
1550 .unwrap_or_default()
1551 .to_owned(),
1552 description,
1553 exit_code: item
1554 .get("exit_code")
1555 .and_then(serde_json::Value::as_i64)
1556 .map(|e| e as i32),
1557 result_summary,
1558 source: "codex".to_owned(),
1559 }
1560}
1561
1562fn tail_chars(s: &str, max: usize) -> String {
1564 let count = s.chars().count();
1565 if count <= max {
1566 return s.to_owned();
1567 }
1568 s.chars().skip(count - max).collect()
1569}
1570
1571fn codex_quota(stdout: &str) -> Option<Quota> {
1574 let mut message = None;
1575 let mut failed = false;
1576 for line in stdout.lines() {
1577 let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else {
1578 continue;
1579 };
1580 match v.get("type").and_then(serde_json::Value::as_str) {
1581 Some("error") => {
1582 if let Some(m) = v.get("message").and_then(serde_json::Value::as_str)
1583 && m.starts_with("You've hit your usage limit. Visit https://chatgpt.com/settings/usage to purchase more credits")
1584 {
1585 message = Some(m.to_owned());
1586 }
1587 }
1588 Some("turn.failed") => failed = true,
1589 _ => {}
1590 }
1591 }
1592 if !failed {
1593 return None;
1594 }
1595 let message = message?;
1596 Some(Quota {
1597 reset: message
1598 .split_once("try again at ")
1599 .map(|(_, hint)| hint.trim().trim_end_matches('.').trim().to_owned())
1600 .filter(|hint| !hint.is_empty()),
1601 cause: QuotaCause::UsageLimit,
1602 agent: String::new(),
1603 })
1604}
1605
1606fn claude_quota(v: &serde_json::Value) -> Option<Quota> {
1613 let is_err = v.get("is_error").and_then(|e| e.as_bool()).unwrap_or(false);
1614 if !is_err {
1615 return None;
1616 }
1617 let result = v.get("result").and_then(|r| r.as_str()).unwrap_or("");
1618 if v.get("terminal_reason").and_then(serde_json::Value::as_str) == Some("api_error")
1619 && result.starts_with("Failed to authenticate:")
1620 && result.contains("OAuth session expired and could not be refreshed")
1621 {
1622 return Some(Quota {
1623 reset: None,
1624 cause: QuotaCause::Authentication,
1625 agent: String::new(),
1626 });
1627 }
1628 let status = v.get("api_error_status");
1629 let usage_limit = (status.and_then(serde_json::Value::as_u64) == Some(429)
1630 || status.and_then(serde_json::Value::as_str) == Some("429"))
1631 && v.get("api_error").and_then(serde_json::Value::as_str) == Some("usage_limit_reached");
1632 if !usage_limit && !result.to_lowercase().contains("session limit") {
1633 return None;
1634 }
1635 let reset = result
1638 .split("resets ")
1639 .nth(1)
1640 .map(str::trim)
1641 .filter(|s| !s.is_empty())
1642 .map(str::to_owned);
1643 Some(Quota {
1644 reset,
1645 cause: QuotaCause::UsageLimit,
1646 agent: String::new(),
1647 })
1648}
1649
1650fn agy_quota(stdout: &str, stderr: &str) -> Option<Quota> {
1665 let from_stdout = stdout
1666 .lines()
1667 .rev()
1668 .find_map(|l| serde_json::from_str::<serde_json::Value>(l.trim()).ok())
1669 .and_then(|v| {
1670 let status = v.get("status").and_then(|s| s.as_str()).unwrap_or("");
1671 let error = v.get("error").and_then(|e| e.as_str()).unwrap_or("");
1672 (status.eq_ignore_ascii_case("error") && error.to_lowercase().contains("quota reached"))
1673 .then(|| error.to_owned())
1674 });
1675 let from_stderr = || {
1676 stderr.lines().find_map(|l| {
1677 let v: serde_json::Value =
1678 serde_json::from_str(l.trim().strip_prefix("AGY_ERROR:")?.trim()).ok()?;
1679 let exhausted = v.get("status").and_then(|s| s.as_str()) == Some("RESOURCE_EXHAUSTED");
1680 let code = v.get("error_code").and_then(serde_json::Value::as_u64) == Some(429);
1681 (exhausted && code).then(|| {
1682 v.get("short_error")
1683 .and_then(|e| e.as_str())
1684 .unwrap_or_default()
1685 .to_owned()
1686 })
1687 })
1688 };
1689 let text = from_stdout.or_else(from_stderr)?;
1690 let reset = text
1691 .split_once("Resets ")
1692 .map(|(_, rest)| rest.trim().trim_end_matches('.').trim())
1693 .filter(|s| !s.is_empty())
1694 .map(str::to_owned);
1695 Some(Quota {
1696 reset,
1697 cause: QuotaCause::UsageLimit,
1698 agent: String::new(),
1699 })
1700}
1701
1702fn dropped_stream(v: &serde_json::Value) -> Option<Dropped> {
1733 let status = v.get("status").and_then(|s| s.as_str()).unwrap_or("");
1734 if !status.eq_ignore_ascii_case("error") {
1735 return None;
1736 }
1737 let response = v.get("response").and_then(|r| r.as_str()).unwrap_or("");
1738 if !response.trim().is_empty() {
1739 return None;
1741 }
1742 let produced = v
1743 .get("usage")
1744 .and_then(|u| u.get("output_tokens"))
1745 .and_then(serde_json::Value::as_u64)
1746 .unwrap_or(0);
1747 if produced == 0 {
1748 return None;
1750 }
1751 Some(Dropped {
1752 why: v
1753 .get("error")
1754 .and_then(|e| e.as_str())
1755 .unwrap_or("the CLI ended the stream without delivering its answer")
1756 .trim()
1757 .to_owned(),
1758 output_tokens: produced,
1759 })
1760}
1761
1762pub fn missing_programs(specs: &[AgentSpec]) -> Vec<String> {
1764 let mut missing = Vec::new();
1765 for s in specs {
1766 let program = match s.kind {
1767 AgentKind::Command => s.command.first().map(String::as_str),
1768 other => other.program(),
1769 };
1770 if let Some(p) = program
1771 && !crate::config::which(p)
1772 && !Path::new(p).is_file()
1773 && !missing.iter().any(|m: &String| m == p)
1774 {
1775 missing.push(p.to_owned());
1776 }
1777 }
1778 missing
1779}
1780
1781pub fn artifacts_dir(run_dir: &Path) -> PathBuf {
1783 run_dir.join("artifacts")
1784}
1785
1786pub fn installed(spec: &AgentSpec) -> bool {
1788 spec.kind.program().is_none_or(crate::config::which)
1791}
1792
1793pub fn pick(
1815 agents: &[AgentSpec],
1816 want: Option<&str>,
1817 available: &dyn Fn(&AgentSpec) -> bool,
1818) -> Result<AgentSpec> {
1819 if let Some(id) = want {
1820 let spec = agents
1821 .iter()
1822 .find(|a| a.id == id)
1823 .with_context(|| format!("no agent `{id}` in the roster; it has {}", ids(agents)))?;
1824 if !available(spec) {
1825 bail!(
1826 "agent `{}` needs `{}` on PATH; install it or pass a different \
1827 --agent",
1828 spec.id,
1829 spec.kind.program().unwrap_or("its command")
1830 );
1831 }
1832 return Ok(spec.clone());
1833 }
1834
1835 if agents.is_empty() {
1836 bail!(
1837 "the agent roster is empty, so there is nobody to ask: install one \
1838 of claude, opencode or agy - magi derives a roster from what is on \
1839 PATH - or add an [[agents]] entry to magi.toml."
1840 );
1841 }
1842
1843 if let Some(spec) = agents
1844 .iter()
1845 .find(|a| a.kind == AgentKind::Claude && available(a))
1846 {
1847 return Ok(spec.clone());
1848 }
1849
1850 agents
1851 .iter()
1852 .find(|a| available(a))
1853 .cloned()
1854 .with_context(|| {
1855 let missing = agents
1856 .iter()
1857 .filter_map(|a| a.kind.program())
1858 .collect::<Vec<_>>()
1859 .join(", ");
1860 format!(
1861 "no agent in the roster can be run here: install one of \
1862 {missing}, or add an [[agents]] entry to magi.toml for a CLI \
1863 you do have"
1864 )
1865 })
1866}
1867
1868pub fn for_github_text(spec: &AgentSpec, github_language: &str, cwd: &Path) -> Result<AgentSpec> {
1881 let mut spec = spec.clone();
1882 if spec.kind == AgentKind::Claude {
1883 let mut existing = None;
1886 let mut args = spec.extra_args.iter().enumerate();
1887 while let Some((index, arg)) = args.next() {
1888 if arg == "--settings" {
1889 let (value_index, value) = args.next().context("--settings requires a value")?;
1890 existing = Some((value_index, value.as_str(), false));
1891 } else if let Some(value) = arg.strip_prefix("--settings=") {
1892 existing = Some((index, value, true));
1893 }
1894 }
1895 let mut settings = if let Some((_, value, _)) = existing {
1896 let json = if value.trim_start().starts_with('{') {
1897 value.to_owned()
1898 } else {
1899 std::fs::read_to_string(cwd.join(value))
1900 .context("cannot read existing seat --settings file")?
1901 };
1902 serde_json::from_str::<serde_json::Value>(&json)
1903 .context("cannot parse existing seat --settings JSON")?
1904 } else {
1905 serde_json::json!({})
1906 };
1907 settings
1908 .as_object_mut()
1909 .context("seat --settings must be a JSON object")?
1910 .insert(
1911 "language".to_owned(),
1912 serde_json::json!(crate::lang::name(github_language)),
1913 );
1914 let settings = settings.to_string();
1915 if let Some((index, _, equals)) = existing {
1916 spec.extra_args[index] = if equals {
1917 format!("--settings={settings}")
1918 } else {
1919 settings
1920 };
1921 } else {
1922 spec.extra_args.extend(["--settings".to_owned(), settings]);
1923 }
1924 }
1925 Ok(spec)
1926}
1927
1928pub fn pick_chain(
1936 agents: &[AgentSpec],
1937 choice: Option<&AgentChoice>,
1938 available: &dyn Fn(&AgentSpec) -> bool,
1939 role: &str,
1940) -> Result<Vec<AgentSpec>> {
1941 let wanted = choice.map(AgentChoice::ids).unwrap_or_default();
1942 if wanted.is_empty() {
1943 return pick(agents, None, available)
1944 .map(|s| vec![s])
1945 .with_context(|| format!("choose an agent for the {role} role"));
1946 }
1947 let mut chain: Vec<AgentSpec> = Vec::new();
1948 for id in wanted {
1949 if chain.iter().any(|s| s.id == id) {
1950 continue;
1951 }
1952 match pick(agents, Some(id), available) {
1953 Ok(spec) => chain.push(spec),
1954 Err(e) => tracing::warn!("[roles] {role}: skipping `{id}`: {e:#}"),
1955 }
1956 }
1957 if chain.is_empty() {
1958 bail!(
1959 "[roles] {role} names no agent that can run here; the roster has {}",
1960 ids(agents)
1961 );
1962 }
1963 Ok(chain)
1964}
1965
1966pub fn chain_advances(outcome: &Result<AgentOutput>) -> bool {
1972 match outcome {
1973 Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => false,
1974 Err(_) => true,
1975 Ok(out) => output_advances(out),
1976 }
1977}
1978
1979pub fn output_advances(out: &AgentOutput) -> bool {
1983 out.quota_exhausted() || !out.usable()
1984}
1985
1986fn ids(agents: &[AgentSpec]) -> String {
1987 if agents.is_empty() {
1988 return "no agents at all".to_owned();
1989 }
1990 agents
1991 .iter()
1992 .map(|a| a.id.clone())
1993 .collect::<Vec<_>>()
1994 .join(", ")
1995}
1996
1997#[cfg(all(test, unix))]
2000pub(crate) mod test_watchdog {
2001 use super::*;
2002 static FLOORS: Mutex<BTreeMap<String, u64>> = Mutex::new(BTreeMap::new());
2003
2004 pub(crate) struct Guard(String);
2005
2006 pub(crate) fn set(run: &str, floor: u64) -> Guard {
2007 assert!(
2008 FLOORS
2009 .lock()
2010 .unwrap()
2011 .insert(run.to_owned(), floor)
2012 .is_none()
2013 );
2014 Guard(run.to_owned())
2015 }
2016
2017 pub(super) fn floor(run: &str, configured: u64) -> u64 {
2018 FLOORS
2019 .lock()
2020 .unwrap()
2021 .get(run)
2022 .copied()
2023 .unwrap_or(configured)
2024 }
2025
2026 impl Drop for Guard {
2027 fn drop(&mut self) {
2028 FLOORS.lock().unwrap().remove(&self.0);
2029 }
2030 }
2031}
2032
2033#[cfg(test)]
2034mod tests {
2035 use super::*;
2036
2037 const COMMAND_HELPER_MODE: &str = "MAGI_TEST_COMMAND_HELPER_MODE";
2038
2039 fn command_helper(mode: &str) -> AgentSpec {
2042 crate::run::pin_test_home();
2044 AgentSpec {
2045 id: "helper".to_owned(),
2046 kind: AgentKind::Command,
2047 model: None,
2048 command: vec![
2049 std::env::current_exe()
2050 .expect("locate test helper")
2051 .to_string_lossy()
2052 .into_owned(),
2053 "--exact".to_owned(),
2054 "agent::tests::command_agent_test_helper".to_owned(),
2055 "--nocapture".to_owned(),
2056 ],
2057 extra_args: Vec::new(),
2058 env: BTreeMap::from([(COMMAND_HELPER_MODE.to_owned(), mode.to_owned())]),
2059 prompt_delivery: None,
2060 max_turn_secs: None,
2061 }
2062 }
2063
2064 #[test]
2065 fn command_agent_test_helper() {
2066 match std::env::var(COMMAND_HELPER_MODE).as_deref() {
2067 Ok("reply") => println!("hello {}", std::env::var("MAGI_SEAT").unwrap()),
2068 Ok("cache") => println!("{}", std::env::var("CARGO_TARGET_DIR").unwrap()),
2069 Ok("no-cache") => println!(
2070 "{}",
2071 std::env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| "ABSENT".to_owned())
2072 ),
2073 Ok("ignore-stdin") => println!("done"),
2074 Ok("chatty-sleep") => {
2075 println!("i-said-something");
2076 std::thread::sleep(Duration::from_secs(30));
2077 }
2078 Ok("sleep") => std::thread::sleep(Duration::from_secs(30)),
2079 Ok(other) => panic!("unknown command helper mode {other}"),
2080 Err(_) => {}
2081 }
2082 }
2083
2084 fn spec(kind: AgentKind, model: Option<&str>) -> AgentSpec {
2085 AgentSpec {
2086 id: "a".to_owned(),
2087 kind,
2088 model: model.map(str::to_owned),
2089 command: vec!["echo".to_owned(), "{label}".to_owned()],
2090 extra_args: Vec::new(),
2091 env: BTreeMap::new(),
2092 prompt_delivery: None,
2093 max_turn_secs: None,
2094 }
2095 }
2096
2097 fn inv<'a>(cwd: &'a Path, art: &'a Path, allow_write: bool) -> Invocation<'a> {
2098 Invocation {
2099 coordination: None,
2100 fetched_base: None,
2101 cwd,
2102 prompt: "do the thing",
2103 timeout: Duration::from_secs(900),
2104 allow_write,
2105 sessions: true,
2106 artifacts: art,
2107 stem: "t",
2108 run: "test-run",
2109 node: "test",
2110 cache_dir: None,
2111 attachments: &[],
2112 writable: &[],
2113 }
2114 }
2115
2116 fn plan_for(kind: AgentKind, seat: &SeatState, allow_write: bool) -> Plan {
2117 build_command(
2118 &spec(kind, None),
2119 seat,
2120 &inv(Path::new("."), Path::new("/art"), allow_write),
2121 Path::new("/art/p.md"),
2122 )
2123 .unwrap()
2124 }
2125
2126 #[test]
2127 fn editing_access_requires_fetch_evidence_and_keeps_snapshot() {
2128 let missing = editing_access_note(None);
2129 assert!(missing.contains("No successful launcher fetch evidence"));
2130 let base = crate::run::FetchedBase {
2131 remote: "origin".into(),
2132 branch: "main".into(),
2133 commit: "0123456789abcdef".into(),
2134 fetched_at: "2026-10-18T00:00:00Z".parse().unwrap(),
2135 };
2136 let note = editing_access_note(Some(&base));
2137 for expected in [
2138 "origin/main",
2139 "0123456789abcdef",
2140 "2026-10-18T00:00:00Z",
2141 "Do not fetch again",
2142 ] {
2143 assert!(note.contains(expected), "missing {expected}");
2144 }
2145 for text in [&missing, ¬e] {
2148 assert!(!text.to_lowercase().contains("sandbox"), "{text}");
2149 assert!(!text.contains("Network access is restricted"), "{text}");
2150 }
2151 let roundtrip: crate::run::FetchedBase =
2152 serde_json::from_str(&serde_json::to_string(&base).unwrap()).unwrap();
2153 assert_eq!(editing_access_note(Some(&roundtrip)), note);
2154 }
2155
2156 #[test]
2157 fn codex_editing_seats_bypass_the_sandbox_on_initial_and_resume() {
2158 const BYPASS: &str = "--dangerously-bypass-approvals-and-sandbox";
2159 let roots = [PathBuf::from("/shared/git"), PathBuf::from("/questions")];
2160 for resumed in [false, true] {
2161 let mut seat = SeatState::new("impl-A", "a", 7);
2162 if resumed {
2163 seat.turns = 1;
2164 seat.captured_session = Some("fixture-thread".into());
2165 }
2166 let build = |invocation: &Invocation<'_>| {
2167 build_command(
2168 &spec(AgentKind::Codex, None),
2169 &seat,
2170 invocation,
2171 Path::new("/art/p.md"),
2172 )
2173 .unwrap()
2174 };
2175 for node in [
2176 "implement",
2177 "fix",
2178 "graft",
2179 "gate-fix",
2180 "land",
2181 "rebase",
2182 "base-conflict",
2183 crate::queue::CHAT_NODE,
2184 ] {
2185 let mut invocation = inv(Path::new("."), Path::new("/art"), true);
2186 invocation.node = node;
2187 invocation.writable = &roots;
2188 let plan = build(&invocation);
2189 let at = plan.argv.iter().position(|s| s == BYPASS);
2190 assert!(at.is_some(), "{node}: {:?}", plan.argv);
2191 if resumed {
2192 let resume = plan.argv.iter().position(|s| s == "resume").unwrap();
2193 assert!(at.unwrap() < resume, "{node}: {:?}", plan.argv);
2194 }
2195 assert!(!plan.argv.iter().any(|s| s == "--sandbox"), "{node}");
2197 assert!(!plan.argv.iter().any(|s| s == "-c"), "{node}");
2198 }
2199 for (node, write) in [
2200 ("review", false),
2201 ("judge", false),
2202 ("advise", false),
2203 ("implement", false),
2204 ("fix", false),
2205 ("dupes", false),
2206 ("conduct", false),
2207 ("waiter", false),
2208 ("talk-title", false),
2209 (crate::queue::CHAT_NODE, false),
2210 ("deputy", true),
2211 ] {
2212 let mut invocation = inv(Path::new("."), Path::new("/art"), write);
2213 invocation.node = node;
2214 let plan = build(&invocation);
2215 assert!(!plan.argv.iter().any(|s| s == BYPASS), "{node}");
2216 let mode = if write {
2217 "workspace-write"
2218 } else {
2219 "read-only"
2220 };
2221 assert!(
2222 plan.argv.windows(2).any(|w| w == ["--sandbox", mode]),
2223 "{node}: {:?}",
2224 plan.argv
2225 );
2226 assert!(
2227 plan.argv
2228 .windows(2)
2229 .any(|w| w == ["-c", "approval_policy=\"never\""]),
2230 "{node}"
2231 );
2232 }
2233 }
2234 }
2235
2236 #[test]
2237 fn claude_mints_then_resumes_the_same_uuid() {
2238 let mut seat = SeatState::new("judge-1", "a", 7);
2239 let uuid = seat.claude_session.clone().unwrap();
2240 let first = plan_for(AgentKind::Claude, &seat, true);
2241 assert!(first.argv.windows(2).any(|w| w == ["--session-id", &uuid]));
2242 assert!(!first.argv.iter().any(|a| a == "--resume"));
2243
2244 seat.turns = 1;
2245 let second = plan_for(AgentKind::Claude, &seat, true);
2246 assert!(second.argv.windows(2).any(|w| w == ["--resume", &uuid]));
2247 assert!(!second.argv.iter().any(|a| a == "--session-id"));
2248 }
2249
2250 #[test]
2251 fn github_bound_claude_seats_override_the_operators_answer_language() {
2252 let seat = SeatState::new("change-summary", "a", 7);
2253 let art = Path::new("/art");
2254 for (language, name) in [("en", "English"), ("", "English"), ("ja", "Japanese")] {
2255 let claude =
2256 for_github_text(&spec(AgentKind::Claude, None), language, Path::new(".")).unwrap();
2257 let plan = build_command(
2258 &claude,
2259 &seat,
2260 &inv(Path::new("."), art, false),
2261 Path::new("/art/p.md"),
2262 )
2263 .unwrap();
2264 let settings = format!(r#"{{"language":"{name}"}}"#);
2265 assert!(
2266 plan.argv
2267 .windows(2)
2268 .any(|w| w == ["--settings", settings.as_str()]),
2269 "{:?}",
2270 plan.argv
2271 );
2272 assert_eq!(plan.stdin.as_deref(), Some("do the thing"));
2275 }
2276 for kind in [
2277 AgentKind::Codex,
2278 AgentKind::Opencode,
2279 AgentKind::Antigravity,
2280 AgentKind::Omp,
2281 ] {
2282 assert!(
2283 for_github_text(&spec(kind, None), "en", Path::new("."))
2284 .unwrap()
2285 .extra_args
2286 .is_empty()
2287 );
2288 }
2289 }
2290
2291 #[test]
2292 fn github_text_preserves_existing_settings() {
2293 let dir = tempfile::tempdir().unwrap();
2294 let original = serde_json::json!({
2295 "language": "Japanese",
2296 "env": { "SEAT_MODE": "configured" },
2297 "apiKeyHelper": "credential-helper",
2298 "hooks": { "Stop": [] }
2299 });
2300 std::fs::write(dir.path().join("seat-settings.json"), original.to_string()).unwrap();
2301 for value in [original.to_string(), "./seat-settings.json".to_owned()] {
2302 for equals in [false, true] {
2303 let mut spec = spec(AgentKind::Claude, None);
2304 spec.extra_args = vec!["--settings={\"language\":\"French\"}".to_owned()];
2306 if equals {
2307 spec.extra_args.push(format!("--settings={value}"));
2308 } else {
2309 spec.extra_args
2310 .extend(["--settings".to_owned(), value.clone()]);
2311 }
2312 spec.extra_args.push("--verbose".to_owned());
2313 let updated = for_github_text(&spec, "en", dir.path()).unwrap();
2314 assert_eq!(updated.extra_args.len(), spec.extra_args.len());
2315 assert_eq!(updated.extra_args[0], spec.extra_args[0]);
2316 assert_eq!(updated.extra_args.last(), spec.extra_args.last());
2317 let value = &updated.extra_args[updated.extra_args.len() - 2];
2318 let actual: serde_json::Value =
2319 serde_json::from_str(value.strip_prefix("--settings=").unwrap_or(value))
2320 .unwrap();
2321 let mut expected = original.clone();
2322 expected["language"] = serde_json::json!("English");
2323 assert_eq!(actual, expected);
2324 }
2325 }
2326 let on_disk: serde_json::Value = serde_json::from_str(
2327 &std::fs::read_to_string(dir.path().join("seat-settings.json")).unwrap(),
2328 )
2329 .unwrap();
2330 assert_eq!(on_disk, original);
2331 }
2332
2333 #[test]
2334 fn github_text_settings_are_redacted_from_command_logging() {
2335 let dir = tempfile::tempdir().unwrap();
2336 let settings = serde_json::json!({ "env": { "AUTH_TOKEN": "test-only-secret" } });
2337 std::fs::write(dir.path().join("seat-settings.json"), settings.to_string()).unwrap();
2338 for equals in [false, true] {
2339 let mut spec = spec(AgentKind::Claude, None);
2340 spec.extra_args =
2341 vec!["--settings={\"env\":{\"AUTH_TOKEN\":\"earlier-secret\"}}".to_owned()];
2342 if equals {
2343 spec.extra_args
2344 .push("--settings=./seat-settings.json".to_owned());
2345 } else {
2346 spec.extra_args
2347 .extend(["--settings".to_owned(), "./seat-settings.json".to_owned()]);
2348 }
2349 let spec = for_github_text(&spec, "en", dir.path()).unwrap();
2350 let plan = build_command(
2351 &spec,
2352 &SeatState::new("change-summary", "a", 7),
2353 &inv(dir.path(), dir.path(), false),
2354 &dir.path().join("prompt.md"),
2355 )
2356 .unwrap();
2357 let actual = plan.argv.last().unwrap();
2359 let actual: serde_json::Value =
2360 serde_json::from_str(actual.strip_prefix("--settings=").unwrap_or(actual)).unwrap();
2361 assert_eq!(actual["env"]["AUTH_TOKEN"], "test-only-secret");
2362 assert_eq!(actual["language"], "English");
2363 let logged = format!("{:?}", plan.logged_argv());
2364 assert!(!logged.contains("secret"));
2365 assert!(!logged.contains("AUTH_TOKEN"));
2366 assert!(logged.contains("[redacted]"));
2367 assert_eq!(plan.logged_argv()[0], "claude");
2368 assert!(plan.logged_argv().contains(&"--output-format"));
2369 }
2370 }
2371
2372 #[test]
2373 fn github_text_rejects_unreadable_or_invalid_settings() {
2374 let dir = tempfile::tempdir().unwrap();
2375 std::fs::write(dir.path().join("bad.json"), "invalid json").unwrap();
2376 std::fs::write(dir.path().join("array.json"), "[]").unwrap();
2377 for args in [
2378 vec!["--settings"],
2379 vec!["--settings", "missing.json"],
2380 vec!["--settings=bad.json"],
2381 vec!["--settings", "array.json"],
2382 ] {
2383 let mut spec = spec(AgentKind::Claude, None);
2384 spec.extra_args = args.into_iter().map(str::to_owned).collect();
2385 assert!(for_github_text(&spec, "en", dir.path()).is_err());
2386 }
2387 }
2388
2389 #[test]
2390 fn read_only_seats_cannot_edit() {
2391 let seat = SeatState::new("judge-1", "a", 7);
2392 let claude = plan_for(AgentKind::Claude, &seat, false);
2393 assert!(claude.argv.iter().any(|a| a == "--disallowed-tools"));
2394 assert!(
2395 !plan_for(AgentKind::Claude, &seat, true)
2396 .argv
2397 .iter()
2398 .any(|a| a == "--disallowed-tools")
2399 );
2400
2401 let agy = plan_for(AgentKind::Antigravity, &seat, false);
2402 assert!(agy.argv.windows(2).any(|w| w == ["--mode", "plan"]));
2403 assert!(
2404 !agy.argv
2405 .iter()
2406 .any(|a| a == "--dangerously-skip-permissions")
2407 );
2408 let agy_rw = plan_for(AgentKind::Antigravity, &seat, true);
2409 assert!(
2410 agy_rw
2411 .argv
2412 .windows(2)
2413 .any(|w| w == ["--mode", "accept-edits"])
2414 );
2415 assert!(
2416 agy_rw
2417 .argv
2418 .iter()
2419 .any(|a| a == "--dangerously-skip-permissions")
2420 );
2421 let agy_prompt = agy_rw
2426 .argv
2427 .iter()
2428 .position(|a| a == "-p")
2429 .map(|i| agy_rw.argv[i + 1].clone())
2430 .expect("agy takes its prompt with -p");
2431 assert!(
2432 agy_prompt.starts_with('@'),
2433 "agy must get a file reference, got {agy_prompt:?}"
2434 );
2435 assert!(
2436 !agy_prompt.contains("Read the file at"),
2437 "the prose pointer is for CLIs with no file syntax"
2438 );
2439
2440 for allow_write in [false, true] {
2445 assert!(
2446 plan_for(AgentKind::Opencode, &seat, allow_write)
2447 .argv
2448 .iter()
2449 .any(|a| a == "--auto"),
2450 "opencode needs --auto even to read (allow_write = {allow_write})"
2451 );
2452 }
2453 }
2454
2455 #[test]
2458 fn codex_gets_extra_writable_roots_only_when_it_may_write() {
2459 let seat = SeatState::new("deputy-x", "a", 7);
2460 let roots = [PathBuf::from("/data/questions")];
2461 let mk = |allow_write: bool| {
2462 let mut i = inv(Path::new("."), Path::new("/art"), allow_write);
2463 i.writable = &roots;
2464 build_command(
2465 &spec(AgentKind::Codex, None),
2466 &seat,
2467 &i,
2468 Path::new("/art/p.md"),
2469 )
2470 .unwrap()
2471 };
2472 let want = "sandbox_workspace_write.writable_roots=[\"/data/questions\"]";
2473 assert!(mk(true).argv.windows(2).any(|w| w == ["-c", want]));
2474 assert!(!mk(false).argv.iter().any(|a| a.contains("writable_roots")));
2475 }
2476
2477 #[test]
2478 fn repository_write_scope_covers_editing_nodes_without_changing_other_roles() {
2479 let mut i = inv(Path::new("."), Path::new("/art"), true);
2480 for node in [
2481 "implement",
2482 "fix",
2483 "graft",
2484 "gate-fix",
2485 "land",
2486 "rebase",
2487 "base-conflict",
2488 "chat",
2489 ] {
2490 i.node = node;
2491 assert!(repository_writer(&i), "{node}");
2492 i.allow_write = false;
2493 assert!(!repository_writer(&i), "{node}");
2494 i.allow_write = true;
2495 }
2496 for node in ["deputy", "judge", "review", "bump", "conduct", "talk-title"] {
2497 i.node = node;
2498 assert!(!repository_writer(&i), "{node}");
2499 }
2500 i.node = "chat";
2501 let roots = [PathBuf::from("/questions")];
2502 i.writable = &roots;
2503 assert!(
2504 repository_writer(&i),
2505 "explicit roots do not change the role"
2506 );
2507 assert!(
2508 !repository_seat(&i),
2509 "chat turns bypass repository scheduling"
2510 );
2511 }
2512
2513 #[test]
2514 fn coordination_classification_is_independent_of_write_grants() {
2515 let roots = [PathBuf::from("/questions")];
2516 for node in [
2517 crate::queue::CHAT_NODE,
2518 "implement",
2519 "fix",
2520 "graft",
2521 "gate-fix",
2522 "land",
2523 "rebase",
2524 "base-conflict",
2525 "review",
2526 "judge",
2527 "advise",
2528 "deputy",
2529 "waiter",
2530 "conduct",
2531 "dupes",
2532 "talk-title",
2533 ] {
2534 for allow_write in [false, true] {
2535 for writable in [&[][..], &roots[..]] {
2536 let mut i = inv(Path::new("."), Path::new("/art"), allow_write);
2537 i.node = node;
2538 i.writable = writable;
2539 assert_eq!(
2540 repository_seat(&i),
2541 !matches!(
2542 node,
2543 crate::queue::CHAT_NODE | "talk-title" | "deputy" | "conduct" | "dupes"
2544 ),
2545 "{node}, allow_write={allow_write}, writable={writable:?}"
2546 );
2547 if node == crate::queue::CHAT_NODE {
2548 assert_eq!(repository_writer(&i), allow_write);
2549 }
2550 }
2551 }
2552 }
2553 }
2554
2555 #[test]
2556 fn writable_directories_reach_initial_and_resumed_adapter_commands() {
2557 let roots = [
2558 PathBuf::from("/shared/git"),
2559 PathBuf::from("/state/questions"),
2560 ];
2561 for kind in [AgentKind::Codex, AgentKind::Antigravity] {
2562 for resumed in [false, true] {
2563 let mut seat = SeatState::new("impl-A", "a", 7);
2564 if resumed {
2565 seat.turns = 1;
2566 seat.captured_session = Some("session-id".into());
2567 }
2568 for allow_write in [false, true] {
2569 let mut i = inv(Path::new("."), Path::new("/art"), allow_write);
2570 i.writable = &roots;
2571 let plan = build_command(&spec(kind, None), &seat, &i, Path::new("/art/p.md"))
2572 .unwrap();
2573 for root in &roots {
2574 if kind == AgentKind::Antigravity {
2575 assert_eq!(
2576 plan.argv.windows(2).any(|w| {
2577 w[0] == "--add-dir" && w[1] == root.to_str().unwrap()
2578 }),
2579 allow_write,
2580 "resumed={resumed}: {:?}",
2581 plan.argv
2582 );
2583 }
2584 assert_eq!(
2585 plan.argv
2586 .iter()
2587 .any(|arg| arg.contains(root.to_str().unwrap())),
2588 allow_write,
2589 "{kind:?}, resumed={resumed}: {:?}",
2590 plan.argv
2591 );
2592 }
2593 if kind == AgentKind::Codex && resumed {
2594 let at = plan.argv.iter().position(|s| s == "resume").unwrap();
2595 assert!(!plan.argv[at..].iter().any(|s| s == "-c"));
2596 }
2597 }
2598 }
2599 }
2600 }
2601
2602 #[test]
2603 fn codex_is_sandboxed_reads_stdin_and_puts_resume_last() {
2604 let mut seat = SeatState::new("judge-1", "a", 7);
2605
2606 let ro = plan_for(AgentKind::Codex, &seat, false);
2612 assert!(ro.argv.windows(2).any(|w| w == ["--sandbox", "read-only"]));
2613 let rw = plan_for(AgentKind::Codex, &seat, true);
2614 assert!(
2615 rw.argv
2616 .windows(2)
2617 .any(|w| w == ["--sandbox", "workspace-write"])
2618 );
2619 for p in [&ro, &rw] {
2620 assert!(
2621 !p.argv
2622 .iter()
2623 .any(|a| a == "--dangerously-bypass-approvals-and-sandbox"),
2624 "the bypass defeats the only enforced read-only mode we have"
2625 );
2626 assert!(
2628 p.argv
2629 .windows(2)
2630 .any(|w| w == ["-c", "approval_policy=\"never\""]),
2631 "an unattended seat that asks for approval blocks until timeout"
2632 );
2633 }
2634
2635 assert_eq!(ro.stdin.as_deref(), Some("do the thing"));
2637 assert_eq!(
2638 ro.argv.last().map(String::as_str),
2639 Some("-"),
2640 "without the `-` argument codex waits for a prompt it never gets"
2641 );
2642
2643 seat.turns = 1;
2647 assert!(!has_session(AgentKind::Codex, &seat, true));
2648 assert!(
2649 !plan_for(AgentKind::Codex, &seat, true)
2650 .argv
2651 .iter()
2652 .any(|a| a == "resume")
2653 );
2654 seat.captured_session = Some("01a07440-4545-7492-85c1-024e3259a90a".to_owned());
2655 let resumed = plan_for(AgentKind::Codex, &seat, true);
2656 let at = resumed
2657 .argv
2658 .iter()
2659 .position(|a| a == "resume")
2660 .expect("resumes by subcommand");
2661 assert_eq!(resumed.argv[at + 1], "01a07440-4545-7492-85c1-024e3259a90a");
2662 assert!(
2663 resumed.argv[..at].iter().any(|a| a == "--sandbox"),
2664 "every option precedes the subcommand"
2665 );
2666 assert_eq!(resumed.argv.last().map(String::as_str), Some("-"));
2667 }
2668
2669 #[test]
2672 fn omp_reads_stdin_auto_approves_and_resumes_by_id() {
2673 let mut seat = SeatState::new("review-1", "a", 7);
2674
2675 let first = plan_for(AgentKind::Omp, &seat, false);
2679 assert!(first.argv.iter().any(|a| a == "-p"));
2680 assert!(first.argv.iter().any(|a| a == "--mode=json"));
2681 assert_eq!(first.stdin.as_deref(), Some("do the thing"));
2682 assert!(
2683 !first.argv.iter().any(|a| a == "do the thing"),
2684 "the prompt reached argv, where Windows caps it"
2685 );
2686
2687 for allow_write in [false, true] {
2693 let p = plan_for(AgentKind::Omp, &seat, allow_write);
2694 assert!(
2695 p.argv.iter().any(|a| a == "--auto-approve"),
2696 "omp needs --auto-approve even to read (allow_write = {allow_write})"
2697 );
2698 assert!(
2699 !p.argv
2700 .iter()
2701 .any(|a| a == "--dangerously-bypass-approvals-and-sandbox"),
2702 "nothing ever asks for the bypass"
2703 );
2704 }
2705
2706 seat.turns = 1;
2709 assert!(!has_session(AgentKind::Omp, &seat, true));
2710 assert!(
2711 !plan_for(AgentKind::Omp, &seat, true)
2712 .argv
2713 .iter()
2714 .any(|a| a == "--resume")
2715 );
2716 seat.captured_session = Some("01a09fe9-4e31-7226-85b3-fda6f46689d5".to_owned());
2717 let resumed = plan_for(AgentKind::Omp, &seat, true);
2718 assert!(
2719 resumed
2720 .argv
2721 .windows(2)
2722 .any(|w| w == ["--resume", "01a09fe9-4e31-7226-85b3-fda6f46689d5"]),
2723 "a captured id is what makes the next turn a resume"
2724 );
2725 assert!(!resumed.argv.iter().any(|a| a == "--continue"));
2728 assert_eq!(resumed.stdin.as_deref(), Some("do the thing"));
2730 }
2731
2732 #[test]
2737 fn omp_takes_the_answer_without_an_agent_end_line() {
2738 let stream = concat!(
2739 r#"{"type":"session","version":3,"id":"01a09fe9-4e31-7226-85b3-fda6f46689d5","cwd":"C:\\w"}"#,
2740 "\n",
2741 r#"{"type":"agent_start"}"#,
2742 "\n",
2743 r#"{"type":"turn_start"}"#,
2744 "\n",
2745 r#"{"type":"message_update","assistantMessageEvent":{"type":"text_delta","contentIndex":1,"delta":"."}}"#,
2746 "\n",
2747 r#"{"type":"message_end","message":{"role":"assistant","content":[{"type":"thinking","thinking":"checking"},{"type":"text","text":"."}]}}"#,
2748 "\n",
2749 r#"{"type":"turn_end","message":{"role":"assistant","content":[{"type":"thinking","thinking":"done"},{"type":"text","text":"{\"vote\":\"approve\"}"}]}}"#,
2750 "\n",
2751 );
2752 let out = extract(AgentKind::Omp, stream);
2753 assert_eq!(
2754 out.text, "{\"vote\":\"approve\"}",
2755 "the last assistant text block is the answer even with no agent_end"
2756 );
2757 assert_eq!(
2758 out.session.as_deref(),
2759 Some("01a09fe9-4e31-7226-85b3-fda6f46689d5")
2760 );
2761 }
2762
2763 #[test]
2767 fn omp_walks_agent_end_and_ignores_tool_loop_narration() {
2768 let stream = concat!(
2769 r#"{"type":"session","version":3,"id":"s1"}"#,
2770 "\n",
2771 "{\"type\":\"agent_end\",\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"review this\"}]},{\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":\"Looking at the diff…\"}]},{\"role\":\"assistant\",\"content\":[{\"type\":\"thinking\",\"thinking\":\"…\"},{\"type\":\"text\",\"text\":\"## 判定\\n\\n問題ありません。\"}]}]}",
2772 "\n",
2773 );
2774 let out = extract(AgentKind::Omp, stream);
2775 assert_eq!(
2776 out.text, "## 判定\n\n問題ありません。",
2777 "the narration is not the answer, and non-ASCII survives intact"
2778 );
2779 assert_eq!(out.session.as_deref(), Some("s1"));
2780 }
2781
2782 #[test]
2785 fn omp_skips_non_json_lines() {
2786 let stream = concat!(
2787 "Warning: some omp notice\n",
2788 r#"{"type":"session","version":3,"id":"s2"}"#,
2789 "\n",
2790 r#"{"type":"message_end","message":{"role":"assistant","content":[{"type":"text","text":"the answer"}]}}"#,
2791 "\n",
2792 "trailing junk",
2793 "\n",
2794 );
2795 let out = extract(AgentKind::Omp, stream);
2796 assert_eq!(out.text, "the answer");
2797 assert_eq!(out.session.as_deref(), Some("s2"));
2798 }
2799
2800 #[test]
2802 fn codex_takes_the_last_agent_message_and_the_thread_id() {
2803 let stream = concat!(
2804 "2026-09-06T01:05:49.394445Z ERROR codex_models_manager: failed to load models cache\n",
2805 r#"{"type":"thread.started","thread_id":"01a07440-4545-7492-85c1-024e3259a90a"}"#,
2806 "\n",
2807 r#"{"type":"turn.started"}"#,
2808 "\n",
2809 r#"{"type":"item.completed","item":{"id":"item_0","type":"agent_message","text":"Looking into it."}}"#,
2810 "\n",
2811 r#"{"type":"item.completed","item":{"id":"item_1","type":"command_execution","text":"cargo test"}}"#,
2812 "\n",
2813 r#"{"type":"item.completed","item":{"id":"item_2","type":"agent_message","text":"{\"verdict\": \"ok\"}"}}"#,
2814 "\n",
2815 r#"{"type":"turn.completed","usage":{"input_tokens":17137}}"#,
2816 "\n",
2817 );
2818 let out = extract(AgentKind::Codex, stream);
2819 assert_eq!(
2820 out.text, "{\"verdict\": \"ok\"}",
2821 "the last agent message is the answer; earlier ones narrate"
2822 );
2823 assert_eq!(
2824 out.session.as_deref(),
2825 Some("01a07440-4545-7492-85c1-024e3259a90a")
2826 );
2827 assert_eq!(out.status.as_deref(), Some("success"));
2828
2829 let failed = concat!(
2830 r#"{"type":"thread.started","thread_id":"t1"}"#,
2831 "\n",
2832 r#"{"type":"turn.failed","error":{"message":"nope"}}"#,
2833 "\n",
2834 );
2835 assert_eq!(
2836 extract(AgentKind::Codex, failed).status.as_deref(),
2837 Some("error")
2838 );
2839 }
2840
2841 #[test]
2842 fn captured_sessions_resume_only_once_reported() {
2843 let mut seat = SeatState::new("impl-A", "a", 7);
2844 seat.turns = 1;
2845 for kind in [AgentKind::Opencode, AgentKind::Antigravity] {
2846 assert!(!has_session(kind, &seat, true));
2847 let p = plan_for(kind, &seat, true);
2848 assert!(!p.argv.iter().any(|a| a == "-s" || a == "--conversation"));
2849 }
2850
2851 seat.captured_session = Some("sid".to_owned());
2852 assert!(has_session(AgentKind::Opencode, &seat, true));
2853 assert!(
2854 plan_for(AgentKind::Opencode, &seat, true)
2855 .argv
2856 .windows(2)
2857 .any(|w| w == ["-s", "sid"])
2858 );
2859 assert!(
2860 plan_for(AgentKind::Antigravity, &seat, true)
2861 .argv
2862 .windows(2)
2863 .any(|w| w == ["--conversation", "sid"])
2864 );
2865 }
2866
2867 #[test]
2868 fn sessions_disabled_never_resumes() {
2869 let mut seat = SeatState::new("impl-A", "a", 7);
2870 seat.turns = 3;
2871 seat.captured_session = Some("sid".to_owned());
2872 for kind in [
2873 AgentKind::Claude,
2874 AgentKind::Opencode,
2875 AgentKind::Antigravity,
2876 ] {
2877 assert!(!has_session(kind, &seat, false));
2878 }
2879 }
2880
2881 #[test]
2882 fn long_prompts_never_reach_argv_for_file_delivery_clis() {
2883 let seat = SeatState::new("judge-1", "a", 7);
2884 for kind in [AgentKind::Opencode, AgentKind::Antigravity] {
2885 let p = plan_for(kind, &seat, false);
2886 assert!(
2887 p.argv.iter().all(|a| a != "do the thing"),
2888 "{kind:?} put the prompt on the command line"
2889 );
2890 assert!(p.argv.iter().any(|a| a.contains("/art/p.md")));
2891 }
2892 let p = plan_for(AgentKind::Antigravity, &seat, false);
2894 let at = p.argv.iter().position(|a| a == "-p").unwrap();
2895 assert!(p.argv.get(at + 1).is_some_and(|v| v.contains("p.md")));
2896 assert!(p.stdin.is_none());
2897 }
2898
2899 #[test]
2900 fn agy_print_timeout_tracks_the_node_budget() {
2901 let seat = SeatState::new("impl-A", "a", 7);
2902 let p = build_command(
2903 &spec(AgentKind::Antigravity, None),
2904 &seat,
2905 &Invocation {
2906 coordination: None,
2907 fetched_base: None,
2908 cwd: Path::new("."),
2909 prompt: "p",
2910 timeout: Duration::from_secs(3600),
2911 allow_write: true,
2912 sessions: true,
2913 artifacts: Path::new("/art"),
2914 stem: "t",
2915 run: "test-run",
2916 node: "test",
2917 cache_dir: None,
2918 attachments: &[],
2919 writable: &[],
2920 },
2921 Path::new("/art/p.md"),
2922 )
2923 .unwrap();
2924 assert!(p.argv.windows(2).any(|w| w == ["--print-timeout", "3600s"]));
2925 }
2926
2927 #[test]
2934 fn attachments_widen_antigravitys_add_dir_even_off_file_delivery() {
2935 let mut s = spec(AgentKind::Antigravity, None);
2936 s.prompt_delivery = Some(Delivery::Argv);
2937 let seat = SeatState::new("talk", "a", 7);
2938 let atts = [PathBuf::from("/art/attachments/abc.png")];
2939
2940 let without = build_command(
2941 &s,
2942 &seat,
2943 &Invocation {
2944 attachments: &[],
2945 writable: &[],
2946 ..inv(Path::new("."), Path::new("/art"), true)
2947 },
2948 Path::new("/art/p.md"),
2949 )
2950 .unwrap();
2951 assert!(
2952 !without.argv.iter().any(|a| a == "--add-dir"),
2953 "no attachment, no reason to widen the sandbox: {without:?}"
2954 );
2955
2956 let with = build_command(
2957 &s,
2958 &seat,
2959 &Invocation {
2960 attachments: &atts,
2961 writable: &[],
2962 ..inv(Path::new("."), Path::new("/art"), true)
2963 },
2964 Path::new("/art/p.md"),
2965 )
2966 .unwrap();
2967 assert!(
2968 with.argv.windows(2).any(|w| w == ["--add-dir", "/art"]),
2969 "an attachment outside cwd must widen the sandbox even off File delivery: {with:?}"
2970 );
2971 }
2972
2973 #[test]
2979 fn an_inherited_attachment_outside_this_conversations_artifacts_dir_gets_its_own_add_dir() {
2980 let seat = SeatState::new("plan", "a", 7);
2981 let atts = [
2982 PathBuf::from("/art/attachments/own.png"),
2983 PathBuf::from("/other-chat/attachments/inherited.png"),
2984 ];
2985
2986 let p = build_command(
2987 &spec(AgentKind::Antigravity, None),
2988 &seat,
2989 &Invocation {
2990 attachments: &atts,
2991 writable: &[],
2992 ..inv(Path::new("."), Path::new("/art"), true)
2993 },
2994 Path::new("/art/p.md"),
2995 )
2996 .unwrap();
2997
2998 assert!(
2999 p.argv.windows(2).any(|w| w == ["--add-dir", "/art"]),
3000 "this conversation's own artifacts dir must still be granted: {p:?}"
3001 );
3002 assert!(
3003 p.argv
3004 .windows(2)
3005 .any(|w| w == ["--add-dir", "/other-chat/attachments"]),
3006 "the inherited attachment's own directory must be granted too: {p:?}"
3007 );
3008 }
3009
3010 #[test]
3011 fn command_agents_get_placeholders_substituted() {
3012 let seat = SeatState::new("impl-A", "a", 7);
3013 let p = plan_for(AgentKind::Command, &seat, true);
3014 assert_eq!(p.argv[0], "echo");
3015 assert_eq!(p.argv[1], "impl-A");
3016 assert_eq!(p.stdin.as_deref(), Some("do the thing"));
3017 }
3018
3019 const EXPIRED_AUTH: &str = r#"{"is_error":true,"terminal_reason":"api_error","result":"Failed to authenticate: OAuth session expired and could not be refreshed"}"#;
3020 const CODEX_LIMIT: &str = r#"{"type":"error","message":"You've hit your usage limit. Visit https://chatgpt.com/settings/usage to purchase more credits or try again at Oct 27th, 2026 6:18 PM."}
3021{"type":"turn.failed","error":{"message":"You've hit your usage limit."}}"#;
3022
3023 #[test]
3024 fn observed_machine_failures_are_detected_conservatively() {
3025 let auth = extract(AgentKind::Claude, EXPIRED_AUTH).quota.unwrap();
3026 assert_eq!(auth.cause, QuotaCause::Authentication);
3027 assert_eq!(auth.reset, None);
3028 let limit = extract(AgentKind::Codex, CODEX_LIMIT).quota.unwrap();
3029 assert_eq!(limit.cause, QuotaCause::UsageLimit);
3030 assert_eq!(limit.reset.as_deref(), Some("Oct 27th, 2026 6:18 PM"));
3031 assert!(
3033 extract(AgentKind::Codex, &format!("{CODEX_LIMIT}\n{CODEX_LIMIT}"))
3034 .quota
3035 .is_some()
3036 );
3037 let without_reset = CODEX_LIMIT.replace(" or try again at Oct 27th, 2026 6:18 PM", "");
3038 assert!(
3039 extract(AgentKind::Codex, &without_reset)
3040 .quota
3041 .unwrap()
3042 .reset
3043 .is_none()
3044 );
3045 for text in [
3046 EXPIRED_AUTH.replace("true", "false"),
3047 EXPIRED_AUTH.replace("api_error", "unknown"),
3048 EXPIRED_AUTH.replace(
3049 "OAuth session expired and could not be refreshed",
3050 "unknown error",
3051 ),
3052 ] {
3053 assert!(extract(AgentKind::Claude, &text).quota.is_none());
3054 }
3055 assert!(
3056 extract(AgentKind::Codex, CODEX_LIMIT.lines().next().unwrap())
3057 .quota
3058 .is_none()
3059 );
3060 assert!(
3061 extract(
3062 AgentKind::Codex,
3063 &CODEX_LIMIT.replace("You've hit your usage limit.", "Something failed.")
3064 )
3065 .quota
3066 .is_none()
3067 );
3068 let quoted = serde_json::json!({"type":"item.completed","item":{"type":"agent_message","text":CODEX_LIMIT}}).to_string();
3069 assert!(extract(AgentKind::Codex, "ed).quota.is_none());
3070 assert!(extract(AgentKind::Codex, EXPIRED_AUTH).quota.is_none());
3071 assert!(
3072 extract(AgentKind::Antigravity, EXPIRED_AUTH)
3073 .quota
3074 .is_none()
3075 );
3076 let legacy: Quota = serde_json::from_str(r#"{"reset":null}"#).unwrap();
3077 assert_eq!(legacy.cause, QuotaCause::UsageLimit);
3078 }
3079
3080 #[test]
3081 fn claude_rate_limit_is_detected_and_reset_read_when_present() {
3082 let stdout = r#"{"is_error": true, "terminal_reason": "api_error",
3084 "result": "You've hit your session limit · resets 4:50am (Asia/Tokyo)",
3085 "session_id": "b8e928f1-754e-4bd3-86c5-0567763654e3"}"#;
3086 let out = extract(AgentKind::Claude, stdout);
3087 let quota = out.quota.as_ref().expect("rate limit must be detected");
3088 assert_eq!(
3089 quota.reset.as_deref(),
3090 Some("4:50am (Asia/Tokyo)"),
3091 "reset time read from the body"
3092 );
3093 }
3094
3095 #[test]
3096 fn claude_rate_limit_without_a_readable_reset_is_still_detected() {
3097 let out = extract(
3098 AgentKind::Claude,
3099 r#"{"is_error":true,"result":"session limit reached"}"#,
3100 );
3101 let quota = out.quota.expect("rate limit detected without a reset");
3102 assert!(quota.reset.is_none(), "unknown reset is kept as unknown");
3103 }
3104
3105 #[test]
3106 fn claude_structured_usage_limit_requires_the_error_and_exact_pair() {
3107 for kind in [AgentKind::Claude, AgentKind::Command] {
3108 for reply in [
3109 r#"{"is_error":true,"api_error_status":429,"api_error":"usage_limit_reached"}"#,
3110 r#"{"is_error":true,"api_error_status":"429","api_error":"usage_limit_reached"}"#,
3111 ] {
3112 assert!(extract(kind, reply).quota.is_some(), "{reply}");
3113 }
3114 for reply in [
3115 r#"{"is_error":false,"api_error_status":429,"api_error":"usage_limit_reached"}"#,
3116 r#"{"is_error":true,"api_error_status":500,"api_error":"usage_limit_reached"}"#,
3117 r#"{"is_error":true,"api_error_status":429,"api_error":"other_error"}"#,
3118 r#"{"is_error":false,"api_error_status":"429","api_error":"usage_limit_reached"}"#,
3119 r#"{"is_error":true,"api_error_status":"500","api_error":"usage_limit_reached"}"#,
3120 r#"{"is_error":true,"api_error_status":"429","api_error":"other_error"}"#,
3121 r#"{"is_error":true,"api_error":"usage_limit_reached"}"#,
3122 ] {
3123 assert!(extract(kind, reply).quota.is_none(), "{reply}");
3124 }
3125 }
3126 }
3127
3128 #[test]
3129 fn ordinary_failures_are_never_quota() {
3130 let claude_fail = extract(
3132 AgentKind::Claude,
3133 r#"{"is_error":true,"result":"account does not exist"}"#,
3134 );
3135 assert!(claude_fail.quota.is_none());
3136
3137 let cmd_fail = extract(AgentKind::Command, "boom");
3139 assert!(cmd_fail.quota.is_none());
3140
3141 let success = extract(
3143 AgentKind::Command,
3144 r#"{"is_error":false,"result":"session limit is fine"}"#,
3145 );
3146 assert!(success.quota.is_none());
3147 }
3148
3149 #[test]
3157 fn codex_command_execution_events_are_captured_alongside_the_final_message() {
3158 let stream = concat!(
3159 r#"{"type":"thread.started","thread_id":"t1"}"#,
3160 "\n",
3161 r#"{"type":"item.completed","item":{"id":"item49","type":"command_execution","command":["bash","-lc","cargo test --test graph_cached_gate"],"exit_code":1,"aggregated_output":"test result: 1 passed; 1 failed"}}"#,
3162 "\n",
3163 r#"{"type":"item.completed","item":{"id":"item52","type":"command_execution","command":["bash","-lc","cargo test --test graph_cached_gate a_single_test"],"exit_code":0,"aggregated_output":"test result: 1 passed; 0 failed"}}"#,
3164 "\n",
3165 r#"{"type":"item.completed","item":{"id":"item99","type":"agent_message","text":"Both tests in the target pass."}}"#,
3166 "\n",
3167 r#"{"type":"turn.completed"}"#,
3168 "\n",
3169 );
3170 let out = extract(AgentKind::Codex, stream);
3171 assert_eq!(out.text, "Both tests in the target pass.");
3172 assert_eq!(out.commands.len(), 2, "{:?}", out.commands);
3173
3174 let paired = &out.commands[0];
3175 assert_eq!(paired.id, "item49");
3176 assert_eq!(paired.exit_code, Some(1));
3177 assert!(paired.description.contains("graph_cached_gate"));
3178 assert!(paired.result_summary.contains("1 failed"));
3179
3180 let solo = &out.commands[1];
3181 assert_eq!(solo.exit_code, Some(0));
3182
3183 assert!(
3187 out.commands
3188 .iter()
3189 .any(|c| c.exit_code != Some(0) && c.description.contains("graph_cached_gate")),
3190 "a failed run of the actual target must still be visible: {:?}",
3191 out.commands
3192 );
3193 }
3194
3195 #[test]
3196 fn command_agent_can_carry_the_claude_quota_shape() {
3197 let out = extract(
3198 AgentKind::Command,
3199 r#"{"is_error":true,"result":"You've hit your session limit · resets 1:00am (UTC)"}"#,
3200 );
3201 assert!(
3202 out.quota.is_some(),
3203 "a wrapper emitting the claude shape counts as quota"
3204 );
3205 }
3206
3207 #[test]
3208 fn claude_json_result_is_extracted() {
3209 let out = extract(
3210 AgentKind::Claude,
3211 r#"{"result":"all done","session_id":"abc","is_error":false}"#,
3212 );
3213 assert_eq!(out.text, "all done");
3214 assert_eq!(out.session.as_deref(), Some("abc"));
3215 assert_eq!(out.status.as_deref(), Some("success"));
3216 }
3217
3218 #[test]
3233 fn a_clean_cli_turn_is_not_the_same_fact_as_the_nodes_own_work_being_done() {
3234 let stdout = r#"{"type":"result","subtype":"success","is_error":false,"terminal_reason":"completed","stop_reason":"end_turn","result":"I'll pause here until the `cargo make check` background run reports back.","session_id":"11111111-1111-1111-1111-111111111111"}"#;
3235 let out = extract(AgentKind::Claude, stdout);
3236 assert_eq!(out.status.as_deref(), Some("success"));
3237 assert!(out.quota.is_none());
3238 assert!(!out.text.trim().is_empty());
3239
3240 let agent_out = AgentOutput {
3241 text: out.text.clone(),
3242 exit_code: Some(0),
3243 timed_out: false,
3244 duration_ms: 500,
3245 artifacts: Vec::new(),
3246 quota: out.quota,
3247 dropped: out.dropped,
3248 commands: out.commands,
3249 context_tokens: None,
3250 };
3251 assert!(
3252 agent_out.usable(),
3253 "the CLI turn itself ended cleanly and must read as usable"
3254 );
3255 assert!(
3256 crate::verdict::extract_json::<crate::verdict::FixReport>(&agent_out.text).is_err(),
3257 "a clean CLI turn is not proof the node's own report ever arrived"
3258 );
3259 }
3260
3261 #[test]
3262 fn opencode_event_stream_is_concatenated() {
3263 let stream = concat!(
3264 r#"{"type":"step_start","sessionID":"ses_1","part":{"type":"step-start"}}"#,
3265 "\n",
3266 r#"{"type":"text","sessionID":"ses_1","part":{"type":"text","text":"first"}}"#,
3267 "\n",
3268 "garbage line\n",
3269 r#"{"type":"text","sessionID":"ses_1","part":{"type":"text","text":"second"}}"#,
3270 "\n"
3271 );
3272 let out = extract(AgentKind::Opencode, stream);
3273 assert_eq!(out.text, "first\nsecond");
3274 assert_eq!(out.session.as_deref(), Some("ses_1"));
3275 }
3276
3277 #[test]
3278 fn agy_json_survives_a_leading_warning_line() {
3279 let stdout = concat!(
3280 "warning: --mode plan has no effect while slash commands are disabled.\n",
3281 r#"{"conversation_id":"eaf2d00a","status":"SUCCESS","response":"persimmon\n"}"#,
3282 "\n"
3283 );
3284 let out = extract(AgentKind::Antigravity, stdout);
3285 assert_eq!(out.text, "persimmon");
3286 assert_eq!(out.session.as_deref(), Some("eaf2d00a"));
3287 assert_eq!(out.status.as_deref(), Some("SUCCESS"));
3288 }
3289
3290 const AGY_DROPPED: &str = concat!(
3297 r#"{"conversation_id":"36743d06-c0b3-4b79-9fa2-23869289d7b6","status":"ERROR","#,
3298 r#""response":"","error":"the connection to the agent was interrupted before "#,
3299 r#"the response finished: subscriber fell behind updates, stalled for 5s","#,
3300 r#""duration_seconds":431.1941803,"num_turns":1,"usage":{"input_tokens":260113,"#,
3301 r#""output_tokens":14267,"thinking_tokens":9695,"cache_read_tokens":2200925,"#,
3302 r#""total_tokens":274380}}"#
3303 );
3304
3305 const AGY_QUOTA_OUT: &str = concat!(
3307 r#"{"conversation_id":"323c3b5b-0000","status":"ERROR","response":"","#,
3308 r#""error":"Individual quota reached. Please upgrade your subscription to "#,
3309 r#"increase your limits. Resets in 1h2m49s.","duration_seconds":265.9,"#,
3310 r#""num_turns":2,"usage":{"input_tokens":1000,"output_tokens":50}}"#
3311 );
3312 const AGY_QUOTA_ERR: &str = concat!(
3313 "error: Individual quota reached. Resets in 1h2m49s.\n",
3314 r#"AGY_ERROR: {"short_error":"RESOURCE_EXHAUSTED (code 429): Individual quota "#,
3315 r#"reached.","status":"RESOURCE_EXHAUSTED","error_code":429,"code_kind":"http","#,
3316 r#""retryable":true}"#,
3317 "\n"
3318 );
3319
3320 #[test]
3321 fn agy_out_of_quota_is_a_quota_with_the_reset_hint() {
3322 let both = agy_quota(AGY_QUOTA_OUT, AGY_QUOTA_ERR).expect("both streams");
3323 assert_eq!(both.reset.as_deref(), Some("in 1h2m49s"));
3324 let stdout_only = agy_quota(AGY_QUOTA_OUT, "").expect("stdout alone");
3325 assert_eq!(stdout_only.reset.as_deref(), Some("in 1h2m49s"));
3326 let stderr_only = agy_quota("not json", AGY_QUOTA_ERR).expect("stderr alone");
3328 assert!(stderr_only.reset.is_none());
3329 }
3330
3331 #[test]
3332 fn ordinary_agy_failures_are_not_a_quota() {
3333 assert!(agy_quota(AGY_DROPPED, "").is_none());
3334 assert!(agy_quota(r#"{"status":"ERROR","error":"boom"}"#, "").is_none());
3335 assert!(
3336 agy_quota(
3337 "",
3338 r#"AGY_ERROR: {"status":"RESOURCE_EXHAUSTED","error_code":500}"#
3339 )
3340 .is_none()
3341 );
3342 assert!(
3343 agy_quota(
3344 "",
3345 r#"AGY_ERROR: {"status":"UNAVAILABLE","error_code":429}"#
3346 )
3347 .is_none()
3348 );
3349 assert!(agy_quota(r#"{"status":"SUCCESS","response":"ok"}"#, "").is_none());
3350 }
3351
3352 #[test]
3353 fn a_cli_that_hangs_up_on_billed_work_is_not_an_agent_that_produced_nothing() {
3354 let out = extract(AgentKind::Antigravity, AGY_DROPPED);
3355 let dropped = out.dropped.expect("recognised as undelivered work");
3356 assert_eq!(dropped.output_tokens, 14267);
3357 assert!(
3358 dropped.why.contains("subscriber fell behind"),
3359 "the CLI's own words are kept for the record: {}",
3360 dropped.why
3361 );
3362 assert_eq!(
3365 out.session.as_deref(),
3366 Some("36743d06-c0b3-4b79-9fa2-23869289d7b6")
3367 );
3368 assert!(out.quota.is_none(), "a dropped stream is not a rate limit");
3369 }
3370
3371 #[test]
3372 fn an_error_with_nothing_produced_stays_an_ordinary_failure() {
3373 let bare = r#"{"conversation_id":"c1","status":"ERROR","response":"","error":"boom"}"#;
3377 assert!(extract(AgentKind::Antigravity, bare).dropped.is_none());
3378
3379 let answered = concat!(
3382 r#"{"conversation_id":"c2","status":"ERROR","response":"here it is","#,
3383 r#""usage":{"output_tokens":10}}"#
3384 );
3385 assert!(extract(AgentKind::Antigravity, answered).dropped.is_none());
3386
3387 let ok = concat!(
3389 r#"{"conversation_id":"c3","status":"SUCCESS","response":"done","#,
3390 r#""usage":{"output_tokens":10}}"#
3391 );
3392 assert!(extract(AgentKind::Antigravity, ok).dropped.is_none());
3393 }
3394
3395 #[test]
3396 fn an_undelivered_output_is_not_usable_but_is_worth_asking_again() {
3397 let out = AgentOutput {
3398 text: String::new(),
3399 exit_code: Some(1),
3400 timed_out: false,
3401 duration_ms: 431_194,
3402 artifacts: Vec::new(),
3403 quota: None,
3404 dropped: Some(Dropped {
3405 why: "subscriber fell behind updates".to_owned(),
3406 output_tokens: 14267,
3407 }),
3408 commands: Vec::new(),
3409 context_tokens: None,
3410 };
3411 assert!(!out.usable());
3412 assert!(out.work_undelivered());
3413 assert!(!out.quota_exhausted());
3416 }
3417
3418 #[test]
3419 fn non_json_stdout_falls_back_to_raw_text() {
3420 let out = extract(AgentKind::Antigravity, "plain answer\n");
3421 assert_eq!(out.text, "plain answer");
3422 assert!(out.session.is_none());
3423 }
3424
3425 #[tokio::test]
3426 async fn command_agent_round_trip_writes_artifacts() {
3427 let dir = tempfile::tempdir().unwrap();
3428 let art = dir.path().join("artifacts");
3429 let mut seat = SeatState::new("impl-A", "a", 7);
3430 let s = command_helper("reply");
3431 let out = invoke(
3432 &s,
3433 &mut seat,
3434 &Invocation {
3435 coordination: None,
3436 fetched_base: None,
3437 cwd: dir.path(),
3438 prompt: "unused",
3439 timeout: Duration::from_secs(30),
3440 allow_write: true,
3441 sessions: true,
3442 artifacts: &art,
3443 stem: "impl-A",
3444 run: "test-run",
3445 node: "test",
3446 cache_dir: None,
3447 attachments: &[],
3448 writable: &[],
3449 },
3450 )
3451 .await
3452 .unwrap();
3453 assert!(out.usable(), "{out:?}");
3454 assert!(out.text.contains("hello impl-A"), "{}", out.text);
3455 assert_eq!(seat.turns, 1);
3456 assert!(art.join("impl-A.prompt.md").is_file());
3457 assert!(art.join("impl-A.out").is_file());
3458 }
3459
3460 #[tokio::test]
3461 async fn the_invocation_cache_dir_reaches_the_seat_as_cargo_target_dir() {
3462 crate::run::pin_test_home();
3463 let dir = tempfile::tempdir().unwrap();
3467 let cache = dir.path().join("magi-cache");
3468 let mut seat = SeatState::new("impl-A", "a", 7);
3469 let s = command_helper("cache");
3470 let out = invoke(
3471 &s,
3472 &mut seat,
3473 &Invocation {
3474 coordination: None,
3475 fetched_base: None,
3476 cwd: dir.path(),
3477 prompt: "unused",
3478 timeout: Duration::from_secs(30),
3479 allow_write: true,
3480 sessions: true,
3481 artifacts: &dir.path().join("artifacts"),
3482 stem: "cache",
3483 run: "test-run",
3484 node: "test",
3485 cache_dir: Some(&cache),
3486 attachments: &[],
3487 writable: &[],
3488 },
3489 )
3490 .await
3491 .unwrap();
3492 assert!(out.usable(), "{out:?}");
3493 assert!(
3494 out.text.contains(cache.to_string_lossy().as_ref()),
3495 "the seat must see CARGO_TARGET_DIR = the shared cache"
3496 );
3497 }
3498
3499 #[tokio::test]
3500 async fn cache_dir_none_strips_a_cargo_target_dir_inherited_from_this_process() {
3501 let previous = std::env::var("CARGO_TARGET_DIR").ok();
3509 unsafe {
3514 std::env::set_var("CARGO_TARGET_DIR", "/should/never/reach/a/read-only/seat");
3515 }
3516 let dir = tempfile::tempdir().unwrap();
3517 let mut seat = SeatState::new("review-1", "a", 7);
3518 let s = command_helper("no-cache");
3519 let result = invoke(
3520 &s,
3521 &mut seat,
3522 &Invocation {
3523 coordination: None,
3524 fetched_base: None,
3525 cwd: dir.path(),
3526 prompt: "unused",
3527 timeout: Duration::from_secs(30),
3528 allow_write: false,
3529 sessions: true,
3530 artifacts: &dir.path().join("artifacts"),
3531 stem: "no-cache",
3532 run: "test-run",
3533 node: "test",
3534 cache_dir: None,
3535 attachments: &[],
3536 writable: &[],
3537 },
3538 )
3539 .await;
3540 unsafe {
3545 match &previous {
3546 Some(v) => std::env::set_var("CARGO_TARGET_DIR", v),
3547 None => std::env::remove_var("CARGO_TARGET_DIR"),
3548 }
3549 }
3550 let out = result.unwrap();
3551 assert!(out.usable(), "{out:?}");
3552 assert!(
3553 out.text.contains("ABSENT"),
3554 "a read-only seat must never inherit the process's own CARGO_TARGET_DIR: {}",
3555 out.text
3556 );
3557 }
3558
3559 #[tokio::test]
3560 async fn a_prompt_larger_than_the_pipe_buffer_does_not_deadlock() {
3561 let dir = tempfile::tempdir().unwrap();
3562 let mut seat = SeatState::new("impl-A", "a", 7);
3563 let s = command_helper("ignore-stdin");
3566 let big = "x".repeat(1_000_000);
3567 let out = invoke(
3568 &s,
3569 &mut seat,
3570 &Invocation {
3571 coordination: None,
3572 fetched_base: None,
3573 cwd: dir.path(),
3574 prompt: &big,
3575 timeout: Duration::from_secs(60),
3576 allow_write: true,
3577 sessions: true,
3578 artifacts: &dir.path().join("artifacts"),
3579 stem: "big",
3580 run: "test-run",
3581 node: "test",
3582 cache_dir: None,
3583 attachments: &[],
3584 writable: &[],
3585 },
3586 )
3587 .await
3588 .unwrap();
3589 assert!(out.usable(), "{out:?}");
3590 assert!(out.text.contains("done"), "{}", out.text);
3591 }
3592
3593 #[tokio::test]
3594 async fn agent_turn_cap_limits_a_direct_invocation() {
3595 let dir = tempfile::tempdir().unwrap();
3596 let artifacts = dir.path().join("artifacts");
3597 let mut seat = SeatState::new("impl-A", "helper", 7);
3598 let mut s = command_helper("sleep");
3599 s.max_turn_secs = Some(2);
3600 let out = invoke(&s, &mut seat, &inv(dir.path(), &artifacts, false))
3601 .await
3602 .unwrap();
3603 assert!(out.timed_out, "{out:?}");
3604 assert!(out.duration_ms < 20_000, "{out:?}");
3607 }
3608
3609 #[tokio::test]
3610 async fn timeout_is_reported_not_hung() {
3611 let dir = tempfile::tempdir().unwrap();
3612 let mut seat = SeatState::new("impl-A", "a", 7);
3613 let s = command_helper("sleep");
3614 let out = invoke(
3615 &s,
3616 &mut seat,
3617 &Invocation {
3618 coordination: None,
3619 fetched_base: None,
3620 cwd: dir.path(),
3621 prompt: "unused",
3622 timeout: Duration::from_millis(300),
3623 allow_write: true,
3624 sessions: true,
3625 artifacts: &dir.path().join("artifacts"),
3626 stem: "slow",
3627 run: "test-run",
3628 node: "test",
3629 cache_dir: None,
3630 attachments: &[],
3631 writable: &[],
3632 },
3633 )
3634 .await
3635 .unwrap();
3636 assert!(out.timed_out);
3637 assert!(!out.usable());
3638 }
3639
3640 #[tokio::test]
3641 async fn a_timeout_keeps_what_the_agent_had_already_printed() {
3642 let dir = tempfile::tempdir().unwrap();
3648 let artifacts = dir.path().join("artifacts");
3649 let mut seat = SeatState::new("impl-A", "a", 7);
3650 let s = command_helper("chatty-sleep");
3651 let out = invoke(
3652 &s,
3653 &mut seat,
3654 &Invocation {
3655 coordination: None,
3656 fetched_base: None,
3657 cwd: dir.path(),
3658 prompt: "unused",
3659 timeout: Duration::from_secs(10),
3664 allow_write: true,
3665 sessions: true,
3666 artifacts: &artifacts,
3667 stem: "chatty",
3668 run: "test-run",
3669 node: "test",
3670 cache_dir: None,
3671 attachments: &[],
3672 writable: &[],
3673 },
3674 )
3675 .await
3676 .unwrap();
3677
3678 assert!(out.timed_out, "{out:?}");
3679 assert!(!out.usable(), "a cut-off answer is still not an answer");
3680 let recorded = std::fs::read_to_string(artifacts.join("chatty.out")).unwrap();
3681 assert!(
3682 recorded.contains("i-said-something"),
3683 "the artifact must keep what arrived before the kill, got {recorded:?}"
3684 );
3685 assert!(
3686 out.text.contains("i-said-something"),
3687 "and the graph must be able to see it too, got {:?}",
3688 out.text
3689 );
3690 }
3691
3692 #[test]
3693 fn missing_programs_reports_command_binaries() {
3694 let mut s = spec(AgentKind::Command, None);
3695 s.command = vec!["definitely-not-a-real-binary-xyz".to_owned()];
3696 assert_eq!(
3697 missing_programs(&[s]),
3698 ["definitely-not-a-real-binary-xyz".to_owned()]
3699 );
3700 }
3701
3702 fn pick_spec(id: &str, kind: AgentKind) -> AgentSpec {
3703 AgentSpec {
3704 id: id.to_owned(),
3705 kind,
3706 model: None,
3707 command: Vec::new(),
3708 extra_args: Vec::new(),
3709 env: BTreeMap::new(),
3710 prompt_delivery: None,
3711 max_turn_secs: None,
3712 }
3713 }
3714
3715 fn without<'a>(missing: &'a [&'a str]) -> impl Fn(&AgentSpec) -> bool + 'a {
3718 move |a: &AgentSpec| !missing.contains(&a.id.as_str())
3719 }
3720
3721 #[test]
3722 fn pick_prefers_the_claude_seat_even_when_it_is_not_first_in_the_roster() {
3723 let agents = [
3724 pick_spec("oc", AgentKind::Opencode),
3725 pick_spec("opus", AgentKind::Claude),
3726 pick_spec("agy", AgentKind::Antigravity),
3727 ];
3728 let got = pick(&agents, None, &without(&[])).expect("a pick");
3729 assert_eq!(got.id, "opus");
3730 }
3731
3732 #[test]
3733 fn pick_falls_back_to_the_first_installed_agent_in_roster_order() {
3734 let agents = [
3735 pick_spec("opus", AgentKind::Claude),
3736 pick_spec("oc", AgentKind::Opencode),
3737 pick_spec("agy", AgentKind::Antigravity),
3738 ];
3739 let got = pick(&agents, None, &without(&["opus", "oc"])).expect("a pick");
3740 assert_eq!(got.id, "agy");
3741 }
3742
3743 #[test]
3744 fn pick_on_an_empty_roster_says_what_to_install() {
3745 let msg = pick(&[], None, &without(&[]))
3746 .expect_err("nobody to ask")
3747 .to_string();
3748 assert!(msg.contains("roster is empty"), "{msg}");
3749 assert!(msg.contains("claude"), "{msg}");
3750 assert!(msg.contains("magi.toml"), "{msg}");
3751 }
3752
3753 #[test]
3754 fn pick_on_a_roster_with_nothing_installed_names_the_programs_that_are_missing() {
3755 let agents = [
3756 pick_spec("opus", AgentKind::Claude),
3757 pick_spec("oc", AgentKind::Opencode),
3758 ];
3759 let err = pick(&agents, None, &without(&["opus", "oc"])).expect_err("nothing runnable");
3760 let msg = format!("{err:#}");
3761 assert!(msg.contains("claude"), "{msg}");
3762 assert!(msg.contains("opencode"), "{msg}");
3763 }
3764
3765 #[test]
3766 fn an_explicitly_named_agent_wins_over_the_claude_preference() {
3767 let agents = [
3768 pick_spec("opus", AgentKind::Claude),
3769 pick_spec("oc", AgentKind::Opencode),
3770 ];
3771 let got = pick(&agents, Some("oc"), &without(&[])).expect("a pick");
3772 assert_eq!(got.id, "oc");
3773 }
3774
3775 #[test]
3776 fn an_unknown_agent_id_lists_the_ids_that_do_exist() {
3777 let agents = [
3778 pick_spec("opus", AgentKind::Claude),
3779 pick_spec("oc", AgentKind::Opencode),
3780 ];
3781 let msg = pick(&agents, Some("gemini"), &without(&[]))
3782 .expect_err("no such agent")
3783 .to_string();
3784 assert!(msg.contains("gemini"), "{msg}");
3785 assert!(msg.contains("opus, oc"), "{msg}");
3786 }
3787
3788 #[test]
3789 fn an_explicitly_named_agent_that_is_not_installed_is_an_error_not_a_fallback() {
3790 let agents = [
3791 pick_spec("opus", AgentKind::Claude),
3792 pick_spec("oc", AgentKind::Opencode),
3793 ];
3794 let msg = pick(&agents, Some("oc"), &without(&["oc"]))
3795 .expect_err("must not silently substitute another model")
3796 .to_string();
3797 assert!(msg.contains("opencode"), "{msg}");
3798 assert!(msg.contains("--agent"), "{msg}");
3799 }
3800
3801 fn named(id: &str) -> AgentSpec {
3802 AgentSpec {
3803 id: id.to_owned(),
3804 ..spec(AgentKind::Command, None)
3805 }
3806 }
3807
3808 fn output(text: &str, exit: i32, quota: bool) -> AgentOutput {
3809 AgentOutput {
3810 text: text.to_owned(),
3811 exit_code: Some(exit),
3812 timed_out: false,
3813 duration_ms: 0,
3814 artifacts: Vec::new(),
3815 quota: quota.then_some(Quota {
3816 reset: None,
3817 cause: QuotaCause::UsageLimit,
3818 agent: String::new(),
3819 }),
3820 dropped: None,
3821 commands: Vec::new(),
3822 context_tokens: None,
3823 }
3824 }
3825
3826 #[test]
3827 fn a_chain_keeps_the_written_order_and_a_string_is_a_chain_of_one() {
3828 let agents = [named("a"), named("b"), named("c")];
3829 let all = |_: &AgentSpec| true;
3830 let chain = AgentChoice::Chain(vec!["c".into(), "a".into()]);
3831 let got = pick_chain(&agents, Some(&chain), &all, "synthesizer").unwrap();
3832 assert_eq!(
3833 got.iter().map(|s| s.id.as_str()).collect::<Vec<_>>(),
3834 ["c", "a"]
3835 );
3836
3837 let one = AgentChoice::from("b");
3838 let got = pick_chain(&agents, Some(&one), &all, "synthesizer").unwrap();
3839 assert_eq!(got.len(), 1);
3840 assert_eq!(got[0].id, "b");
3841
3842 let got = pick_chain(&agents, None, &all, "synthesizer").unwrap();
3843 assert_eq!(got.len(), 1, "unset keeps pick's default");
3844 assert_eq!(got[0].id, "a");
3845 let empty = AgentChoice::Chain(Vec::new());
3846 assert_eq!(
3847 pick_chain(&agents, Some(&empty), &all, "x").unwrap()[0].id,
3848 "a"
3849 );
3850 }
3851
3852 #[test]
3853 fn a_chain_skips_unknown_and_uninstalled_ids_and_tries_each_once() {
3854 let agents = [named("a"), named("b")];
3855 let not_a = |s: &AgentSpec| s.id != "a";
3856 let chain = AgentChoice::Chain(
3857 ["a", "ghost", "b", "b"]
3858 .iter()
3859 .map(|s| (*s).to_owned())
3860 .collect(),
3861 );
3862 let got = pick_chain(&agents, Some(&chain), ¬_a, "chatter").unwrap();
3863 assert_eq!(got.iter().map(|s| s.id.as_str()).collect::<Vec<_>>(), ["b"]);
3864
3865 let dup = AgentChoice::Chain(vec!["b".into(), "a".into(), "b".into()]);
3866 let got = pick_chain(&agents, Some(&dup), &|_| true, "chatter").unwrap();
3867 assert_eq!(
3868 got.iter().map(|s| s.id.as_str()).collect::<Vec<_>>(),
3869 ["b", "a"]
3870 );
3871 }
3872
3873 #[test]
3874 fn a_chain_with_nothing_runnable_names_the_role() {
3875 let agents = [named("a")];
3876 let chain = AgentChoice::Chain(vec!["a".into(), "ghost".into()]);
3877 let err = pick_chain(&agents, Some(&chain), &|_| false, "conductor")
3878 .unwrap_err()
3879 .to_string();
3880 assert!(err.contains("conductor"), "{err}");
3881 }
3882
3883 #[test]
3884 fn a_chain_advances_on_error_quota_or_an_unusable_answer_only() {
3885 assert!(chain_advances(&Err(anyhow::anyhow!("spawn failed"))));
3886 assert!(chain_advances(&Ok(output("limit", 0, true))));
3887 assert!(chain_advances(&Ok(output("", 0, false))));
3888 assert!(chain_advances(&Ok(output("x", 1, false))));
3889 assert!(!chain_advances(&Ok(output("answer", 0, false))));
3890 }
3891
3892 #[test]
3893 fn claude_context_tokens_are_unknown_because_usage_is_aggregated() {
3894 for out in [
3895 r#"{"result":"ok","num_turns":1,"usage":{"input_tokens":10,"cache_read_input_tokens":3000}}"#,
3896 r#"{"result":"ok","num_turns":3,"usage":{"input_tokens":10}}"#,
3897 r#"{"result":"ok"}"#,
3898 "not json",
3899 ] {
3900 assert_eq!(context_tokens(AgentKind::Claude, out), None, "{out}");
3901 }
3902 }
3903
3904 #[test]
3905 fn opencode_context_tokens_take_the_last_step_finish() {
3906 let out = concat!(
3907 r#"{"type":"step_finish","sessionID":"s","part":{"type":"step-finish","tokens":{"input":100,"output":5,"cache":{"read":1000,"write":50}}}}"#,
3908 "\n",
3909 r#"{"type":"text","part":{"type":"text","text":"hi"}}"#,
3910 "\n",
3911 r#"{"type":"step_finish","sessionID":"s","part":{"type":"step-finish","tokens":{"input":120,"output":9,"cache":{"read":1500}}}}"#,
3912 "\n"
3913 );
3914 assert_eq!(context_tokens(AgentKind::Opencode, out), Some(1620));
3915 let none = r#"{"type":"step_finish","part":{"type":"step-finish"}}"#;
3916 assert_eq!(context_tokens(AgentKind::Opencode, none), None);
3917 assert_eq!(context_tokens(AgentKind::Opencode, ""), None);
3918 }
3919
3920 #[test]
3921 fn agy_context_tokens_are_unknown_because_usage_is_aggregated() {
3922 let out = r#"{"conversation_id":"c","status":"OK","response":"x","usage":{"input_tokens":260113,"cache_read_tokens":2200925}}"#;
3923 assert_eq!(context_tokens(AgentKind::Antigravity, out), None);
3924 }
3925
3926 #[test]
3927 fn codex_context_tokens_are_unknown_because_usage_is_cumulative() {
3928 let out = concat!(
3929 r#"{"type":"turn.completed","usage":{"input_tokens":1000,"cached_input_tokens":900}}"#,
3930 "\n"
3931 );
3932 assert_eq!(context_tokens(AgentKind::Codex, out), None);
3933 }
3934
3935 #[test]
3936 fn omp_context_tokens_come_from_messages_without_an_agent_end() {
3937 let out = concat!(
3938 r#"{"type":"session","id":"s"}"#,
3939 "\n",
3940 r#"{"type":"message_end","message":{"role":"assistant","content":[],"usage":{"input":50,"cacheRead":400,"cacheWrite":10}}}"#,
3941 "\n",
3942 r#"{"type":"turn_end","message":{"role":"assistant","content":[],"usage":{"input":70,"cacheRead":500}}}"#,
3943 "\n"
3944 );
3945 assert_eq!(context_tokens(AgentKind::Omp, out), Some(570));
3946 let user_only = r#"{"type":"message_end","message":{"role":"user","usage":{"input":9}}}"#;
3947 assert_eq!(context_tokens(AgentKind::Omp, user_only), None);
3948 let no_usage = r#"{"type":"message_end","message":{"role":"assistant","content":[]}}"#;
3949 assert_eq!(context_tokens(AgentKind::Omp, no_usage), None);
3950 }
3951
3952 #[test]
3953 fn command_agents_report_no_context_tokens() {
3954 let out = r#"{"usage":{"input_tokens":5}}"#;
3955 assert_eq!(context_tokens(AgentKind::Command, out), None);
3956 }
3957}