1use std::collections::BTreeMap;
33use std::ffi::OsStr;
34use std::path::{Path, PathBuf};
35use std::process::Stdio;
36use std::time::{Duration, Instant};
37
38use anyhow::{Context as _, Result, bail};
39use serde::{Deserialize, Serialize};
40use std::sync::{Arc, Mutex};
41
42use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
43use tokio::process::Command;
44
45use crate::config::{AgentChoice, AgentKind, AgentSpec, Delivery};
46use crate::proc::Quiet as _;
47use crate::rng::SplitMix64;
48
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52pub struct SeatState {
53 pub key: String,
55 pub agent: String,
57 pub turns: usize,
59 pub claude_session: Option<String>,
62 pub captured_session: Option<String>,
64 #[serde(default, skip_serializing_if = "Option::is_none")]
67 pub omp_session_dir: Option<PathBuf>,
68}
69
70impl SeatState {
71 pub fn new(key: &str, agent: &str, run_seed: u64) -> Self {
73 let mut rng = SplitMix64::new(run_seed ^ crate::rng::fnv1a(key));
74 Self {
75 key: key.to_owned(),
76 agent: agent.to_owned(),
77 turns: 0,
78 claude_session: Some(rng.uuid_v4()),
79 captured_session: None,
80 omp_session_dir: None,
81 }
82 }
83}
84
85pub fn has_session(kind: AgentKind, seat: &SeatState, sessions_enabled: bool) -> bool {
87 if !sessions_enabled || seat.turns == 0 {
88 return false;
89 }
90 match kind {
91 AgentKind::Claude => seat.claude_session.is_some(),
92 AgentKind::Opencode | AgentKind::Antigravity | AgentKind::Codex | AgentKind::Omp => {
93 seat.captured_session.is_some()
94 }
95 AgentKind::Command => true,
96 }
97}
98
99#[derive(Debug, Clone)]
101pub struct Invocation<'a> {
102 pub coordination: Option<&'a crate::config::Coordination>,
104 pub fetched_base: Option<&'a crate::run::FetchedBase>,
106 pub cwd: &'a Path,
109 pub prompt: &'a str,
111 pub timeout: Duration,
113 pub allow_write: bool,
118 pub sessions: bool,
120 pub artifacts: &'a Path,
122 pub stem: &'a str,
124 pub run: &'a str,
128 pub node: &'a str,
132 pub cache_dir: Option<&'a Path>,
138 pub attachments: &'a [PathBuf],
145 pub writable: &'a [PathBuf],
152}
153
154fn repository_writer(inv: &Invocation<'_>) -> bool {
163 inv.allow_write
164 && (matches!(
165 inv.node,
166 "implement"
167 | "fix"
168 | "graft"
169 | "gate-fix"
170 | "land"
171 | "rebase"
172 | "base-conflict"
173 | "external-chat"
174 ) || inv.node == crate::queue::CHAT_NODE)
175}
176
177fn repository_seat(inv: &Invocation<'_>) -> bool {
178 !matches!(
184 inv.node,
185 crate::queue::CHAT_NODE | "external-chat" | "talk-title" | "deputy" | "conduct" | "dupes"
186 )
187}
188
189pub async fn worktree_writable_roots(cwd: &Path, home: &Path) -> Result<Vec<PathBuf>> {
196 let mut roots = Vec::new();
197 if let Some(common) = crate::repo_lock::common_dir(cwd).await? {
198 let cwd = std::fs::canonicalize(cwd).context("canonicalize seat working directory")?;
199 if !common.starts_with(&cwd) {
200 roots.push(common);
201 }
202 }
203 for name in ["questions", "notifications"] {
207 let dir = home.join(name);
208 std::fs::create_dir_all(&dir).with_context(|| format!("prepare seat {name} directory"))?;
209 roots.push(std::fs::canonicalize(dir)?);
210 }
211 Ok(roots)
212}
213
214fn editing_access_note(base: Option<&crate::run::FetchedBase>) -> String {
216 let mut note = String::from(
217 "Launcher repository access contract (applies to this turn and overrides earlier fetch instructions):\n",
218 );
219 if let Some(base) = base {
220 note.push_str(&format!(
221 "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",
222 base.remote, base.branch, base.fetched_at, base.commit,
223 ));
224 } else {
225 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");
226 }
227 note
228}
229
230#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
237pub struct Quota {
238 #[serde(default)]
240 pub cause: QuotaCause,
241 #[serde(default)]
243 pub agent: String,
244 #[serde(default)]
246 pub reset: Option<String>,
247}
248
249#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
251#[serde(rename_all = "snake_case")]
252pub enum QuotaCause {
253 #[default]
255 UsageLimit,
256 Authentication,
258}
259
260#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
267pub struct Dropped {
268 pub why: String,
270 pub output_tokens: u64,
273}
274
275#[derive(Debug, Clone, Serialize, Deserialize)]
289pub struct CommandEvidence {
290 pub id: String,
292 pub description: String,
294 pub exit_code: Option<i32>,
296 pub result_summary: String,
298 pub source: String,
300}
301
302#[derive(Debug, Clone, Serialize, Deserialize)]
304pub struct AgentOutput {
305 pub text: String,
307 pub exit_code: Option<i32>,
309 pub timed_out: bool,
311 pub duration_ms: u64,
313 pub artifacts: Vec<String>,
315 #[serde(default)]
319 pub quota: Option<Quota>,
320 #[serde(default)]
324 pub dropped: Option<Dropped>,
325 #[serde(default)]
329 pub commands: Vec<CommandEvidence>,
330 #[serde(default)]
335 pub context_tokens: Option<u64>,
336}
337
338impl AgentOutput {
339 pub fn usable(&self) -> bool {
341 !self.quota_exhausted()
342 && !self.timed_out
343 && self.exit_code == Some(0)
344 && !self.text.trim().is_empty()
345 }
346
347 pub fn quota_exhausted(&self) -> bool {
349 self.quota.is_some()
350 }
351
352 pub fn work_undelivered(&self) -> bool {
357 self.dropped.is_some()
358 }
359}
360
361#[derive(Debug)]
364pub(crate) struct ExecutionInterrupted(pub String);
365
366impl std::fmt::Display for ExecutionInterrupted {
367 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
368 write!(f, "execution interrupted: {}", self.0)
369 }
370}
371
372impl std::error::Error for ExecutionInterrupted {}
373
374const PIPE_GRACE: Duration = Duration::from_secs(3);
379
380pub(crate) type Captured = Arc<Mutex<Vec<u8>>>;
382
383pub(crate) fn drain<R>(pipe: Option<R>) -> (Captured, Option<tokio::task::JoinHandle<()>>)
393where
394 R: tokio::io::AsyncRead + Unpin + Send + 'static,
395{
396 let buf: Captured = Arc::new(Mutex::new(Vec::new()));
397 let Some(mut pipe) = pipe else {
398 return (buf, None);
399 };
400 let sink = Arc::clone(&buf);
401 let handle = tokio::spawn(async move {
402 let mut chunk = [0u8; 8192];
403 loop {
404 match pipe.read(&mut chunk).await {
405 Ok(0) | Err(_) => break,
406 Ok(n) => {
407 if let Ok(mut guard) = sink.lock() {
408 guard.extend_from_slice(&chunk[..n]);
409 }
410 }
411 }
412 }
413 });
414 (buf, Some(handle))
415}
416
417pub(crate) async fn collect(
422 buf: &Captured,
423 handle: Option<tokio::task::JoinHandle<()>>,
424 grace: Duration,
425) -> String {
426 if let Some(handle) = handle {
427 if tokio::time::timeout(grace, handle).await.is_err() {
428 tracing::debug!("a pipe is still held open after the child exited");
429 }
430 }
431 let bytes = buf.lock().map(|g| g.clone()).unwrap_or_default();
432 String::from_utf8_lossy(&bytes).into_owned()
433}
434
435pub async fn invoke(
437 spec: &AgentSpec,
438 seat: &mut SeatState,
439 inv: &Invocation<'_>,
440) -> Result<AgentOutput> {
441 let lease = if repository_seat(inv) {
446 crate::repo_lock::SeatLease::for_checkout(inv.cwd, inv.allow_write, inv.coordination)
447 .await?
448 } else {
449 None
450 };
451 let inv = &Invocation {
452 timeout: spec.turn_timeout(inv.timeout),
453 ..inv.clone()
454 };
455 let mut outputs = Vec::new();
456 if repository_writer(inv) {
457 let min_free = crate::run::RunState::load_under(inv.run, &crate::run::home())
458 .map_or(0, |state| state.config.disk.min_free_bytes);
459 let mut paths = vec![inv.cwd.to_owned()];
460 if let Some(cache) = inv.cache_dir {
461 paths.push(cache.to_owned());
462 }
463 outputs.extend(
464 crate::retention::OutputLease::admit(&crate::run::home(), &paths, min_free)
465 .map_err(|e| crate::repo_lock::ResourceBlocked(format!("disk admission: {e:#}")))?,
466 );
467 }
468 if repository_seat(inv) {
469 if let Some(guard) = crate::retention::OutputLease::borrow(inv.cwd).map_err(|e| {
470 crate::repo_lock::ResourceBlocked(format!("worktree output ownership: {e:#}"))
471 })? {
472 outputs.push(guard);
473 }
474 if let Some(cache) = inv.cache_dir {
475 outputs.push(crate::retention::OutputLease::cache(
476 &crate::run::home(),
477 cache,
478 false,
479 )?);
480 }
481 }
482
483 let mut prompt = inv.prompt.to_owned();
484 if inv.node == crate::queue::CHAT_NODE {
485 prompt.push_str("\n\n");
486 prompt.push_str(crate::prompt::CHAT_FOLLOW_THROUGH);
487 }
488 if let Some(lease) = lease.as_ref().filter(|lease| lease.delegated) {
489 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()));
490 }
491 let home = repository_writer(inv).then(crate::run::home);
494 let mut writable = inv.writable.to_vec();
495 if let Some(home) = &home {
496 for root in worktree_writable_roots(inv.cwd, home).await? {
497 if !writable.contains(&root) {
498 writable.push(root);
499 }
500 }
501 }
502 if repository_writer(inv) {
503 prompt.push_str("\n\n");
504 prompt.push_str(&editing_access_note(inv.fetched_base));
505 }
506 let inv = &Invocation {
507 writable: &writable,
508 prompt: &prompt,
509 ..inv.clone()
510 };
511 tokio::fs::create_dir_all(inv.artifacts)
512 .await
513 .with_context(|| format!("create {}", inv.artifacts.display()))?;
514 let prompt_path = inv.artifacts.join(format!("{}.prompt.md", inv.stem));
515 tokio::fs::write(&prompt_path, inv.prompt)
516 .await
517 .with_context(|| format!("write {}", prompt_path.display()))?;
518
519 let omp_session = if spec.kind == AgentKind::Omp {
520 Some(OmpSession::prepare(
521 spec,
522 seat,
523 inv.sessions,
524 crate::run::home,
525 )?)
526 } else {
527 None
528 };
529 let plan = build_command(spec, seat, inv, &prompt_path)?;
530 tracing::debug!(seat = %seat.key, agent = %spec.id, argv = ?plan.logged_argv(), "spawning agent");
531 tokio::fs::write(
533 inv.artifacts.join(format!("{}.access.json", inv.stem)),
534 serde_json::to_vec_pretty(&serde_json::json!({
535 "launcher_version": env!("CARGO_PKG_VERSION"),
536 "kind": spec.kind,
537 "allow_write": inv.allow_write,
538 "unsandboxed": repository_writer(inv),
539 "writable_roots": inv.writable,
540 "fetched_base": inv.fetched_base,
541 }))?,
542 )
543 .await
544 .context("write seat access evidence")?;
545
546 let started = Instant::now();
547 let child_path = spec
550 .env
551 .iter()
552 .find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
553 .map(|(_, v)| std::ffi::OsString::from(v))
554 .or_else(|| std::env::var_os("PATH"))
555 .unwrap_or_default();
556 let program = crate::config::find_program_on(&plan.argv[0], &child_path).map_or_else(
557 || plan.argv[0].clone().into(),
558 std::path::PathBuf::into_os_string,
559 );
560 let mut cmd = Command::new(program);
561 cmd.args(plan.args(omp_session.as_ref().and_then(|session| session.dir(seat))))
562 .current_dir(inv.cwd)
563 .envs(&spec.env)
564 .env("MAGI_SEAT", &seat.key)
565 .env("MAGI_TURN", seat.turns.to_string())
566 .env("MAGI_RUN", inv.run)
567 .env("MAGI_NODE", inv.node)
568 .env("MAGI_PROMPT_FILE", &prompt_path)
569 .env("MAGI_ALLOW_WRITE", if inv.allow_write { "1" } else { "0" })
570 .env("GIT_TERMINAL_PROMPT", "0")
571 .stdin(if plan.stdin.is_some() {
572 Stdio::piped()
573 } else {
574 Stdio::null()
575 })
576 .stdout(Stdio::piped())
577 .stderr(Stdio::piped())
578 .kill_on_drop(true)
579 .quiet();
582 if let Some(session) = &omp_session {
583 session.isolate_terminal_history(&mut cmd, seat);
584 }
585 crate::incremental::default_environment(&mut cmd);
586 if repository_writer(inv) {
587 crate::incremental::configure(&mut cmd, inv.cwd)?;
588 }
589 if let Some(home) = home {
590 cmd.env("MAGI_HOME", std::fs::canonicalize(home)?);
593 }
594 if let Some(cache) = inv.cache_dir {
595 cmd.env("CARGO_TARGET_DIR", cache);
598 } else {
599 cmd.env_remove("CARGO_TARGET_DIR");
607 }
608
609 #[cfg(any(unix, windows))]
610 let _chat_controls = {
611 use crate::chat_control::bridge::{self, Bridge};
612 bridge::clear_environment(&mut cmd);
615 let bridge = if inv.node == crate::queue::CHAT_NODE {
616 crate::run::try_home().and_then(|home| {
617 match Bridge::start(&home, inv.run, inv.artifacts) {
618 Ok(bridge) => Some(bridge),
619 Err(error) => {
620 tracing::warn!(%error, "chat controls unavailable; continuing conversation");
621 None
622 }
623 }
624 })
625 } else {
626 None
627 };
628 if let Some(bridge) = &bridge {
629 cmd.env("MAGI_HOME", std::fs::canonicalize(crate::run::home())?);
633 bridge.attach(&mut cmd);
634 }
635 bridge
636 };
637
638 let mut running = crate::seat_process::Running::spawn(cmd, lease, outputs)
639 .with_context(|| format!("spawn `{}` for seat {}", plan.argv[0], seat.key))?;
640 if let (Some(body), Some(mut sink)) = (plan.stdin.clone(), running.child().stdin.take()) {
644 tokio::spawn(async move {
645 sink.write_all(body.as_bytes()).await.ok();
646 sink.shutdown().await.ok();
647 });
648 }
649
650 let (out_buf, out_reader) = drain(running.child().stdout.take());
667 let (err_buf, err_reader) = drain(running.child().stderr.take());
668
669 let min_free = crate::run::RunState::load_under(inv.run, &crate::run::home())
670 .ok()
671 .map_or(0, |state| state.config.disk.min_free_bytes);
672 #[cfg(all(test, unix))]
673 let min_free = test_watchdog::floor(inv.run, min_free);
674 let mut paths = vec![inv.cwd.to_owned()];
675 if let Some(cache) = inv.cache_dir {
676 paths.push(cache.to_owned());
677 }
678 let mut pressure = None;
679 let waited = tokio::select! {
680 waited = tokio::time::timeout(inv.timeout, running.child().wait()) => Some(waited),
681 reason = crate::retention::emergency(paths, min_free) => {
682 pressure = Some(reason);
683 None
684 }
685 };
686 let (code, timed_out) = match waited {
687 Some(Ok(res)) => {
688 let status = res.with_context(|| format!("wait for seat {}", seat.key))?;
689 (status.code(), false)
690 }
691 Some(Err(_)) | None => {
692 if let Some(reason) = &pressure {
693 tracing::warn!(seat = %seat.key, %reason, "agent execution interrupted");
694 } else {
695 tracing::warn!(seat = %seat.key, secs = inv.timeout.as_secs(), "agent timed out");
696 }
697 if !running.coordinated() {
699 running
700 .child()
701 .kill()
702 .await
703 .context("stop timed-out seat")?;
704 }
705 (None, true)
706 }
707 };
708 running.finish().await;
709
710 let stdout = collect(&out_buf, out_reader, PIPE_GRACE).await;
715 let stderr = collect(&err_buf, err_reader, PIPE_GRACE).await;
716
717 let out_path = inv.artifacts.join(format!("{}.out", inv.stem));
718 let err_path = inv.artifacts.join(format!("{}.err", inv.stem));
719 tokio::fs::write(&out_path, &stdout).await.ok();
720 tokio::fs::write(&err_path, &stderr).await.ok();
721 if let Some(reason) = pressure {
722 return Err(
723 anyhow::Error::new(crate::repo_lock::ResourceBlocked(reason.clone()))
724 .context(ExecutionInterrupted(reason)),
725 );
726 }
727
728 if code != Some(0)
729 && (stdout.contains(crate::incremental::BLOCKED)
730 || stderr.contains(crate::incremental::BLOCKED))
731 {
732 let detail = if stderr.contains(crate::incremental::BLOCKED) {
733 &stderr
734 } else {
735 &stdout
736 };
737 return Err(crate::repo_lock::ResourceBlocked(tail_chars(detail, 2000)).into());
738 }
739
740 let mut extracted = extract(spec.kind, &stdout);
741 if spec.kind == AgentKind::Antigravity && extracted.quota.is_none() {
742 extracted.quota = agy_quota(&stdout, &stderr);
743 }
744 if let Some(quota) = &mut extracted.quota {
745 quota.agent.clone_from(&spec.id);
746 if quota.cause == QuotaCause::Authentication {
747 let _ = crate::notices::Notices::open().raise(crate::notices::Notice::warn(
748 &format!("agent-authentication:{}", spec.id),
749 format!("Agent `{}` cannot authenticate. Re-authenticate this agent, then resume the held task.", spec.id),
750 ));
751 }
752 extracted.dropped = None;
755 tracing::warn!(
756 seat = %seat.key,
757 agent = %spec.id,
758 reset = ?quota.reset,
759 cause = ?quota.cause,
760 "agent needs machine-side recovery"
761 );
762 }
763 if let Some(omp_session) = omp_session {
764 omp_session.record(seat, extracted.session, code == Some(0))?;
765 } else if let Some(session) = extracted.session {
766 match spec.kind {
767 AgentKind::Claude => seat.claude_session = Some(session),
768 AgentKind::Opencode | AgentKind::Antigravity | AgentKind::Codex => {
769 seat.captured_session = Some(session);
770 }
771 AgentKind::Command | AgentKind::Omp => {}
772 }
773 }
774 if let Some(status) = &extracted.status
775 && !status.eq_ignore_ascii_case("success")
776 {
777 tracing::warn!(seat = %seat.key, status = %status, "agent reported a non-success status");
778 }
779 let text = if extracted.text.trim().is_empty() {
780 if stdout.trim().is_empty() {
782 stderr.trim().to_owned()
783 } else {
784 stdout.trim().to_owned()
785 }
786 } else {
787 extracted.text
788 };
789 seat.turns += 1;
790
791 Ok(AgentOutput {
792 text,
793 exit_code: code,
794 timed_out,
795 duration_ms: started.elapsed().as_millis() as u64,
796 artifacts: vec![
797 file_name(&prompt_path),
798 file_name(&out_path),
799 file_name(&err_path),
800 ],
801 quota: extracted.quota,
802 dropped: extracted.dropped,
803 commands: extracted.commands,
804 context_tokens: extracted.context_tokens,
805 })
806}
807
808fn file_name(p: &Path) -> String {
809 p.file_name()
810 .unwrap_or_default()
811 .to_string_lossy()
812 .into_owned()
813}
814
815enum OmpSession {
816 Fresh(PathBuf),
817 Resume,
818}
819
820impl OmpSession {
821 fn prepare(
822 spec: &AgentSpec,
823 seat: &SeatState,
824 sessions: bool,
825 home: impl FnOnce() -> PathBuf,
826 ) -> Result<Self> {
827 let resume = has_session(AgentKind::Omp, seat, sessions);
828 if resume && seat.omp_session_dir.is_none() {
829 return Ok(Self::Resume);
831 }
832 for arg in &spec.extra_args {
833 let flag = arg.split_once('=').map_or(arg.as_str(), |(flag, _)| flag);
834 if matches!(
835 flag,
836 "--session-dir"
837 | "--no-session"
838 | "--resume"
839 | "--session"
840 | "--fork"
841 | "--restore"
842 | "--continue"
843 | "--from-claude"
844 | "--from-codex"
845 | "-r"
846 | "-c"
847 ) {
848 bail!("omp extra_args cannot set {flag} for isolated sessions");
849 }
850 }
851 if resume {
852 let dir = seat.omp_session_dir.as_ref().expect("managed resume");
853 anyhow::ensure!(
854 dir.is_absolute(),
855 "saved omp session directory is not absolute"
856 );
857 std::fs::read_dir(dir)
858 .with_context(|| format!("open saved omp session directory {}", dir.display()))?;
859 return Ok(Self::Resume);
860 }
861
862 let root = std::path::absolute(home().join("agent-sessions").join("omp"))
863 .context("resolve absolute omp session store")?;
864 anyhow::ensure!(
866 root.to_str().is_some(),
867 "omp session store is not valid Unicode"
868 );
869 std::fs::create_dir_all(&root)
870 .with_context(|| format!("create omp session store {}", root.display()))?;
871 let ids =
872 crate::id_reserve::IdSource::new(|| SplitMix64::new(crate::rng::entropy()).uuid_v4());
873 let id = ids.reserve(None, "omp session directory", |id| {
874 crate::id_reserve::create_dir(&root.join(id))
875 })?;
876 Ok(Self::Fresh(root.join(id)))
877 }
878
879 fn dir<'a>(&'a self, seat: &'a SeatState) -> Option<&'a Path> {
880 match self {
881 Self::Fresh(dir) => Some(dir),
882 Self::Resume => seat.omp_session_dir.as_deref(),
883 }
884 }
885
886 fn isolate_terminal_history(&self, cmd: &mut Command, seat: &SeatState) {
887 if self.dir(seat).is_none() {
888 return;
889 }
890 for key in [
894 "ZELLIJ_PANE_ID",
895 "TMUX_PANE",
896 "CMUX_SURFACE_ID",
897 "KITTY_WINDOW_ID",
898 "WEZTERM_PANE",
899 "TERM_SESSION_ID",
900 "WT_SESSION",
901 ] {
902 cmd.env_remove(key);
903 }
904 }
905
906 fn record(self, seat: &mut SeatState, reported: Option<String>, success: bool) -> Result<()> {
907 let reported = reported.filter(|id| !id.is_empty());
908 match self {
909 Self::Resume if seat.omp_session_dir.is_none() => {
910 if let Some(id) = reported {
912 seat.captured_session = Some(id);
913 }
914 }
915 Self::Resume => {
916 if let Some(id) = reported {
917 let previous = seat.captured_session.as_deref().expect("managed resume");
918 let dir = seat.omp_session_dir.as_deref().expect("managed resume");
919 if previous != id {
920 anyhow::ensure!(
921 omp_continues(dir, previous, &id)?,
922 "omp resumed a different session than requested"
923 );
924 seat.captured_session = Some(id);
925 }
926 } else if success {
927 bail!("omp did not confirm the requested session; see the seat output");
930 }
931 }
932 Self::Fresh(dir) => {
933 if let Some(id) = reported {
934 seat.captured_session = Some(id);
935 seat.omp_session_dir = Some(dir);
936 } else if success {
937 bail!("omp did not report a new session id; see the seat output");
938 }
939 }
940 }
941 Ok(())
942 }
943}
944
945fn omp_continues(dir: &Path, previous: &str, reported: &str) -> Result<bool> {
948 use std::io::{BufRead as _, BufReader, Read as _};
949
950 let mut parents = BTreeMap::new();
951 let mut line = Vec::new();
952 for entry in std::fs::read_dir(dir).context("read omp continuation directory")? {
953 let entry = entry?;
954 let path = entry.path();
955 if path.extension() != Some(OsStr::new("jsonl")) || !entry.file_type()?.is_file() {
956 continue;
957 }
958 line.clear();
959 BufReader::new(std::fs::File::open(path)?)
961 .take(64 * 1024)
962 .read_until(b'\n', &mut line)?;
963 if !line.ends_with(b"\n") {
964 continue;
965 }
966 let Ok(header) = serde_json::from_slice::<serde_json::Value>(&line) else {
967 continue;
968 };
969 if header["type"].as_str() != Some("session") {
970 continue;
971 }
972 if let Some(id) = header["id"].as_str() {
973 let parent = header["continuationOf"].as_str().map(str::to_owned);
974 if parents.insert(id.to_owned(), parent).is_some() {
975 return Ok(false);
976 }
977 }
978 }
979
980 let mut current = reported.to_owned();
981 while let Some(Some(parent)) = parents.remove(¤t) {
983 if parent == previous {
984 return Ok(true);
985 }
986 current = parent;
987 }
988 Ok(false)
989}
990
991#[derive(Debug)]
993struct Plan {
994 argv: Vec<String>,
995 stdin: Option<String>,
996}
997
998impl Plan {
999 fn args<'a>(&'a self, omp_dir: Option<&'a Path>) -> impl Iterator<Item = &'a OsStr> {
1001 omp_dir
1002 .into_iter()
1003 .flat_map(|dir| [OsStr::new("--session-dir"), dir.as_os_str()])
1004 .chain(self.argv[1..].iter().map(OsStr::new))
1005 }
1006
1007 fn logged_argv(&self) -> Vec<&str> {
1010 let mut settings_value = false;
1011 self.argv
1012 .iter()
1013 .map(|arg| {
1014 if settings_value {
1015 settings_value = false;
1016 "[redacted]"
1017 } else if arg == "--settings" {
1018 settings_value = true;
1019 arg.as_str()
1020 } else if arg.starts_with("--settings=") {
1021 "--settings=[redacted]"
1022 } else {
1023 arg.as_str()
1024 }
1025 })
1026 .collect()
1027 }
1028}
1029
1030fn pointer(kind: AgentKind, prompt_path: &Path) -> String {
1041 if matches!(kind, AgentKind::Antigravity) {
1042 return format!("@{}", prompt_path.display());
1043 }
1044 format!(
1045 "Read the file at {} and follow every instruction in it exactly. That \
1046 file is your complete task description; this message contains nothing \
1047 else.",
1048 prompt_path.display()
1049 )
1050}
1051
1052fn build_command(
1053 spec: &AgentSpec,
1054 seat: &SeatState,
1055 inv: &Invocation<'_>,
1056 prompt_path: &Path,
1057) -> Result<Plan> {
1058 let mut argv: Vec<String> = Vec::new();
1059 let mut stdin: Option<String> = None;
1060 let delivery = spec.delivery();
1061 let resuming = has_session(spec.kind, seat, inv.sessions);
1062
1063 match spec.kind {
1064 AgentKind::Claude => {
1065 argv.push("claude".to_owned());
1070 argv.push("-p".to_owned());
1071 argv.push("--output-format".to_owned());
1072 argv.push("json".to_owned());
1073 if let Some(m) = &spec.model {
1074 argv.push("--model".to_owned());
1075 argv.push(m.clone());
1076 }
1077 if inv.sessions {
1078 let uuid = seat
1079 .claude_session
1080 .as_deref()
1081 .context("claude seat is missing its session uuid")?;
1082 argv.push(if resuming { "--resume" } else { "--session-id" }.to_owned());
1083 argv.push(uuid.to_owned());
1084 }
1085 argv.push("--permission-mode".to_owned());
1086 argv.push("bypassPermissions".to_owned());
1087 if !inv.allow_write {
1088 argv.push("--disallowed-tools".to_owned());
1089 argv.push("Edit,Write,MultiEdit,NotebookEdit".to_owned());
1090 }
1091 }
1092 AgentKind::Opencode => {
1093 argv.push("opencode".to_owned());
1097 argv.push("run".to_owned());
1098 argv.push("--format".to_owned());
1099 argv.push("json".to_owned());
1100 argv.push("--dir".to_owned());
1101 argv.push(inv.cwd.to_string_lossy().into_owned());
1102 argv.push("--auto".to_owned());
1111 if let Some(m) = &spec.model {
1112 argv.push("-m".to_owned());
1113 argv.push(m.clone());
1114 }
1115 if resuming {
1116 argv.push("-s".to_owned());
1117 argv.push(
1118 seat.captured_session
1119 .clone()
1120 .expect("has_session checked the id is present"),
1121 );
1122 }
1123 }
1124 AgentKind::Antigravity => {
1125 argv.push("agy".to_owned());
1126 argv.push("--output-format".to_owned());
1127 argv.push("json".to_owned());
1128 argv.push("--print-timeout".to_owned());
1131 argv.push(format!("{}s", inv.timeout.as_secs()));
1132 argv.push("--mode".to_owned());
1133 argv.push(
1134 if inv.allow_write {
1135 "accept-edits"
1136 } else {
1137 "plan"
1138 }
1139 .to_owned(),
1140 );
1141 if inv.allow_write {
1142 argv.push("--dangerously-skip-permissions".to_owned());
1143 }
1144 if let Some(m) = &spec.model {
1145 argv.push("--model".to_owned());
1146 argv.push(m.clone());
1147 }
1148 if resuming {
1149 argv.push("--conversation".to_owned());
1150 argv.push(
1151 seat.captured_session
1152 .clone()
1153 .expect("has_session checked the id is present"),
1154 );
1155 }
1156 let mut add_dirs: Vec<String> = Vec::new();
1166 if delivery == Delivery::File || !inv.attachments.is_empty() {
1167 add_dirs.push(inv.artifacts.to_string_lossy().into_owned());
1168 }
1169 for path in inv.attachments {
1170 let Some(parent) = path.parent() else {
1171 continue;
1172 };
1173 if parent.starts_with(inv.artifacts) {
1174 continue;
1175 }
1176 let dir = parent.to_string_lossy().into_owned();
1177 if !add_dirs.contains(&dir) {
1178 add_dirs.push(dir);
1179 }
1180 }
1181 if inv.allow_write {
1182 for path in inv.writable {
1183 let dir = path.to_string_lossy().into_owned();
1184 if !add_dirs.contains(&dir) {
1185 add_dirs.push(dir);
1186 }
1187 }
1188 }
1189 for dir in add_dirs {
1190 argv.push("--add-dir".to_owned());
1191 argv.push(dir);
1192 }
1193 }
1194 AgentKind::Codex => {
1195 argv.push("codex".to_owned());
1201 argv.push("exec".to_owned());
1202 argv.push("--json".to_owned());
1203 argv.push("--skip-git-repo-check".to_owned());
1206 argv.push("-C".to_owned());
1207 argv.push(inv.cwd.to_string_lossy().into_owned());
1208 if repository_writer(inv) {
1218 argv.push("--dangerously-bypass-approvals-and-sandbox".to_owned());
1219 } else {
1220 argv.push("--sandbox".to_owned());
1221 argv.push(
1222 if inv.allow_write {
1223 "workspace-write"
1224 } else {
1225 "read-only"
1226 }
1227 .to_owned(),
1228 );
1229 argv.push("-c".to_owned());
1232 argv.push("approval_policy=\"never\"".to_owned());
1233 if inv.allow_write && !inv.writable.is_empty() {
1234 let roots: Vec<String> = inv
1235 .writable
1236 .iter()
1237 .map(|p| p.to_string_lossy().into_owned())
1238 .collect();
1239 argv.push("-c".to_owned());
1240 argv.push(format!(
1241 "sandbox_workspace_write.writable_roots={}",
1242 serde_json::to_string(&roots).unwrap_or_else(|_| "[]".to_owned())
1243 ));
1244 }
1245 }
1246 if let Some(m) = &spec.model {
1247 argv.push("-m".to_owned());
1248 argv.push(m.clone());
1249 }
1250 if resuming {
1256 argv.push("resume".to_owned());
1257 argv.push(
1258 seat.captured_session
1259 .clone()
1260 .expect("has_session checked the id is present"),
1261 );
1262 }
1263 }
1264 AgentKind::Omp => {
1265 argv.push("omp".to_owned());
1269 argv.push("-p".to_owned());
1270 argv.push("--mode=json".to_owned());
1271 argv.push("--auto-approve".to_owned());
1281 if let Some(m) = &spec.model {
1282 argv.push("--model".to_owned());
1283 argv.push(m.clone());
1284 }
1285 if resuming {
1291 argv.push("--resume".to_owned());
1292 argv.push(
1293 seat.captured_session
1294 .clone()
1295 .expect("has_session checked the id is present"),
1296 );
1297 }
1298 }
1299 AgentKind::Command => {
1300 if spec.command.is_empty() {
1305 bail!("agent `{}` has kind = \"command\" but no command", spec.id);
1306 }
1307 let vars: BTreeMap<&str, String> = BTreeMap::from([
1308 ("{prompt_file}", prompt_path.to_string_lossy().into_owned()),
1309 ("{cwd}", inv.cwd.to_string_lossy().into_owned()),
1310 ("{label}", seat.key.clone()),
1311 ("{session}", seat.claude_session.clone().unwrap_or_default()),
1312 ]);
1313 for raw in &spec.command {
1314 let mut arg = raw.clone();
1315 for (k, v) in &vars {
1316 if arg.contains(k) {
1317 arg = arg.replace(k, v);
1318 }
1319 }
1320 argv.push(arg);
1321 }
1322 }
1323 }
1324
1325 argv.extend(spec.extra_args.iter().cloned());
1326
1327 if spec.kind == AgentKind::Antigravity {
1330 argv.push("-p".to_owned());
1331 }
1332 if spec.kind == AgentKind::Codex && delivery == Delivery::Stdin {
1335 argv.push("-".to_owned());
1336 }
1337 match delivery {
1338 Delivery::Stdin if spec.kind == AgentKind::Antigravity => {
1339 argv.push(pointer(spec.kind, prompt_path));
1341 }
1342 Delivery::Stdin => stdin = Some(inv.prompt.to_owned()),
1343 Delivery::Argv => argv.push(inv.prompt.to_owned()),
1344 Delivery::File => argv.push(pointer(spec.kind, prompt_path)),
1345 }
1346
1347 Ok(Plan { argv, stdin })
1348}
1349
1350#[derive(Debug, Default)]
1352struct Extracted {
1353 text: String,
1354 session: Option<String>,
1355 status: Option<String>,
1356 quota: Option<Quota>,
1357 dropped: Option<Dropped>,
1358 commands: Vec<CommandEvidence>,
1359 context_tokens: Option<u64>,
1360}
1361
1362fn extract(kind: AgentKind, stdout: &str) -> Extracted {
1364 let mut extracted = extract_answer(kind, stdout);
1365 extracted.context_tokens = context_tokens(kind, stdout);
1366 extracted
1367}
1368
1369fn uint(v: &serde_json::Value, key: &str) -> Option<u64> {
1371 v.get(key).and_then(serde_json::Value::as_u64)
1372}
1373
1374fn input_side(usage: &serde_json::Value, input: &[&str], cache: &[&str]) -> Option<u64> {
1379 let first = |keys: &[&str]| keys.iter().find_map(|k| uint(usage, k));
1380 let base = first(input)?;
1381 let cached: u64 = cache.iter().filter_map(|k| uint(usage, k)).sum();
1382 Some(base.saturating_add(cached))
1383}
1384
1385fn context_tokens(kind: AgentKind, stdout: &str) -> Option<u64> {
1406 use serde_json::Value;
1407 let lines = || {
1408 stdout
1409 .lines()
1410 .filter_map(|l| serde_json::from_str::<Value>(l.trim()).ok())
1411 };
1412 match kind {
1413 AgentKind::Claude => None,
1414 AgentKind::Opencode => lines()
1415 .filter(|v| {
1416 v.get("type").and_then(|t| t.as_str()) == Some("step_finish")
1418 || v.get("part")
1419 .and_then(|p| p.get("type"))
1420 .and_then(|t| t.as_str())
1421 == Some("step-finish")
1422 })
1423 .filter_map(|v| {
1424 let tokens = v.get("part")?.get("tokens")?;
1425 let base = uint(tokens, "input")?;
1426 let cache = tokens.get("cache");
1427 let cached = ["read", "write"]
1428 .iter()
1429 .filter_map(|k| cache.and_then(|c| uint(c, k)))
1430 .sum::<u64>();
1431 Some(base.saturating_add(cached))
1432 })
1433 .next_back(),
1434 AgentKind::Antigravity => None,
1435 AgentKind::Codex => None,
1436 AgentKind::Omp => lines()
1437 .flat_map(|v| {
1438 match v.get("type").and_then(|t| t.as_str()) {
1441 Some("agent_end") => v
1442 .get("messages")
1443 .and_then(|m| m.as_array())
1444 .cloned()
1445 .unwrap_or_default(),
1446 Some("turn_end") | Some("message_end") => {
1447 v.get("message").cloned().into_iter().collect()
1448 }
1449 _ => Vec::new(),
1450 }
1451 })
1452 .filter(|m| m.get("role").and_then(|r| r.as_str()) == Some("assistant"))
1453 .filter_map(|m| {
1454 input_side(
1455 m.get("usage")?,
1456 &["input", "input_tokens"],
1457 &[
1458 "cacheRead",
1459 "cacheWrite",
1460 "cache_read_tokens",
1461 "cache_write_tokens",
1462 ],
1463 )
1464 })
1465 .next_back(),
1466 AgentKind::Command => None,
1467 }
1468}
1469
1470pub(crate) fn answer_text(kind: AgentKind, stdout: &str) -> String {
1473 extract_answer(kind, stdout).text
1474}
1475
1476fn extract_answer(kind: AgentKind, stdout: &str) -> Extracted {
1477 match kind {
1478 AgentKind::Claude => {
1479 let Ok(v) = serde_json::from_str::<serde_json::Value>(stdout.trim()) else {
1480 return Extracted {
1481 text: stdout.trim().to_owned(),
1482 ..Extracted::default()
1483 };
1484 };
1485 Extracted {
1486 text: v
1487 .get("result")
1488 .and_then(|r| r.as_str())
1489 .unwrap_or_default()
1490 .to_owned(),
1491 session: v
1492 .get("session_id")
1493 .and_then(|s| s.as_str())
1494 .map(str::to_owned),
1495 status: v.get("is_error").and_then(|e| e.as_bool()).map(|e| {
1496 if e {
1497 "error".to_owned()
1498 } else {
1499 "success".to_owned()
1500 }
1501 }),
1502 quota: claude_quota(&v),
1503 dropped: None,
1506 commands: Vec::new(),
1507 context_tokens: None,
1508 }
1509 }
1510 AgentKind::Opencode => {
1511 let mut text = String::new();
1513 let mut session = None;
1514 for line in stdout.lines() {
1515 let Ok(v) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
1516 continue;
1517 };
1518 if session.is_none() {
1519 session = v
1520 .get("sessionID")
1521 .and_then(|s| s.as_str())
1522 .map(str::to_owned);
1523 }
1524 let part = v.get("part").unwrap_or(&serde_json::Value::Null);
1525 if part.get("type").and_then(|t| t.as_str()) == Some("text")
1526 && let Some(t) = part.get("text").and_then(|t| t.as_str())
1527 {
1528 if !text.is_empty() {
1529 text.push('\n');
1530 }
1531 text.push_str(t);
1532 }
1533 }
1534 Extracted {
1535 text,
1536 session,
1537 status: None,
1538 quota: None,
1539 dropped: None,
1540 commands: Vec::new(),
1541 context_tokens: None,
1542 }
1543 }
1544 AgentKind::Antigravity => {
1545 let obj = stdout
1548 .lines()
1549 .rev()
1550 .find_map(|l| serde_json::from_str::<serde_json::Value>(l.trim()).ok());
1551 let Some(v) = obj else {
1552 return Extracted {
1553 text: stdout.trim().to_owned(),
1554 ..Extracted::default()
1555 };
1556 };
1557 Extracted {
1558 text: v
1559 .get("response")
1560 .and_then(|r| r.as_str())
1561 .unwrap_or_default()
1562 .trim()
1563 .to_owned(),
1564 session: v
1565 .get("conversation_id")
1566 .and_then(|s| s.as_str())
1567 .map(str::to_owned),
1568 status: v.get("status").and_then(|s| s.as_str()).map(str::to_owned),
1569 quota: None,
1570 dropped: dropped_stream(&v),
1571 commands: Vec::new(),
1572 context_tokens: None,
1573 }
1574 }
1575 AgentKind::Codex => {
1576 let mut text = String::new();
1598 let mut session = None;
1599 let mut status = None;
1600 let mut commands = Vec::new();
1601 for line in stdout.lines() {
1602 let Ok(v) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
1603 continue;
1604 };
1605 match v.get("type").and_then(|t| t.as_str()) {
1606 Some("thread.started") => {
1607 session = v
1608 .get("thread_id")
1609 .and_then(|s| s.as_str())
1610 .map(str::to_owned);
1611 }
1612 Some("item.completed") => {
1613 let item = v.get("item").unwrap_or(&serde_json::Value::Null);
1614 match item.get("type").and_then(|t| t.as_str()) {
1615 Some("agent_message") => {
1616 if let Some(t) = item.get("text").and_then(|t| t.as_str()) {
1617 text = t.trim().to_owned();
1618 }
1619 }
1620 Some("command_execution") => {
1621 commands.push(command_evidence(item));
1622 }
1623 _ => {}
1624 }
1625 }
1626 Some("turn.completed") => status = Some("success".to_owned()),
1627 Some("turn.failed") => status = Some("error".to_owned()),
1628 _ => {}
1629 }
1630 }
1631 Extracted {
1632 text,
1633 session,
1634 status,
1635 quota: codex_quota(stdout),
1636 dropped: None,
1637 commands,
1638 context_tokens: None,
1639 }
1640 }
1641 AgentKind::Omp => {
1642 let mut text = String::new();
1663 let mut session = None;
1664 for line in stdout.lines() {
1665 let Ok(v) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
1666 continue;
1667 };
1668 if v.get("type").and_then(|t| t.as_str()) == Some("session") {
1669 session = v.get("id").and_then(|s| s.as_str()).map(str::to_owned);
1670 continue;
1671 }
1672 let messages: Vec<&serde_json::Value> = match v.get("type").and_then(|t| t.as_str())
1676 {
1677 Some("agent_end") => v
1678 .get("messages")
1679 .and_then(|m| m.as_array())
1680 .map(|m| m.iter().collect())
1681 .unwrap_or_default(),
1682 Some("turn_end") | Some("message_end") => {
1683 v.get("message").into_iter().collect()
1684 }
1685 _ => continue,
1686 };
1687 for message in messages {
1688 if message.get("role").and_then(|r| r.as_str()) != Some("assistant") {
1689 continue;
1690 }
1691 let Some(parts) = message.get("content").and_then(|c| c.as_array()) else {
1692 continue;
1693 };
1694 for part in parts {
1695 if part.get("type").and_then(|t| t.as_str()) != Some("text") {
1696 continue;
1697 }
1698 if let Some(t) = part.get("text").and_then(|t| t.as_str())
1699 && !t.trim().is_empty()
1700 {
1701 text = t.trim().to_owned();
1702 }
1703 }
1704 }
1705 }
1706 Extracted {
1707 text,
1708 session,
1709 status: None,
1710 quota: None,
1711 dropped: None,
1712 commands: Vec::new(),
1713 context_tokens: None,
1714 }
1715 }
1716 AgentKind::Command => {
1717 let parsed = serde_json::from_str::<serde_json::Value>(stdout.trim()).ok();
1722 let quota = parsed.as_ref().and_then(claude_quota);
1723 let dropped = parsed.as_ref().and_then(dropped_stream);
1726 Extracted {
1727 text: stdout.trim().to_owned(),
1728 session: None,
1729 status: None,
1730 quota,
1731 dropped,
1732 commands: Vec::new(),
1733 context_tokens: None,
1734 }
1735 }
1736 }
1737}
1738
1739fn command_evidence(item: &serde_json::Value) -> CommandEvidence {
1746 let description = match item.get("command") {
1747 Some(serde_json::Value::String(s)) => s.clone(),
1748 Some(serde_json::Value::Array(parts)) => parts
1749 .iter()
1750 .filter_map(|p| p.as_str())
1751 .collect::<Vec<_>>()
1752 .join(" "),
1753 _ => String::new(),
1754 };
1755 let result_summary = item
1756 .get("aggregated_output")
1757 .and_then(|o| o.as_str())
1758 .map(|s| tail_chars(s.trim(), 400))
1759 .unwrap_or_default();
1760 CommandEvidence {
1761 id: item
1762 .get("id")
1763 .and_then(|s| s.as_str())
1764 .unwrap_or_default()
1765 .to_owned(),
1766 description,
1767 exit_code: item
1768 .get("exit_code")
1769 .and_then(serde_json::Value::as_i64)
1770 .map(|e| e as i32),
1771 result_summary,
1772 source: "codex".to_owned(),
1773 }
1774}
1775
1776fn tail_chars(s: &str, max: usize) -> String {
1778 let count = s.chars().count();
1779 if count <= max {
1780 return s.to_owned();
1781 }
1782 s.chars().skip(count - max).collect()
1783}
1784
1785fn codex_quota(stdout: &str) -> Option<Quota> {
1788 let mut message = None;
1789 let mut failed = false;
1790 for line in stdout.lines() {
1791 let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else {
1792 continue;
1793 };
1794 match v.get("type").and_then(serde_json::Value::as_str) {
1795 Some("error") => {
1796 if let Some(m) = v.get("message").and_then(serde_json::Value::as_str)
1797 && m.starts_with("You've hit your usage limit. Visit https://chatgpt.com/settings/usage to purchase more credits")
1798 {
1799 message = Some(m.to_owned());
1800 }
1801 }
1802 Some("turn.failed") => failed = true,
1803 _ => {}
1804 }
1805 }
1806 if !failed {
1807 return None;
1808 }
1809 let message = message?;
1810 Some(Quota {
1811 reset: message
1812 .split_once("try again at ")
1813 .map(|(_, hint)| hint.trim().trim_end_matches('.').trim().to_owned())
1814 .filter(|hint| !hint.is_empty()),
1815 cause: QuotaCause::UsageLimit,
1816 agent: String::new(),
1817 })
1818}
1819
1820fn claude_quota(v: &serde_json::Value) -> Option<Quota> {
1827 let is_err = v.get("is_error").and_then(|e| e.as_bool()).unwrap_or(false);
1828 if !is_err {
1829 return None;
1830 }
1831 let result = v.get("result").and_then(|r| r.as_str()).unwrap_or("");
1832 if v.get("terminal_reason").and_then(serde_json::Value::as_str) == Some("api_error")
1833 && result.starts_with("Failed to authenticate:")
1834 && result.contains("OAuth session expired and could not be refreshed")
1835 {
1836 return Some(Quota {
1837 reset: None,
1838 cause: QuotaCause::Authentication,
1839 agent: String::new(),
1840 });
1841 }
1842 let status = v.get("api_error_status");
1843 let usage_limit = (status.and_then(serde_json::Value::as_u64) == Some(429)
1844 || status.and_then(serde_json::Value::as_str) == Some("429"))
1845 && v.get("api_error").and_then(serde_json::Value::as_str) == Some("usage_limit_reached");
1846 if !usage_limit && !result.to_lowercase().contains("session limit") {
1847 return None;
1848 }
1849 let reset = result
1852 .split("resets ")
1853 .nth(1)
1854 .map(str::trim)
1855 .filter(|s| !s.is_empty())
1856 .map(str::to_owned);
1857 Some(Quota {
1858 reset,
1859 cause: QuotaCause::UsageLimit,
1860 agent: String::new(),
1861 })
1862}
1863
1864fn agy_quota(stdout: &str, stderr: &str) -> Option<Quota> {
1879 let from_stdout = stdout
1880 .lines()
1881 .rev()
1882 .find_map(|l| serde_json::from_str::<serde_json::Value>(l.trim()).ok())
1883 .and_then(|v| {
1884 let status = v.get("status").and_then(|s| s.as_str()).unwrap_or("");
1885 let error = v.get("error").and_then(|e| e.as_str()).unwrap_or("");
1886 (status.eq_ignore_ascii_case("error") && error.to_lowercase().contains("quota reached"))
1887 .then(|| error.to_owned())
1888 });
1889 let from_stderr = || {
1890 stderr.lines().find_map(|l| {
1891 let v: serde_json::Value =
1892 serde_json::from_str(l.trim().strip_prefix("AGY_ERROR:")?.trim()).ok()?;
1893 let exhausted = v.get("status").and_then(|s| s.as_str()) == Some("RESOURCE_EXHAUSTED");
1894 let code = v.get("error_code").and_then(serde_json::Value::as_u64) == Some(429);
1895 (exhausted && code).then(|| {
1896 v.get("short_error")
1897 .and_then(|e| e.as_str())
1898 .unwrap_or_default()
1899 .to_owned()
1900 })
1901 })
1902 };
1903 let text = from_stdout.or_else(from_stderr)?;
1904 let reset = text
1905 .split_once("Resets ")
1906 .map(|(_, rest)| rest.trim().trim_end_matches('.').trim())
1907 .filter(|s| !s.is_empty())
1908 .map(str::to_owned);
1909 Some(Quota {
1910 reset,
1911 cause: QuotaCause::UsageLimit,
1912 agent: String::new(),
1913 })
1914}
1915
1916fn dropped_stream(v: &serde_json::Value) -> Option<Dropped> {
1947 let status = v.get("status").and_then(|s| s.as_str()).unwrap_or("");
1948 if !status.eq_ignore_ascii_case("error") {
1949 return None;
1950 }
1951 let response = v.get("response").and_then(|r| r.as_str()).unwrap_or("");
1952 if !response.trim().is_empty() {
1953 return None;
1955 }
1956 let produced = v
1957 .get("usage")
1958 .and_then(|u| u.get("output_tokens"))
1959 .and_then(serde_json::Value::as_u64)
1960 .unwrap_or(0);
1961 if produced == 0 {
1962 return None;
1964 }
1965 Some(Dropped {
1966 why: v
1967 .get("error")
1968 .and_then(|e| e.as_str())
1969 .unwrap_or("the CLI ended the stream without delivering its answer")
1970 .trim()
1971 .to_owned(),
1972 output_tokens: produced,
1973 })
1974}
1975
1976pub fn missing_programs(specs: &[AgentSpec]) -> Vec<String> {
1978 let mut missing = Vec::new();
1979 for s in specs {
1980 let program = match s.kind {
1981 AgentKind::Command => s.command.first().map(String::as_str),
1982 other => other.program(),
1983 };
1984 if let Some(p) = program
1985 && !crate::config::which(p)
1986 && !Path::new(p).is_file()
1987 && !missing.iter().any(|m: &String| m == p)
1988 {
1989 missing.push(p.to_owned());
1990 }
1991 }
1992 missing
1993}
1994
1995pub fn artifacts_dir(run_dir: &Path) -> PathBuf {
1997 run_dir.join("artifacts")
1998}
1999
2000pub fn installed(spec: &AgentSpec) -> bool {
2002 spec.kind.program().is_none_or(crate::config::which)
2005}
2006
2007pub fn pick(
2029 agents: &[AgentSpec],
2030 want: Option<&str>,
2031 available: &dyn Fn(&AgentSpec) -> bool,
2032) -> Result<AgentSpec> {
2033 if let Some(id) = want {
2034 let spec = agents
2035 .iter()
2036 .find(|a| a.id == id)
2037 .with_context(|| format!("no agent `{id}` in the roster; it has {}", ids(agents)))?;
2038 if !available(spec) {
2039 bail!(
2040 "agent `{}` needs `{}` on PATH; install it or pass a different \
2041 --agent",
2042 spec.id,
2043 spec.kind.program().unwrap_or("its command")
2044 );
2045 }
2046 return Ok(spec.clone());
2047 }
2048
2049 if agents.is_empty() {
2050 bail!(
2051 "the agent roster is empty, so there is nobody to ask: install one \
2052 of claude, opencode or agy - magi derives a roster from what is on \
2053 PATH - or add an [[agents]] entry to magi.toml."
2054 );
2055 }
2056
2057 if let Some(spec) = agents
2058 .iter()
2059 .find(|a| a.kind == AgentKind::Claude && available(a))
2060 {
2061 return Ok(spec.clone());
2062 }
2063
2064 agents
2065 .iter()
2066 .find(|a| available(a))
2067 .cloned()
2068 .with_context(|| {
2069 let missing = agents
2070 .iter()
2071 .filter_map(|a| a.kind.program())
2072 .collect::<Vec<_>>()
2073 .join(", ");
2074 format!(
2075 "no agent in the roster can be run here: install one of \
2076 {missing}, or add an [[agents]] entry to magi.toml for a CLI \
2077 you do have"
2078 )
2079 })
2080}
2081
2082pub fn for_github_text(spec: &AgentSpec, github_language: &str, cwd: &Path) -> Result<AgentSpec> {
2095 let mut spec = spec.clone();
2096 if spec.kind == AgentKind::Claude {
2097 let mut existing = None;
2100 let mut args = spec.extra_args.iter().enumerate();
2101 while let Some((index, arg)) = args.next() {
2102 if arg == "--settings" {
2103 let (value_index, value) = args.next().context("--settings requires a value")?;
2104 existing = Some((value_index, value.as_str(), false));
2105 } else if let Some(value) = arg.strip_prefix("--settings=") {
2106 existing = Some((index, value, true));
2107 }
2108 }
2109 let mut settings = if let Some((_, value, _)) = existing {
2110 let json = if value.trim_start().starts_with('{') {
2111 value.to_owned()
2112 } else {
2113 std::fs::read_to_string(cwd.join(value))
2114 .context("cannot read existing seat --settings file")?
2115 };
2116 serde_json::from_str::<serde_json::Value>(&json)
2117 .context("cannot parse existing seat --settings JSON")?
2118 } else {
2119 serde_json::json!({})
2120 };
2121 settings
2122 .as_object_mut()
2123 .context("seat --settings must be a JSON object")?
2124 .insert(
2125 "language".to_owned(),
2126 serde_json::json!(crate::lang::name(github_language)),
2127 );
2128 let settings = settings.to_string();
2129 if let Some((index, _, equals)) = existing {
2130 spec.extra_args[index] = if equals {
2131 format!("--settings={settings}")
2132 } else {
2133 settings
2134 };
2135 } else {
2136 spec.extra_args.extend(["--settings".to_owned(), settings]);
2137 }
2138 }
2139 Ok(spec)
2140}
2141
2142pub fn pick_chain(
2150 agents: &[AgentSpec],
2151 choice: Option<&AgentChoice>,
2152 available: &dyn Fn(&AgentSpec) -> bool,
2153 role: &str,
2154) -> Result<Vec<AgentSpec>> {
2155 let wanted = choice.map(AgentChoice::ids).unwrap_or_default();
2156 if wanted.is_empty() {
2157 return pick(agents, None, available)
2158 .map(|s| vec![s])
2159 .with_context(|| format!("choose an agent for the {role} role"));
2160 }
2161 let mut chain: Vec<AgentSpec> = Vec::new();
2162 for id in wanted {
2163 if chain.iter().any(|s| s.id == id) {
2164 continue;
2165 }
2166 match pick(agents, Some(id), available) {
2167 Ok(spec) => chain.push(spec),
2168 Err(e) => tracing::warn!("[roles] {role}: skipping `{id}`: {e:#}"),
2169 }
2170 }
2171 if chain.is_empty() {
2172 bail!(
2173 "[roles] {role} names no agent that can run here; the roster has {}",
2174 ids(agents)
2175 );
2176 }
2177 Ok(chain)
2178}
2179
2180pub fn chain_advances(outcome: &Result<AgentOutput>) -> bool {
2186 match outcome {
2187 Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => false,
2188 Err(_) => true,
2189 Ok(out) => output_advances(out),
2190 }
2191}
2192
2193pub fn output_advances(out: &AgentOutput) -> bool {
2197 out.quota_exhausted() || !out.usable()
2198}
2199
2200fn ids(agents: &[AgentSpec]) -> String {
2201 if agents.is_empty() {
2202 return "no agents at all".to_owned();
2203 }
2204 agents
2205 .iter()
2206 .map(|a| a.id.clone())
2207 .collect::<Vec<_>>()
2208 .join(", ")
2209}
2210
2211#[cfg(all(test, unix))]
2214pub(crate) mod test_watchdog {
2215 use super::*;
2216 static FLOORS: Mutex<BTreeMap<String, u64>> = Mutex::new(BTreeMap::new());
2217
2218 pub(crate) struct Guard(String);
2219
2220 pub(crate) fn set(run: &str, floor: u64) -> Guard {
2221 assert!(
2222 FLOORS
2223 .lock()
2224 .unwrap()
2225 .insert(run.to_owned(), floor)
2226 .is_none()
2227 );
2228 Guard(run.to_owned())
2229 }
2230
2231 pub(super) fn floor(run: &str, configured: u64) -> u64 {
2232 FLOORS
2233 .lock()
2234 .unwrap()
2235 .get(run)
2236 .copied()
2237 .unwrap_or(configured)
2238 }
2239
2240 impl Drop for Guard {
2241 fn drop(&mut self) {
2242 FLOORS.lock().unwrap().remove(&self.0);
2243 }
2244 }
2245}
2246
2247#[cfg(test)]
2248mod tests {
2249 use super::*;
2250
2251 const COMMAND_HELPER_MODE: &str = "MAGI_TEST_COMMAND_HELPER_MODE";
2252
2253 fn command_helper(mode: &str) -> AgentSpec {
2256 crate::run::pin_test_home();
2258 AgentSpec {
2259 id: "helper".to_owned(),
2260 kind: AgentKind::Command,
2261 model: None,
2262 command: vec![
2263 std::env::current_exe()
2264 .expect("locate test helper")
2265 .to_string_lossy()
2266 .into_owned(),
2267 "--exact".to_owned(),
2268 "agent::tests::command_agent_test_helper".to_owned(),
2269 "--nocapture".to_owned(),
2270 ],
2271 extra_args: Vec::new(),
2272 env: BTreeMap::from([(COMMAND_HELPER_MODE.to_owned(), mode.to_owned())]),
2273 prompt_delivery: None,
2274 max_turn_secs: None,
2275 }
2276 }
2277
2278 #[test]
2279 fn command_agent_test_helper() {
2280 match std::env::var(COMMAND_HELPER_MODE).as_deref() {
2281 Ok("reply") => println!("hello {}", std::env::var("MAGI_SEAT").unwrap()),
2282 Ok("cache") => println!("{}", std::env::var("CARGO_TARGET_DIR").unwrap()),
2283 Ok("no-cache") => println!(
2284 "{}",
2285 std::env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| "ABSENT".to_owned())
2286 ),
2287 Ok("ignore-stdin") => println!("done"),
2288 Ok("chatty-sleep") => {
2289 println!("i-said-something");
2290 std::thread::sleep(Duration::from_secs(30));
2291 }
2292 Ok("sleep") => std::thread::sleep(Duration::from_secs(30)),
2293 Ok(other) => panic!("unknown command helper mode {other}"),
2294 Err(_) => {}
2295 }
2296 }
2297
2298 fn spec(kind: AgentKind, model: Option<&str>) -> AgentSpec {
2299 AgentSpec {
2300 id: "a".to_owned(),
2301 kind,
2302 model: model.map(str::to_owned),
2303 command: vec!["echo".to_owned(), "{label}".to_owned()],
2304 extra_args: Vec::new(),
2305 env: BTreeMap::new(),
2306 prompt_delivery: None,
2307 max_turn_secs: None,
2308 }
2309 }
2310
2311 fn inv<'a>(cwd: &'a Path, art: &'a Path, allow_write: bool) -> Invocation<'a> {
2312 Invocation {
2313 coordination: None,
2314 fetched_base: None,
2315 cwd,
2316 prompt: "do the thing",
2317 timeout: Duration::from_secs(900),
2318 allow_write,
2319 sessions: true,
2320 artifacts: art,
2321 stem: "t",
2322 run: "test-run",
2323 node: "test",
2324 cache_dir: None,
2325 attachments: &[],
2326 writable: &[],
2327 }
2328 }
2329
2330 fn plan_for(kind: AgentKind, seat: &SeatState, allow_write: bool) -> Plan {
2331 build_command(
2332 &spec(kind, None),
2333 seat,
2334 &inv(Path::new("."), Path::new("/art"), allow_write),
2335 Path::new("/art/p.md"),
2336 )
2337 .unwrap()
2338 }
2339
2340 #[test]
2341 fn editing_access_requires_fetch_evidence_and_keeps_snapshot() {
2342 let missing = editing_access_note(None);
2343 assert!(missing.contains("No successful launcher fetch evidence"));
2344 let base = crate::run::FetchedBase {
2345 remote: "origin".into(),
2346 branch: "main".into(),
2347 commit: "0123456789abcdef".into(),
2348 fetched_at: "2026-10-18T00:00:00Z".parse().unwrap(),
2349 };
2350 let note = editing_access_note(Some(&base));
2351 for expected in [
2352 "origin/main",
2353 "0123456789abcdef",
2354 "2026-10-18T00:00:00Z",
2355 "Do not fetch again",
2356 ] {
2357 assert!(note.contains(expected), "missing {expected}");
2358 }
2359 for text in [&missing, ¬e] {
2362 assert!(!text.to_lowercase().contains("sandbox"), "{text}");
2363 assert!(!text.contains("Network access is restricted"), "{text}");
2364 }
2365 let roundtrip: crate::run::FetchedBase =
2366 serde_json::from_str(&serde_json::to_string(&base).unwrap()).unwrap();
2367 assert_eq!(editing_access_note(Some(&roundtrip)), note);
2368 }
2369
2370 #[test]
2371 fn codex_editing_seats_bypass_the_sandbox_on_initial_and_resume() {
2372 const BYPASS: &str = "--dangerously-bypass-approvals-and-sandbox";
2373 let roots = [PathBuf::from("/shared/git"), PathBuf::from("/questions")];
2374 for resumed in [false, true] {
2375 let mut seat = SeatState::new("impl-A", "a", 7);
2376 if resumed {
2377 seat.turns = 1;
2378 seat.captured_session = Some("fixture-thread".into());
2379 }
2380 let build = |invocation: &Invocation<'_>| {
2381 build_command(
2382 &spec(AgentKind::Codex, None),
2383 &seat,
2384 invocation,
2385 Path::new("/art/p.md"),
2386 )
2387 .unwrap()
2388 };
2389 for node in [
2390 "implement",
2391 "fix",
2392 "graft",
2393 "gate-fix",
2394 "land",
2395 "rebase",
2396 "base-conflict",
2397 crate::queue::CHAT_NODE,
2398 "external-chat",
2399 ] {
2400 let mut invocation = inv(Path::new("."), Path::new("/art"), true);
2401 invocation.node = node;
2402 invocation.writable = &roots;
2403 let plan = build(&invocation);
2404 let at = plan.argv.iter().position(|s| s == BYPASS);
2405 assert!(at.is_some(), "{node}: {:?}", plan.argv);
2406 if resumed {
2407 let resume = plan.argv.iter().position(|s| s == "resume").unwrap();
2408 assert!(at.unwrap() < resume, "{node}: {:?}", plan.argv);
2409 }
2410 assert!(!plan.argv.iter().any(|s| s == "--sandbox"), "{node}");
2412 assert!(!plan.argv.iter().any(|s| s == "-c"), "{node}");
2413 }
2414 for (node, write) in [
2415 ("review", false),
2416 ("judge", false),
2417 ("advise", false),
2418 ("implement", false),
2419 ("fix", false),
2420 ("dupes", false),
2421 ("conduct", false),
2422 ("waiter", false),
2423 ("talk-title", false),
2424 (crate::queue::CHAT_NODE, false),
2425 ("external-chat", false),
2426 ("deputy", true),
2427 ] {
2428 let mut invocation = inv(Path::new("."), Path::new("/art"), write);
2429 invocation.node = node;
2430 let plan = build(&invocation);
2431 assert!(!plan.argv.iter().any(|s| s == BYPASS), "{node}");
2432 let mode = if write {
2433 "workspace-write"
2434 } else {
2435 "read-only"
2436 };
2437 assert!(
2438 plan.argv.windows(2).any(|w| w == ["--sandbox", mode]),
2439 "{node}: {:?}",
2440 plan.argv
2441 );
2442 assert!(
2443 plan.argv
2444 .windows(2)
2445 .any(|w| w == ["-c", "approval_policy=\"never\""]),
2446 "{node}"
2447 );
2448 }
2449 }
2450 }
2451
2452 #[test]
2453 fn claude_mints_then_resumes_the_same_uuid() {
2454 let mut seat = SeatState::new("judge-1", "a", 7);
2455 let uuid = seat.claude_session.clone().unwrap();
2456 let first = plan_for(AgentKind::Claude, &seat, true);
2457 assert!(first.argv.windows(2).any(|w| w == ["--session-id", &uuid]));
2458 assert!(!first.argv.iter().any(|a| a == "--resume"));
2459
2460 seat.turns = 1;
2461 let second = plan_for(AgentKind::Claude, &seat, true);
2462 assert!(second.argv.windows(2).any(|w| w == ["--resume", &uuid]));
2463 assert!(!second.argv.iter().any(|a| a == "--session-id"));
2464 }
2465
2466 #[test]
2467 fn github_bound_claude_seats_override_the_operators_answer_language() {
2468 let seat = SeatState::new("change-summary", "a", 7);
2469 let art = Path::new("/art");
2470 for (language, name) in [("en", "English"), ("", "English"), ("ja", "Japanese")] {
2471 let claude =
2472 for_github_text(&spec(AgentKind::Claude, None), language, Path::new(".")).unwrap();
2473 let plan = build_command(
2474 &claude,
2475 &seat,
2476 &inv(Path::new("."), art, false),
2477 Path::new("/art/p.md"),
2478 )
2479 .unwrap();
2480 let settings = format!(r#"{{"language":"{name}"}}"#);
2481 assert!(
2482 plan.argv
2483 .windows(2)
2484 .any(|w| w == ["--settings", settings.as_str()]),
2485 "{:?}",
2486 plan.argv
2487 );
2488 assert_eq!(plan.stdin.as_deref(), Some("do the thing"));
2491 }
2492 for kind in [
2493 AgentKind::Codex,
2494 AgentKind::Opencode,
2495 AgentKind::Antigravity,
2496 AgentKind::Omp,
2497 ] {
2498 assert!(
2499 for_github_text(&spec(kind, None), "en", Path::new("."))
2500 .unwrap()
2501 .extra_args
2502 .is_empty()
2503 );
2504 }
2505 }
2506
2507 #[test]
2508 fn github_text_preserves_existing_settings() {
2509 let dir = tempfile::tempdir().unwrap();
2510 let original = serde_json::json!({
2511 "language": "Japanese",
2512 "env": { "SEAT_MODE": "configured" },
2513 "apiKeyHelper": "credential-helper",
2514 "hooks": { "Stop": [] }
2515 });
2516 std::fs::write(dir.path().join("seat-settings.json"), original.to_string()).unwrap();
2517 for value in [original.to_string(), "./seat-settings.json".to_owned()] {
2518 for equals in [false, true] {
2519 let mut spec = spec(AgentKind::Claude, None);
2520 spec.extra_args = vec!["--settings={\"language\":\"French\"}".to_owned()];
2522 if equals {
2523 spec.extra_args.push(format!("--settings={value}"));
2524 } else {
2525 spec.extra_args
2526 .extend(["--settings".to_owned(), value.clone()]);
2527 }
2528 spec.extra_args.push("--verbose".to_owned());
2529 let updated = for_github_text(&spec, "en", dir.path()).unwrap();
2530 assert_eq!(updated.extra_args.len(), spec.extra_args.len());
2531 assert_eq!(updated.extra_args[0], spec.extra_args[0]);
2532 assert_eq!(updated.extra_args.last(), spec.extra_args.last());
2533 let value = &updated.extra_args[updated.extra_args.len() - 2];
2534 let actual: serde_json::Value =
2535 serde_json::from_str(value.strip_prefix("--settings=").unwrap_or(value))
2536 .unwrap();
2537 let mut expected = original.clone();
2538 expected["language"] = serde_json::json!("English");
2539 assert_eq!(actual, expected);
2540 }
2541 }
2542 let on_disk: serde_json::Value = serde_json::from_str(
2543 &std::fs::read_to_string(dir.path().join("seat-settings.json")).unwrap(),
2544 )
2545 .unwrap();
2546 assert_eq!(on_disk, original);
2547 }
2548
2549 #[test]
2550 fn github_text_settings_are_redacted_from_command_logging() {
2551 let dir = tempfile::tempdir().unwrap();
2552 let settings = serde_json::json!({ "env": { "AUTH_TOKEN": "test-only-secret" } });
2553 std::fs::write(dir.path().join("seat-settings.json"), settings.to_string()).unwrap();
2554 for equals in [false, true] {
2555 let mut spec = spec(AgentKind::Claude, None);
2556 spec.extra_args =
2557 vec!["--settings={\"env\":{\"AUTH_TOKEN\":\"earlier-secret\"}}".to_owned()];
2558 if equals {
2559 spec.extra_args
2560 .push("--settings=./seat-settings.json".to_owned());
2561 } else {
2562 spec.extra_args
2563 .extend(["--settings".to_owned(), "./seat-settings.json".to_owned()]);
2564 }
2565 let spec = for_github_text(&spec, "en", dir.path()).unwrap();
2566 let plan = build_command(
2567 &spec,
2568 &SeatState::new("change-summary", "a", 7),
2569 &inv(dir.path(), dir.path(), false),
2570 &dir.path().join("prompt.md"),
2571 )
2572 .unwrap();
2573 let actual = plan.argv.last().unwrap();
2575 let actual: serde_json::Value =
2576 serde_json::from_str(actual.strip_prefix("--settings=").unwrap_or(actual)).unwrap();
2577 assert_eq!(actual["env"]["AUTH_TOKEN"], "test-only-secret");
2578 assert_eq!(actual["language"], "English");
2579 let logged = format!("{:?}", plan.logged_argv());
2580 assert!(!logged.contains("secret"));
2581 assert!(!logged.contains("AUTH_TOKEN"));
2582 assert!(logged.contains("[redacted]"));
2583 assert_eq!(plan.logged_argv()[0], "claude");
2584 assert!(plan.logged_argv().contains(&"--output-format"));
2585 }
2586 }
2587
2588 #[test]
2589 fn github_text_rejects_unreadable_or_invalid_settings() {
2590 let dir = tempfile::tempdir().unwrap();
2591 std::fs::write(dir.path().join("bad.json"), "invalid json").unwrap();
2592 std::fs::write(dir.path().join("array.json"), "[]").unwrap();
2593 for args in [
2594 vec!["--settings"],
2595 vec!["--settings", "missing.json"],
2596 vec!["--settings=bad.json"],
2597 vec!["--settings", "array.json"],
2598 ] {
2599 let mut spec = spec(AgentKind::Claude, None);
2600 spec.extra_args = args.into_iter().map(str::to_owned).collect();
2601 assert!(for_github_text(&spec, "en", dir.path()).is_err());
2602 }
2603 }
2604
2605 #[test]
2606 fn read_only_seats_cannot_edit() {
2607 let seat = SeatState::new("judge-1", "a", 7);
2608 let claude = plan_for(AgentKind::Claude, &seat, false);
2609 assert!(claude.argv.iter().any(|a| a == "--disallowed-tools"));
2610 assert!(
2611 !plan_for(AgentKind::Claude, &seat, true)
2612 .argv
2613 .iter()
2614 .any(|a| a == "--disallowed-tools")
2615 );
2616
2617 let agy = plan_for(AgentKind::Antigravity, &seat, false);
2618 assert!(agy.argv.windows(2).any(|w| w == ["--mode", "plan"]));
2619 assert!(
2620 !agy.argv
2621 .iter()
2622 .any(|a| a == "--dangerously-skip-permissions")
2623 );
2624 let agy_rw = plan_for(AgentKind::Antigravity, &seat, true);
2625 assert!(
2626 agy_rw
2627 .argv
2628 .windows(2)
2629 .any(|w| w == ["--mode", "accept-edits"])
2630 );
2631 assert!(
2632 agy_rw
2633 .argv
2634 .iter()
2635 .any(|a| a == "--dangerously-skip-permissions")
2636 );
2637 let agy_prompt = agy_rw
2642 .argv
2643 .iter()
2644 .position(|a| a == "-p")
2645 .map(|i| agy_rw.argv[i + 1].clone())
2646 .expect("agy takes its prompt with -p");
2647 assert!(
2648 agy_prompt.starts_with('@'),
2649 "agy must get a file reference, got {agy_prompt:?}"
2650 );
2651 assert!(
2652 !agy_prompt.contains("Read the file at"),
2653 "the prose pointer is for CLIs with no file syntax"
2654 );
2655
2656 for allow_write in [false, true] {
2661 assert!(
2662 plan_for(AgentKind::Opencode, &seat, allow_write)
2663 .argv
2664 .iter()
2665 .any(|a| a == "--auto"),
2666 "opencode needs --auto even to read (allow_write = {allow_write})"
2667 );
2668 }
2669 }
2670
2671 #[test]
2674 fn codex_gets_extra_writable_roots_only_when_it_may_write() {
2675 let seat = SeatState::new("deputy-x", "a", 7);
2676 let roots = [PathBuf::from("/data/questions")];
2677 let mk = |allow_write: bool| {
2678 let mut i = inv(Path::new("."), Path::new("/art"), allow_write);
2679 i.writable = &roots;
2680 build_command(
2681 &spec(AgentKind::Codex, None),
2682 &seat,
2683 &i,
2684 Path::new("/art/p.md"),
2685 )
2686 .unwrap()
2687 };
2688 let want = "sandbox_workspace_write.writable_roots=[\"/data/questions\"]";
2689 assert!(mk(true).argv.windows(2).any(|w| w == ["-c", want]));
2690 assert!(!mk(false).argv.iter().any(|a| a.contains("writable_roots")));
2691 }
2692
2693 #[test]
2694 fn repository_write_scope_covers_editing_nodes_without_changing_other_roles() {
2695 let mut i = inv(Path::new("."), Path::new("/art"), true);
2696 for node in [
2697 "implement",
2698 "fix",
2699 "graft",
2700 "gate-fix",
2701 "land",
2702 "rebase",
2703 "base-conflict",
2704 "chat",
2705 "external-chat",
2706 ] {
2707 i.node = node;
2708 assert!(repository_writer(&i), "{node}");
2709 i.allow_write = false;
2710 assert!(!repository_writer(&i), "{node}");
2711 i.allow_write = true;
2712 }
2713 for node in ["deputy", "judge", "review", "bump", "conduct", "talk-title"] {
2714 i.node = node;
2715 assert!(!repository_writer(&i), "{node}");
2716 }
2717 i.node = "chat";
2718 let roots = [PathBuf::from("/questions")];
2719 i.writable = &roots;
2720 assert!(
2721 repository_writer(&i),
2722 "explicit roots do not change the role"
2723 );
2724 assert!(
2725 !repository_seat(&i),
2726 "chat turns bypass repository scheduling"
2727 );
2728 }
2729
2730 #[test]
2731 fn coordination_classification_is_independent_of_write_grants() {
2732 let roots = [PathBuf::from("/questions")];
2733 for node in [
2734 crate::queue::CHAT_NODE,
2735 "external-chat",
2736 "implement",
2737 "fix",
2738 "graft",
2739 "gate-fix",
2740 "land",
2741 "rebase",
2742 "base-conflict",
2743 "review",
2744 "judge",
2745 "advise",
2746 "deputy",
2747 "waiter",
2748 "conduct",
2749 "dupes",
2750 "talk-title",
2751 ] {
2752 for allow_write in [false, true] {
2753 for writable in [&[][..], &roots[..]] {
2754 let mut i = inv(Path::new("."), Path::new("/art"), allow_write);
2755 i.node = node;
2756 i.writable = writable;
2757 assert_eq!(
2758 repository_seat(&i),
2759 !matches!(
2760 node,
2761 crate::queue::CHAT_NODE
2762 | "external-chat"
2763 | "talk-title"
2764 | "deputy"
2765 | "conduct"
2766 | "dupes"
2767 ),
2768 "{node}, allow_write={allow_write}, writable={writable:?}"
2769 );
2770 if matches!(node, crate::queue::CHAT_NODE | "external-chat") {
2771 assert_eq!(repository_writer(&i), allow_write);
2772 }
2773 }
2774 }
2775 }
2776 }
2777
2778 #[test]
2779 fn writable_directories_reach_initial_and_resumed_adapter_commands() {
2780 let roots = [
2781 PathBuf::from("/shared/git"),
2782 PathBuf::from("/state/questions"),
2783 ];
2784 for kind in [AgentKind::Codex, AgentKind::Antigravity] {
2785 for resumed in [false, true] {
2786 let mut seat = SeatState::new("impl-A", "a", 7);
2787 if resumed {
2788 seat.turns = 1;
2789 seat.captured_session = Some("session-id".into());
2790 }
2791 for allow_write in [false, true] {
2792 let mut i = inv(Path::new("."), Path::new("/art"), allow_write);
2793 i.writable = &roots;
2794 let plan = build_command(&spec(kind, None), &seat, &i, Path::new("/art/p.md"))
2795 .unwrap();
2796 for root in &roots {
2797 if kind == AgentKind::Antigravity {
2798 assert_eq!(
2799 plan.argv.windows(2).any(|w| {
2800 w[0] == "--add-dir" && w[1] == root.to_str().unwrap()
2801 }),
2802 allow_write,
2803 "resumed={resumed}: {:?}",
2804 plan.argv
2805 );
2806 }
2807 assert_eq!(
2808 plan.argv
2809 .iter()
2810 .any(|arg| arg.contains(root.to_str().unwrap())),
2811 allow_write,
2812 "{kind:?}, resumed={resumed}: {:?}",
2813 plan.argv
2814 );
2815 }
2816 if kind == AgentKind::Codex && resumed {
2817 let at = plan.argv.iter().position(|s| s == "resume").unwrap();
2818 assert!(!plan.argv[at..].iter().any(|s| s == "-c"));
2819 }
2820 }
2821 }
2822 }
2823 }
2824
2825 #[test]
2826 fn codex_is_sandboxed_reads_stdin_and_puts_resume_last() {
2827 let mut seat = SeatState::new("judge-1", "a", 7);
2828
2829 let ro = plan_for(AgentKind::Codex, &seat, false);
2835 assert!(ro.argv.windows(2).any(|w| w == ["--sandbox", "read-only"]));
2836 let rw = plan_for(AgentKind::Codex, &seat, true);
2837 assert!(
2838 rw.argv
2839 .windows(2)
2840 .any(|w| w == ["--sandbox", "workspace-write"])
2841 );
2842 for p in [&ro, &rw] {
2843 assert!(
2844 !p.argv
2845 .iter()
2846 .any(|a| a == "--dangerously-bypass-approvals-and-sandbox"),
2847 "the bypass defeats the only enforced read-only mode we have"
2848 );
2849 assert!(
2851 p.argv
2852 .windows(2)
2853 .any(|w| w == ["-c", "approval_policy=\"never\""]),
2854 "an unattended seat that asks for approval blocks until timeout"
2855 );
2856 }
2857
2858 assert_eq!(ro.stdin.as_deref(), Some("do the thing"));
2860 assert_eq!(
2861 ro.argv.last().map(String::as_str),
2862 Some("-"),
2863 "without the `-` argument codex waits for a prompt it never gets"
2864 );
2865
2866 seat.turns = 1;
2870 assert!(!has_session(AgentKind::Codex, &seat, true));
2871 assert!(
2872 !plan_for(AgentKind::Codex, &seat, true)
2873 .argv
2874 .iter()
2875 .any(|a| a == "resume")
2876 );
2877 seat.captured_session = Some("01a07440-4545-7492-85c1-024e3259a90a".to_owned());
2878 let resumed = plan_for(AgentKind::Codex, &seat, true);
2879 let at = resumed
2880 .argv
2881 .iter()
2882 .position(|a| a == "resume")
2883 .expect("resumes by subcommand");
2884 assert_eq!(resumed.argv[at + 1], "01a07440-4545-7492-85c1-024e3259a90a");
2885 assert!(
2886 resumed.argv[..at].iter().any(|a| a == "--sandbox"),
2887 "every option precedes the subcommand"
2888 );
2889 assert_eq!(resumed.argv.last().map(String::as_str), Some("-"));
2890 }
2891
2892 #[test]
2895 fn omp_reads_stdin_auto_approves_and_resumes_by_id() {
2896 let mut seat = SeatState::new("review-1", "a", 7);
2897
2898 let first = plan_for(AgentKind::Omp, &seat, false);
2902 assert!(first.argv.iter().any(|a| a == "-p"));
2903 assert!(first.argv.iter().any(|a| a == "--mode=json"));
2904 assert_eq!(first.stdin.as_deref(), Some("do the thing"));
2905 assert!(
2906 !first.argv.iter().any(|a| a == "do the thing"),
2907 "the prompt reached argv, where Windows caps it"
2908 );
2909
2910 for allow_write in [false, true] {
2916 let p = plan_for(AgentKind::Omp, &seat, allow_write);
2917 assert!(
2918 p.argv.iter().any(|a| a == "--auto-approve"),
2919 "omp needs --auto-approve even to read (allow_write = {allow_write})"
2920 );
2921 assert!(
2922 !p.argv
2923 .iter()
2924 .any(|a| a == "--dangerously-bypass-approvals-and-sandbox"),
2925 "nothing ever asks for the bypass"
2926 );
2927 }
2928
2929 seat.turns = 1;
2932 assert!(!has_session(AgentKind::Omp, &seat, true));
2933 assert!(
2934 !plan_for(AgentKind::Omp, &seat, true)
2935 .argv
2936 .iter()
2937 .any(|a| a == "--resume")
2938 );
2939 seat.captured_session = Some("01a09fe9-4e31-7226-85b3-fda6f46689d5".to_owned());
2940 let resumed = plan_for(AgentKind::Omp, &seat, true);
2941 assert!(
2942 resumed
2943 .argv
2944 .windows(2)
2945 .any(|w| w == ["--resume", "01a09fe9-4e31-7226-85b3-fda6f46689d5"]),
2946 "a captured id is what makes the next turn a resume"
2947 );
2948 assert!(!resumed.argv.iter().any(|a| a == "--continue"));
2951 assert_eq!(resumed.stdin.as_deref(), Some("do the thing"));
2953 }
2954
2955 #[test]
2956 fn omp_terminal_breadcrumbs_are_disabled_only_for_managed_sessions() {
2957 let mut seat = SeatState::new("review-1", "a", 7);
2958 let mut cmd = Command::new("omp");
2959 cmd.envs([
2960 ("ZELLIJ_PANE_ID", "1"),
2961 ("TMUX_PANE", "%2"),
2962 ("CMUX_SURFACE_ID", "terminal"),
2963 ("KITTY_WINDOW_ID", "3"),
2964 ("WEZTERM_PANE", "4"),
2965 ("TERM_SESSION_ID", "terminal"),
2966 ("WT_SESSION", "terminal"),
2967 ("OMP_PROFILE", "work"),
2968 ]);
2969 let envs = |cmd: &Command| {
2970 cmd.as_std()
2971 .get_envs()
2972 .filter(|(_, value)| value.is_some())
2973 .count()
2974 };
2975 OmpSession::Resume.isolate_terminal_history(&mut cmd, &seat);
2976 assert_eq!(envs(&cmd), 8);
2977 OmpSession::Fresh(PathBuf::from("managed")).isolate_terminal_history(&mut cmd, &seat);
2978 assert_eq!(envs(&cmd), 1);
2979 assert!(
2980 cmd.as_std()
2981 .get_envs()
2982 .any(|(key, value)| { key == "OMP_PROFILE" && value == Some(OsStr::new("work")) })
2983 );
2984
2985 seat.omp_session_dir = Some(PathBuf::from("managed"));
2986 cmd.env("WT_SESSION", "terminal");
2987 OmpSession::Resume.isolate_terminal_history(&mut cmd, &seat);
2988 assert_eq!(envs(&cmd), 1);
2989 }
2990
2991 #[test]
2992 fn omp_managed_session_persists_native_path_and_reuses_it_after_reload() {
2993 let tmp = tempfile::tempdir().unwrap();
2994 let home = tmp.path().join("magi home 日本語");
2995 let spec = spec(AgentKind::Omp, None);
2996 let mut seat = SeatState::new("review-1", "a", 7);
2997 let art = tmp.path().join("art");
2998 let cwd = tmp.path().join("other checkout");
2999 let mut invocation = inv(&cwd, &art, false);
3000 let prompt = art.join("p.md");
3001
3002 let fresh = OmpSession::prepare(&spec, &seat, true, || home.clone()).unwrap();
3003 let dir = fresh.dir(&seat).unwrap().to_owned();
3004 assert_eq!(dir.parent().unwrap(), home.join("agent-sessions/omp"));
3005 assert!(dir.is_absolute() && dir.is_dir());
3006 assert!(
3007 !dir.file_name()
3008 .unwrap()
3009 .to_str()
3010 .unwrap()
3011 .contains(&seat.key)
3012 );
3013 let plan = build_command(&spec, &seat, &invocation, &prompt).unwrap();
3014 let args: Vec<_> = plan.args(Some(&dir)).collect();
3015 assert_eq!(&args[..2], [OsStr::new("--session-dir"), dir.as_os_str()]);
3016 assert!(!args.contains(&OsStr::new("--resume")));
3017 fresh
3018 .record(&mut seat, Some("first-id".into()), true)
3019 .unwrap();
3020 seat.turns += 1;
3021
3022 let mut seat: SeatState =
3023 serde_json::from_slice(&serde_json::to_vec(&seat).unwrap()).unwrap();
3024 let resumed = OmpSession::prepare(&spec, &seat, true, || {
3025 panic!("resume must not resolve home")
3026 })
3027 .unwrap();
3028 let plan = build_command(&spec, &seat, &invocation, &prompt).unwrap();
3029 let args: Vec<_> = plan.args(resumed.dir(&seat)).collect();
3030 assert_eq!(&args[..2], [OsStr::new("--session-dir"), dir.as_os_str()]);
3031 assert!(args.windows(2).any(|w| w == ["--resume", "first-id"]));
3032 let before = seat.clone();
3033 assert!(
3034 resumed
3035 .record(&mut seat, Some("other-id".into()), true)
3036 .is_err()
3037 );
3038 assert!(OmpSession::Resume.record(&mut seat, None, true).is_err());
3039 assert_eq!(seat, before);
3040 OmpSession::Resume.record(&mut seat, None, false).unwrap();
3042 assert_eq!(seat, before);
3043
3044 let fallback = SeatState::new("review-1", "b", 7);
3045 let next = OmpSession::prepare(&spec, &fallback, true, || home.clone()).unwrap();
3046 assert_ne!(next.dir(&fallback).unwrap(), dir);
3047 invocation.sessions = false;
3049 let fresh = OmpSession::prepare(&spec, &seat, false, || home.clone()).unwrap();
3050 let new_dir = fresh.dir(&seat).unwrap().to_owned();
3051 assert_ne!(new_dir, dir);
3052 assert_ne!(next.dir(&fallback).unwrap(), new_dir);
3053 assert!(
3054 !build_command(&spec, &seat, &invocation, &prompt)
3055 .unwrap()
3056 .args(Some(&new_dir))
3057 .any(|arg| arg == "--resume")
3058 );
3059 fresh
3060 .record(&mut seat, Some("fresh-id".into()), true)
3061 .unwrap();
3062 assert_eq!(seat.omp_session_dir.as_deref(), Some(new_dir.as_path()));
3063 assert_eq!(seat.captured_session.as_deref(), Some("fresh-id"));
3064
3065 std::fs::remove_dir(new_dir).unwrap();
3066 assert!(OmpSession::prepare(&spec, &seat, true, || home.clone()).is_err());
3067 }
3068
3069 #[test]
3070 fn omp_pre_isolation_json_resumes_without_a_session_directory() {
3071 let mut seat: SeatState = serde_json::from_str(
3072 r#"{"key":"review-1","agent":"a","turns":1,"claude_session":null,"captured_session":"legacy-id"}"#,
3073 )
3074 .unwrap();
3075 let resume = OmpSession::prepare(&spec(AgentKind::Omp, None), &seat, true, || {
3076 panic!("legacy resume must not resolve or create a store")
3077 })
3078 .unwrap();
3079 let plan = plan_for(AgentKind::Omp, &seat, false);
3080 let args: Vec<_> = plan.args(resume.dir(&seat)).collect();
3081 assert!(!args.contains(&OsStr::new("--session-dir")));
3082 assert!(args.windows(2).any(|w| w == ["--resume", "legacy-id"]));
3083 resume
3084 .record(&mut seat, Some("continuation-id".into()), true)
3085 .unwrap();
3086 assert!(seat.omp_session_dir.is_none());
3087 assert_eq!(seat.captured_session.as_deref(), Some("continuation-id"));
3088 let plan = plan_for(AgentKind::Omp, &seat, false);
3089 assert!(
3090 plan.args(None)
3091 .zip(plan.args(None).skip(1))
3092 .any(|(flag, id)| flag == "--resume" && id == "continuation-id")
3093 );
3094 }
3095
3096 #[test]
3097 fn omp_managed_resume_tracks_only_local_continuation_lineage() {
3098 let tmp = tempfile::tempdir().unwrap();
3099 let managed = tmp.path().join("managed");
3100 std::fs::create_dir(&managed).unwrap();
3101 let mut seat = SeatState::new("review-1", "a", 7);
3102 seat.turns = 1;
3103 seat.captured_session = Some("original".into());
3104 seat.omp_session_dir = Some(managed.clone());
3105
3106 let write_header = |dir: &Path, id: &str, parent: &str| {
3107 let header = serde_json::json!({
3108 "type": "session", "version": 3, "id": id, "continuationOf": parent,
3109 });
3110 std::fs::write(dir.join(format!("{id}.jsonl")), format!("{header}\n")).unwrap();
3111 };
3112 write_header(tmp.path(), "outside", "original");
3113 write_header(&managed, "unrelated", "other-seat");
3114 write_header(&managed, "middle", "original");
3115 write_header(&managed, "latest", "middle");
3116 for id in ["outside", "unrelated"] {
3117 assert!(
3118 OmpSession::Resume
3119 .record(&mut seat, Some(id.into()), true)
3120 .is_err()
3121 );
3122 assert_eq!(seat.captured_session.as_deref(), Some("original"));
3123 }
3124
3125 OmpSession::Resume
3126 .record(&mut seat, Some("latest".into()), true)
3127 .unwrap();
3128 assert_eq!(seat.omp_session_dir.as_deref(), Some(managed.as_path()));
3129 let plan = plan_for(AgentKind::Omp, &seat, false);
3130 assert!(plan.argv.windows(2).any(|w| w == ["--resume", "latest"]));
3131 }
3132
3133 #[test]
3134 fn omp_managed_session_rejects_extra_args_that_override_history() {
3135 let mut spec = spec(AgentKind::Omp, None);
3136 let mut seat = SeatState::new("review-1", "a", 7);
3137 for arg in [
3138 "--session-dir",
3139 "--session-dir=other",
3140 "--no-session",
3141 "--continue",
3142 "--resume=other",
3143 "--session",
3144 "--session=operator.jsonl",
3145 "--fork",
3146 "--fork=operator.jsonl",
3147 "--restore",
3148 "--from-claude",
3149 "--from-codex",
3150 "-c",
3151 "-r=other",
3152 ] {
3153 spec.extra_args = vec![arg.into()];
3154 for sessions in [false, true] {
3155 let error = OmpSession::prepare(&spec, &seat, sessions, || panic!("invalid arg"))
3156 .err()
3157 .unwrap();
3158 assert!(error.to_string().contains("omp extra_args"));
3159 }
3160 seat.turns = 1;
3161 seat.captured_session = Some("existing-id".into());
3162 seat.omp_session_dir = Some(PathBuf::from("not-opened"));
3163 }
3164 }
3165
3166 #[test]
3171 fn omp_takes_the_answer_without_an_agent_end_line() {
3172 let stream = concat!(
3173 r#"{"type":"session","version":3,"id":"01a09fe9-4e31-7226-85b3-fda6f46689d5","cwd":"C:\\w"}"#,
3174 "\n",
3175 r#"{"type":"agent_start"}"#,
3176 "\n",
3177 r#"{"type":"turn_start"}"#,
3178 "\n",
3179 r#"{"type":"message_update","assistantMessageEvent":{"type":"text_delta","contentIndex":1,"delta":"."}}"#,
3180 "\n",
3181 r#"{"type":"message_end","message":{"role":"assistant","content":[{"type":"thinking","thinking":"checking"},{"type":"text","text":"."}]}}"#,
3182 "\n",
3183 r#"{"type":"turn_end","message":{"role":"assistant","content":[{"type":"thinking","thinking":"done"},{"type":"text","text":"{\"vote\":\"approve\"}"}]}}"#,
3184 "\n",
3185 );
3186 let out = extract(AgentKind::Omp, stream);
3187 assert_eq!(
3188 out.text, "{\"vote\":\"approve\"}",
3189 "the last assistant text block is the answer even with no agent_end"
3190 );
3191 assert_eq!(
3192 out.session.as_deref(),
3193 Some("01a09fe9-4e31-7226-85b3-fda6f46689d5")
3194 );
3195 }
3196
3197 #[test]
3201 fn omp_walks_agent_end_and_ignores_tool_loop_narration() {
3202 let stream = concat!(
3203 r#"{"type":"session","version":3,"id":"s1"}"#,
3204 "\n",
3205 "{\"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問題ありません。\"}]}]}",
3206 "\n",
3207 );
3208 let out = extract(AgentKind::Omp, stream);
3209 assert_eq!(
3210 out.text, "## 判定\n\n問題ありません。",
3211 "the narration is not the answer, and non-ASCII survives intact"
3212 );
3213 assert_eq!(out.session.as_deref(), Some("s1"));
3214 }
3215
3216 #[test]
3219 fn omp_skips_non_json_lines() {
3220 let stream = concat!(
3221 "Warning: some omp notice\n",
3222 r#"{"type":"session","version":3,"id":"s2"}"#,
3223 "\n",
3224 r#"{"type":"message_end","message":{"role":"assistant","content":[{"type":"text","text":"the answer"}]}}"#,
3225 "\n",
3226 "trailing junk",
3227 "\n",
3228 );
3229 let out = extract(AgentKind::Omp, stream);
3230 assert_eq!(out.text, "the answer");
3231 assert_eq!(out.session.as_deref(), Some("s2"));
3232 }
3233
3234 #[test]
3236 fn codex_takes_the_last_agent_message_and_the_thread_id() {
3237 let stream = concat!(
3238 "2026-09-06T01:05:49.394445Z ERROR codex_models_manager: failed to load models cache\n",
3239 r#"{"type":"thread.started","thread_id":"01a07440-4545-7492-85c1-024e3259a90a"}"#,
3240 "\n",
3241 r#"{"type":"turn.started"}"#,
3242 "\n",
3243 r#"{"type":"item.completed","item":{"id":"item_0","type":"agent_message","text":"Looking into it."}}"#,
3244 "\n",
3245 r#"{"type":"item.completed","item":{"id":"item_1","type":"command_execution","text":"cargo test"}}"#,
3246 "\n",
3247 r#"{"type":"item.completed","item":{"id":"item_2","type":"agent_message","text":"{\"verdict\": \"ok\"}"}}"#,
3248 "\n",
3249 r#"{"type":"turn.completed","usage":{"input_tokens":17137}}"#,
3250 "\n",
3251 );
3252 let out = extract(AgentKind::Codex, stream);
3253 assert_eq!(
3254 out.text, "{\"verdict\": \"ok\"}",
3255 "the last agent message is the answer; earlier ones narrate"
3256 );
3257 assert_eq!(
3258 out.session.as_deref(),
3259 Some("01a07440-4545-7492-85c1-024e3259a90a")
3260 );
3261 assert_eq!(out.status.as_deref(), Some("success"));
3262
3263 let failed = concat!(
3264 r#"{"type":"thread.started","thread_id":"t1"}"#,
3265 "\n",
3266 r#"{"type":"turn.failed","error":{"message":"nope"}}"#,
3267 "\n",
3268 );
3269 assert_eq!(
3270 extract(AgentKind::Codex, failed).status.as_deref(),
3271 Some("error")
3272 );
3273 }
3274
3275 #[test]
3276 fn captured_sessions_resume_only_once_reported() {
3277 let mut seat = SeatState::new("impl-A", "a", 7);
3278 seat.turns = 1;
3279 for kind in [AgentKind::Opencode, AgentKind::Antigravity] {
3280 assert!(!has_session(kind, &seat, true));
3281 let p = plan_for(kind, &seat, true);
3282 assert!(!p.argv.iter().any(|a| a == "-s" || a == "--conversation"));
3283 }
3284
3285 seat.captured_session = Some("sid".to_owned());
3286 assert!(has_session(AgentKind::Opencode, &seat, true));
3287 assert!(
3288 plan_for(AgentKind::Opencode, &seat, true)
3289 .argv
3290 .windows(2)
3291 .any(|w| w == ["-s", "sid"])
3292 );
3293 assert!(
3294 plan_for(AgentKind::Antigravity, &seat, true)
3295 .argv
3296 .windows(2)
3297 .any(|w| w == ["--conversation", "sid"])
3298 );
3299 }
3300
3301 #[test]
3302 fn sessions_disabled_never_resumes() {
3303 let mut seat = SeatState::new("impl-A", "a", 7);
3304 seat.turns = 3;
3305 seat.captured_session = Some("sid".to_owned());
3306 for kind in [
3307 AgentKind::Claude,
3308 AgentKind::Opencode,
3309 AgentKind::Antigravity,
3310 ] {
3311 assert!(!has_session(kind, &seat, false));
3312 }
3313 }
3314
3315 #[test]
3316 fn long_prompts_never_reach_argv_for_file_delivery_clis() {
3317 let seat = SeatState::new("judge-1", "a", 7);
3318 for kind in [AgentKind::Opencode, AgentKind::Antigravity] {
3319 let p = plan_for(kind, &seat, false);
3320 assert!(
3321 p.argv.iter().all(|a| a != "do the thing"),
3322 "{kind:?} put the prompt on the command line"
3323 );
3324 assert!(p.argv.iter().any(|a| a.contains("/art/p.md")));
3325 }
3326 let p = plan_for(AgentKind::Antigravity, &seat, false);
3328 let at = p.argv.iter().position(|a| a == "-p").unwrap();
3329 assert!(p.argv.get(at + 1).is_some_and(|v| v.contains("p.md")));
3330 assert!(p.stdin.is_none());
3331 }
3332
3333 #[test]
3334 fn agy_print_timeout_tracks_the_node_budget() {
3335 let seat = SeatState::new("impl-A", "a", 7);
3336 let p = build_command(
3337 &spec(AgentKind::Antigravity, None),
3338 &seat,
3339 &Invocation {
3340 coordination: None,
3341 fetched_base: None,
3342 cwd: Path::new("."),
3343 prompt: "p",
3344 timeout: Duration::from_secs(3600),
3345 allow_write: true,
3346 sessions: true,
3347 artifacts: Path::new("/art"),
3348 stem: "t",
3349 run: "test-run",
3350 node: "test",
3351 cache_dir: None,
3352 attachments: &[],
3353 writable: &[],
3354 },
3355 Path::new("/art/p.md"),
3356 )
3357 .unwrap();
3358 assert!(p.argv.windows(2).any(|w| w == ["--print-timeout", "3600s"]));
3359 }
3360
3361 #[test]
3368 fn attachments_widen_antigravitys_add_dir_even_off_file_delivery() {
3369 let mut s = spec(AgentKind::Antigravity, None);
3370 s.prompt_delivery = Some(Delivery::Argv);
3371 let seat = SeatState::new("talk", "a", 7);
3372 let atts = [PathBuf::from("/art/attachments/abc.png")];
3373
3374 let without = build_command(
3375 &s,
3376 &seat,
3377 &Invocation {
3378 attachments: &[],
3379 writable: &[],
3380 ..inv(Path::new("."), Path::new("/art"), true)
3381 },
3382 Path::new("/art/p.md"),
3383 )
3384 .unwrap();
3385 assert!(
3386 !without.argv.iter().any(|a| a == "--add-dir"),
3387 "no attachment, no reason to widen the sandbox: {without:?}"
3388 );
3389
3390 let with = build_command(
3391 &s,
3392 &seat,
3393 &Invocation {
3394 attachments: &atts,
3395 writable: &[],
3396 ..inv(Path::new("."), Path::new("/art"), true)
3397 },
3398 Path::new("/art/p.md"),
3399 )
3400 .unwrap();
3401 assert!(
3402 with.argv.windows(2).any(|w| w == ["--add-dir", "/art"]),
3403 "an attachment outside cwd must widen the sandbox even off File delivery: {with:?}"
3404 );
3405 }
3406
3407 #[test]
3413 fn an_inherited_attachment_outside_this_conversations_artifacts_dir_gets_its_own_add_dir() {
3414 let seat = SeatState::new("plan", "a", 7);
3415 let atts = [
3416 PathBuf::from("/art/attachments/own.png"),
3417 PathBuf::from("/other-chat/attachments/inherited.png"),
3418 ];
3419
3420 let p = build_command(
3421 &spec(AgentKind::Antigravity, None),
3422 &seat,
3423 &Invocation {
3424 attachments: &atts,
3425 writable: &[],
3426 ..inv(Path::new("."), Path::new("/art"), true)
3427 },
3428 Path::new("/art/p.md"),
3429 )
3430 .unwrap();
3431
3432 assert!(
3433 p.argv.windows(2).any(|w| w == ["--add-dir", "/art"]),
3434 "this conversation's own artifacts dir must still be granted: {p:?}"
3435 );
3436 assert!(
3437 p.argv
3438 .windows(2)
3439 .any(|w| w == ["--add-dir", "/other-chat/attachments"]),
3440 "the inherited attachment's own directory must be granted too: {p:?}"
3441 );
3442 }
3443
3444 #[test]
3445 fn command_agents_get_placeholders_substituted() {
3446 let seat = SeatState::new("impl-A", "a", 7);
3447 let p = plan_for(AgentKind::Command, &seat, true);
3448 assert_eq!(p.argv[0], "echo");
3449 assert_eq!(p.argv[1], "impl-A");
3450 assert_eq!(p.stdin.as_deref(), Some("do the thing"));
3451 }
3452
3453 const EXPIRED_AUTH: &str = r#"{"is_error":true,"terminal_reason":"api_error","result":"Failed to authenticate: OAuth session expired and could not be refreshed"}"#;
3454 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."}
3455{"type":"turn.failed","error":{"message":"You've hit your usage limit."}}"#;
3456
3457 #[test]
3458 fn observed_machine_failures_are_detected_conservatively() {
3459 let auth = extract(AgentKind::Claude, EXPIRED_AUTH).quota.unwrap();
3460 assert_eq!(auth.cause, QuotaCause::Authentication);
3461 assert_eq!(auth.reset, None);
3462 let limit = extract(AgentKind::Codex, CODEX_LIMIT).quota.unwrap();
3463 assert_eq!(limit.cause, QuotaCause::UsageLimit);
3464 assert_eq!(limit.reset.as_deref(), Some("Oct 27th, 2026 6:18 PM"));
3465 assert!(
3467 extract(AgentKind::Codex, &format!("{CODEX_LIMIT}\n{CODEX_LIMIT}"))
3468 .quota
3469 .is_some()
3470 );
3471 let without_reset = CODEX_LIMIT.replace(" or try again at Oct 27th, 2026 6:18 PM", "");
3472 assert!(
3473 extract(AgentKind::Codex, &without_reset)
3474 .quota
3475 .unwrap()
3476 .reset
3477 .is_none()
3478 );
3479 for text in [
3480 EXPIRED_AUTH.replace("true", "false"),
3481 EXPIRED_AUTH.replace("api_error", "unknown"),
3482 EXPIRED_AUTH.replace(
3483 "OAuth session expired and could not be refreshed",
3484 "unknown error",
3485 ),
3486 ] {
3487 assert!(extract(AgentKind::Claude, &text).quota.is_none());
3488 }
3489 assert!(
3490 extract(AgentKind::Codex, CODEX_LIMIT.lines().next().unwrap())
3491 .quota
3492 .is_none()
3493 );
3494 assert!(
3495 extract(
3496 AgentKind::Codex,
3497 &CODEX_LIMIT.replace("You've hit your usage limit.", "Something failed.")
3498 )
3499 .quota
3500 .is_none()
3501 );
3502 let quoted = serde_json::json!({"type":"item.completed","item":{"type":"agent_message","text":CODEX_LIMIT}}).to_string();
3503 assert!(extract(AgentKind::Codex, "ed).quota.is_none());
3504 assert!(extract(AgentKind::Codex, EXPIRED_AUTH).quota.is_none());
3505 assert!(
3506 extract(AgentKind::Antigravity, EXPIRED_AUTH)
3507 .quota
3508 .is_none()
3509 );
3510 let legacy: Quota = serde_json::from_str(r#"{"reset":null}"#).unwrap();
3511 assert_eq!(legacy.cause, QuotaCause::UsageLimit);
3512 }
3513
3514 #[test]
3515 fn claude_rate_limit_is_detected_and_reset_read_when_present() {
3516 let stdout = r#"{"is_error": true, "terminal_reason": "api_error",
3518 "result": "You've hit your session limit · resets 4:50am (Asia/Tokyo)",
3519 "session_id": "b8e928f1-754e-4bd3-86c5-0567763654e3"}"#;
3520 let out = extract(AgentKind::Claude, stdout);
3521 let quota = out.quota.as_ref().expect("rate limit must be detected");
3522 assert_eq!(
3523 quota.reset.as_deref(),
3524 Some("4:50am (Asia/Tokyo)"),
3525 "reset time read from the body"
3526 );
3527 }
3528
3529 #[test]
3530 fn claude_rate_limit_without_a_readable_reset_is_still_detected() {
3531 let out = extract(
3532 AgentKind::Claude,
3533 r#"{"is_error":true,"result":"session limit reached"}"#,
3534 );
3535 let quota = out.quota.expect("rate limit detected without a reset");
3536 assert!(quota.reset.is_none(), "unknown reset is kept as unknown");
3537 }
3538
3539 #[test]
3540 fn claude_structured_usage_limit_requires_the_error_and_exact_pair() {
3541 for kind in [AgentKind::Claude, AgentKind::Command] {
3542 for reply in [
3543 r#"{"is_error":true,"api_error_status":429,"api_error":"usage_limit_reached"}"#,
3544 r#"{"is_error":true,"api_error_status":"429","api_error":"usage_limit_reached"}"#,
3545 ] {
3546 assert!(extract(kind, reply).quota.is_some(), "{reply}");
3547 }
3548 for reply in [
3549 r#"{"is_error":false,"api_error_status":429,"api_error":"usage_limit_reached"}"#,
3550 r#"{"is_error":true,"api_error_status":500,"api_error":"usage_limit_reached"}"#,
3551 r#"{"is_error":true,"api_error_status":429,"api_error":"other_error"}"#,
3552 r#"{"is_error":false,"api_error_status":"429","api_error":"usage_limit_reached"}"#,
3553 r#"{"is_error":true,"api_error_status":"500","api_error":"usage_limit_reached"}"#,
3554 r#"{"is_error":true,"api_error_status":"429","api_error":"other_error"}"#,
3555 r#"{"is_error":true,"api_error":"usage_limit_reached"}"#,
3556 ] {
3557 assert!(extract(kind, reply).quota.is_none(), "{reply}");
3558 }
3559 }
3560 }
3561
3562 #[test]
3563 fn ordinary_failures_are_never_quota() {
3564 let claude_fail = extract(
3566 AgentKind::Claude,
3567 r#"{"is_error":true,"result":"account does not exist"}"#,
3568 );
3569 assert!(claude_fail.quota.is_none());
3570
3571 let cmd_fail = extract(AgentKind::Command, "boom");
3573 assert!(cmd_fail.quota.is_none());
3574
3575 let success = extract(
3577 AgentKind::Command,
3578 r#"{"is_error":false,"result":"session limit is fine"}"#,
3579 );
3580 assert!(success.quota.is_none());
3581 }
3582
3583 #[test]
3591 fn codex_command_execution_events_are_captured_alongside_the_final_message() {
3592 let stream = concat!(
3593 r#"{"type":"thread.started","thread_id":"t1"}"#,
3594 "\n",
3595 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"}}"#,
3596 "\n",
3597 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"}}"#,
3598 "\n",
3599 r#"{"type":"item.completed","item":{"id":"item99","type":"agent_message","text":"Both tests in the target pass."}}"#,
3600 "\n",
3601 r#"{"type":"turn.completed"}"#,
3602 "\n",
3603 );
3604 let out = extract(AgentKind::Codex, stream);
3605 assert_eq!(out.text, "Both tests in the target pass.");
3606 assert_eq!(out.commands.len(), 2, "{:?}", out.commands);
3607
3608 let paired = &out.commands[0];
3609 assert_eq!(paired.id, "item49");
3610 assert_eq!(paired.exit_code, Some(1));
3611 assert!(paired.description.contains("graph_cached_gate"));
3612 assert!(paired.result_summary.contains("1 failed"));
3613
3614 let solo = &out.commands[1];
3615 assert_eq!(solo.exit_code, Some(0));
3616
3617 assert!(
3621 out.commands
3622 .iter()
3623 .any(|c| c.exit_code != Some(0) && c.description.contains("graph_cached_gate")),
3624 "a failed run of the actual target must still be visible: {:?}",
3625 out.commands
3626 );
3627 }
3628
3629 #[test]
3630 fn command_agent_can_carry_the_claude_quota_shape() {
3631 let out = extract(
3632 AgentKind::Command,
3633 r#"{"is_error":true,"result":"You've hit your session limit · resets 1:00am (UTC)"}"#,
3634 );
3635 assert!(
3636 out.quota.is_some(),
3637 "a wrapper emitting the claude shape counts as quota"
3638 );
3639 }
3640
3641 #[test]
3642 fn claude_json_result_is_extracted() {
3643 let out = extract(
3644 AgentKind::Claude,
3645 r#"{"result":"all done","session_id":"abc","is_error":false}"#,
3646 );
3647 assert_eq!(out.text, "all done");
3648 assert_eq!(out.session.as_deref(), Some("abc"));
3649 assert_eq!(out.status.as_deref(), Some("success"));
3650 }
3651
3652 #[test]
3667 fn a_clean_cli_turn_is_not_the_same_fact_as_the_nodes_own_work_being_done() {
3668 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"}"#;
3669 let out = extract(AgentKind::Claude, stdout);
3670 assert_eq!(out.status.as_deref(), Some("success"));
3671 assert!(out.quota.is_none());
3672 assert!(!out.text.trim().is_empty());
3673
3674 let agent_out = AgentOutput {
3675 text: out.text.clone(),
3676 exit_code: Some(0),
3677 timed_out: false,
3678 duration_ms: 500,
3679 artifacts: Vec::new(),
3680 quota: out.quota,
3681 dropped: out.dropped,
3682 commands: out.commands,
3683 context_tokens: None,
3684 };
3685 assert!(
3686 agent_out.usable(),
3687 "the CLI turn itself ended cleanly and must read as usable"
3688 );
3689 assert!(
3690 crate::verdict::extract_json::<crate::verdict::FixReport>(&agent_out.text).is_err(),
3691 "a clean CLI turn is not proof the node's own report ever arrived"
3692 );
3693 }
3694
3695 #[test]
3696 fn opencode_event_stream_is_concatenated() {
3697 let stream = concat!(
3698 r#"{"type":"step_start","sessionID":"ses_1","part":{"type":"step-start"}}"#,
3699 "\n",
3700 r#"{"type":"text","sessionID":"ses_1","part":{"type":"text","text":"first"}}"#,
3701 "\n",
3702 "garbage line\n",
3703 r#"{"type":"text","sessionID":"ses_1","part":{"type":"text","text":"second"}}"#,
3704 "\n"
3705 );
3706 let out = extract(AgentKind::Opencode, stream);
3707 assert_eq!(out.text, "first\nsecond");
3708 assert_eq!(out.session.as_deref(), Some("ses_1"));
3709 }
3710
3711 #[test]
3712 fn agy_json_survives_a_leading_warning_line() {
3713 let stdout = concat!(
3714 "warning: --mode plan has no effect while slash commands are disabled.\n",
3715 r#"{"conversation_id":"eaf2d00a","status":"SUCCESS","response":"persimmon\n"}"#,
3716 "\n"
3717 );
3718 let out = extract(AgentKind::Antigravity, stdout);
3719 assert_eq!(out.text, "persimmon");
3720 assert_eq!(out.session.as_deref(), Some("eaf2d00a"));
3721 assert_eq!(out.status.as_deref(), Some("SUCCESS"));
3722 }
3723
3724 const AGY_DROPPED: &str = concat!(
3731 r#"{"conversation_id":"36743d06-c0b3-4b79-9fa2-23869289d7b6","status":"ERROR","#,
3732 r#""response":"","error":"the connection to the agent was interrupted before "#,
3733 r#"the response finished: subscriber fell behind updates, stalled for 5s","#,
3734 r#""duration_seconds":431.1941803,"num_turns":1,"usage":{"input_tokens":260113,"#,
3735 r#""output_tokens":14267,"thinking_tokens":9695,"cache_read_tokens":2200925,"#,
3736 r#""total_tokens":274380}}"#
3737 );
3738
3739 const AGY_QUOTA_OUT: &str = concat!(
3741 r#"{"conversation_id":"323c3b5b-0000","status":"ERROR","response":"","#,
3742 r#""error":"Individual quota reached. Please upgrade your subscription to "#,
3743 r#"increase your limits. Resets in 1h2m49s.","duration_seconds":265.9,"#,
3744 r#""num_turns":2,"usage":{"input_tokens":1000,"output_tokens":50}}"#
3745 );
3746 const AGY_QUOTA_ERR: &str = concat!(
3747 "error: Individual quota reached. Resets in 1h2m49s.\n",
3748 r#"AGY_ERROR: {"short_error":"RESOURCE_EXHAUSTED (code 429): Individual quota "#,
3749 r#"reached.","status":"RESOURCE_EXHAUSTED","error_code":429,"code_kind":"http","#,
3750 r#""retryable":true}"#,
3751 "\n"
3752 );
3753
3754 #[test]
3755 fn agy_out_of_quota_is_a_quota_with_the_reset_hint() {
3756 let both = agy_quota(AGY_QUOTA_OUT, AGY_QUOTA_ERR).expect("both streams");
3757 assert_eq!(both.reset.as_deref(), Some("in 1h2m49s"));
3758 let stdout_only = agy_quota(AGY_QUOTA_OUT, "").expect("stdout alone");
3759 assert_eq!(stdout_only.reset.as_deref(), Some("in 1h2m49s"));
3760 let stderr_only = agy_quota("not json", AGY_QUOTA_ERR).expect("stderr alone");
3762 assert!(stderr_only.reset.is_none());
3763 }
3764
3765 #[test]
3766 fn ordinary_agy_failures_are_not_a_quota() {
3767 assert!(agy_quota(AGY_DROPPED, "").is_none());
3768 assert!(agy_quota(r#"{"status":"ERROR","error":"boom"}"#, "").is_none());
3769 assert!(
3770 agy_quota(
3771 "",
3772 r#"AGY_ERROR: {"status":"RESOURCE_EXHAUSTED","error_code":500}"#
3773 )
3774 .is_none()
3775 );
3776 assert!(
3777 agy_quota(
3778 "",
3779 r#"AGY_ERROR: {"status":"UNAVAILABLE","error_code":429}"#
3780 )
3781 .is_none()
3782 );
3783 assert!(agy_quota(r#"{"status":"SUCCESS","response":"ok"}"#, "").is_none());
3784 }
3785
3786 #[test]
3787 fn a_cli_that_hangs_up_on_billed_work_is_not_an_agent_that_produced_nothing() {
3788 let out = extract(AgentKind::Antigravity, AGY_DROPPED);
3789 let dropped = out.dropped.expect("recognised as undelivered work");
3790 assert_eq!(dropped.output_tokens, 14267);
3791 assert!(
3792 dropped.why.contains("subscriber fell behind"),
3793 "the CLI's own words are kept for the record: {}",
3794 dropped.why
3795 );
3796 assert_eq!(
3799 out.session.as_deref(),
3800 Some("36743d06-c0b3-4b79-9fa2-23869289d7b6")
3801 );
3802 assert!(out.quota.is_none(), "a dropped stream is not a rate limit");
3803 }
3804
3805 #[test]
3806 fn an_error_with_nothing_produced_stays_an_ordinary_failure() {
3807 let bare = r#"{"conversation_id":"c1","status":"ERROR","response":"","error":"boom"}"#;
3811 assert!(extract(AgentKind::Antigravity, bare).dropped.is_none());
3812
3813 let answered = concat!(
3816 r#"{"conversation_id":"c2","status":"ERROR","response":"here it is","#,
3817 r#""usage":{"output_tokens":10}}"#
3818 );
3819 assert!(extract(AgentKind::Antigravity, answered).dropped.is_none());
3820
3821 let ok = concat!(
3823 r#"{"conversation_id":"c3","status":"SUCCESS","response":"done","#,
3824 r#""usage":{"output_tokens":10}}"#
3825 );
3826 assert!(extract(AgentKind::Antigravity, ok).dropped.is_none());
3827 }
3828
3829 #[test]
3830 fn an_undelivered_output_is_not_usable_but_is_worth_asking_again() {
3831 let out = AgentOutput {
3832 text: String::new(),
3833 exit_code: Some(1),
3834 timed_out: false,
3835 duration_ms: 431_194,
3836 artifacts: Vec::new(),
3837 quota: None,
3838 dropped: Some(Dropped {
3839 why: "subscriber fell behind updates".to_owned(),
3840 output_tokens: 14267,
3841 }),
3842 commands: Vec::new(),
3843 context_tokens: None,
3844 };
3845 assert!(!out.usable());
3846 assert!(out.work_undelivered());
3847 assert!(!out.quota_exhausted());
3850 }
3851
3852 #[test]
3853 fn non_json_stdout_falls_back_to_raw_text() {
3854 let out = extract(AgentKind::Antigravity, "plain answer\n");
3855 assert_eq!(out.text, "plain answer");
3856 assert!(out.session.is_none());
3857 }
3858
3859 #[tokio::test]
3860 async fn command_agent_round_trip_writes_artifacts() {
3861 let dir = tempfile::tempdir().unwrap();
3862 let art = dir.path().join("artifacts");
3863 let mut seat = SeatState::new("impl-A", "a", 7);
3864 let s = command_helper("reply");
3865 let out = invoke(
3866 &s,
3867 &mut seat,
3868 &Invocation {
3869 coordination: None,
3870 fetched_base: None,
3871 cwd: dir.path(),
3872 prompt: "unused",
3873 timeout: Duration::from_secs(30),
3874 allow_write: true,
3875 sessions: true,
3876 artifacts: &art,
3877 stem: "impl-A",
3878 run: "test-run",
3879 node: "test",
3880 cache_dir: None,
3881 attachments: &[],
3882 writable: &[],
3883 },
3884 )
3885 .await
3886 .unwrap();
3887 assert!(out.usable(), "{out:?}");
3888 assert!(out.text.contains("hello impl-A"), "{}", out.text);
3889 assert_eq!(seat.turns, 1);
3890 assert!(art.join("impl-A.prompt.md").is_file());
3891 assert!(art.join("impl-A.out").is_file());
3892 }
3893
3894 #[tokio::test]
3895 async fn the_invocation_cache_dir_reaches_the_seat_as_cargo_target_dir() {
3896 crate::run::pin_test_home();
3897 let dir = tempfile::tempdir().unwrap();
3901 let cache = dir.path().join("magi-cache");
3902 let mut seat = SeatState::new("impl-A", "a", 7);
3903 let s = command_helper("cache");
3904 let out = invoke(
3905 &s,
3906 &mut seat,
3907 &Invocation {
3908 coordination: None,
3909 fetched_base: None,
3910 cwd: dir.path(),
3911 prompt: "unused",
3912 timeout: Duration::from_secs(30),
3913 allow_write: true,
3914 sessions: true,
3915 artifacts: &dir.path().join("artifacts"),
3916 stem: "cache",
3917 run: "test-run",
3918 node: "test",
3919 cache_dir: Some(&cache),
3920 attachments: &[],
3921 writable: &[],
3922 },
3923 )
3924 .await
3925 .unwrap();
3926 assert!(out.usable(), "{out:?}");
3927 assert!(
3928 out.text.contains(cache.to_string_lossy().as_ref()),
3929 "the seat must see CARGO_TARGET_DIR = the shared cache"
3930 );
3931 }
3932
3933 #[tokio::test]
3934 async fn cache_dir_none_strips_a_cargo_target_dir_inherited_from_this_process() {
3935 let previous = std::env::var("CARGO_TARGET_DIR").ok();
3943 unsafe {
3948 std::env::set_var("CARGO_TARGET_DIR", "/should/never/reach/a/read-only/seat");
3949 }
3950 let dir = tempfile::tempdir().unwrap();
3951 let mut seat = SeatState::new("review-1", "a", 7);
3952 let s = command_helper("no-cache");
3953 let result = invoke(
3954 &s,
3955 &mut seat,
3956 &Invocation {
3957 coordination: None,
3958 fetched_base: None,
3959 cwd: dir.path(),
3960 prompt: "unused",
3961 timeout: Duration::from_secs(30),
3962 allow_write: false,
3963 sessions: true,
3964 artifacts: &dir.path().join("artifacts"),
3965 stem: "no-cache",
3966 run: "test-run",
3967 node: "test",
3968 cache_dir: None,
3969 attachments: &[],
3970 writable: &[],
3971 },
3972 )
3973 .await;
3974 unsafe {
3979 match &previous {
3980 Some(v) => std::env::set_var("CARGO_TARGET_DIR", v),
3981 None => std::env::remove_var("CARGO_TARGET_DIR"),
3982 }
3983 }
3984 let out = result.unwrap();
3985 assert!(out.usable(), "{out:?}");
3986 assert!(
3987 out.text.contains("ABSENT"),
3988 "a read-only seat must never inherit the process's own CARGO_TARGET_DIR: {}",
3989 out.text
3990 );
3991 }
3992
3993 #[tokio::test]
3994 async fn a_prompt_larger_than_the_pipe_buffer_does_not_deadlock() {
3995 let dir = tempfile::tempdir().unwrap();
3996 let mut seat = SeatState::new("impl-A", "a", 7);
3997 let s = command_helper("ignore-stdin");
4000 let big = "x".repeat(1_000_000);
4001 let out = invoke(
4002 &s,
4003 &mut seat,
4004 &Invocation {
4005 coordination: None,
4006 fetched_base: None,
4007 cwd: dir.path(),
4008 prompt: &big,
4009 timeout: Duration::from_secs(60),
4010 allow_write: true,
4011 sessions: true,
4012 artifacts: &dir.path().join("artifacts"),
4013 stem: "big",
4014 run: "test-run",
4015 node: "test",
4016 cache_dir: None,
4017 attachments: &[],
4018 writable: &[],
4019 },
4020 )
4021 .await
4022 .unwrap();
4023 assert!(out.usable(), "{out:?}");
4024 assert!(out.text.contains("done"), "{}", out.text);
4025 }
4026
4027 #[tokio::test]
4028 async fn agent_turn_cap_limits_a_direct_invocation() {
4029 let dir = tempfile::tempdir().unwrap();
4030 let artifacts = dir.path().join("artifacts");
4031 let mut seat = SeatState::new("impl-A", "helper", 7);
4032 let mut s = command_helper("sleep");
4033 s.max_turn_secs = Some(2);
4034 let out = invoke(&s, &mut seat, &inv(dir.path(), &artifacts, false))
4035 .await
4036 .unwrap();
4037 assert!(out.timed_out, "{out:?}");
4038 assert!(out.duration_ms < 20_000, "{out:?}");
4041 }
4042
4043 #[tokio::test]
4044 async fn timeout_is_reported_not_hung() {
4045 let dir = tempfile::tempdir().unwrap();
4046 let mut seat = SeatState::new("impl-A", "a", 7);
4047 let s = command_helper("sleep");
4048 let out = invoke(
4049 &s,
4050 &mut seat,
4051 &Invocation {
4052 coordination: None,
4053 fetched_base: None,
4054 cwd: dir.path(),
4055 prompt: "unused",
4056 timeout: Duration::from_millis(300),
4057 allow_write: true,
4058 sessions: true,
4059 artifacts: &dir.path().join("artifacts"),
4060 stem: "slow",
4061 run: "test-run",
4062 node: "test",
4063 cache_dir: None,
4064 attachments: &[],
4065 writable: &[],
4066 },
4067 )
4068 .await
4069 .unwrap();
4070 assert!(out.timed_out);
4071 assert!(!out.usable());
4072 }
4073
4074 #[tokio::test]
4075 async fn a_timeout_keeps_what_the_agent_had_already_printed() {
4076 let dir = tempfile::tempdir().unwrap();
4082 let artifacts = dir.path().join("artifacts");
4083 let mut seat = SeatState::new("impl-A", "a", 7);
4084 let s = command_helper("chatty-sleep");
4085 let out = invoke(
4086 &s,
4087 &mut seat,
4088 &Invocation {
4089 coordination: None,
4090 fetched_base: None,
4091 cwd: dir.path(),
4092 prompt: "unused",
4093 timeout: Duration::from_secs(10),
4098 allow_write: true,
4099 sessions: true,
4100 artifacts: &artifacts,
4101 stem: "chatty",
4102 run: "test-run",
4103 node: "test",
4104 cache_dir: None,
4105 attachments: &[],
4106 writable: &[],
4107 },
4108 )
4109 .await
4110 .unwrap();
4111
4112 assert!(out.timed_out, "{out:?}");
4113 assert!(!out.usable(), "a cut-off answer is still not an answer");
4114 let recorded = std::fs::read_to_string(artifacts.join("chatty.out")).unwrap();
4115 assert!(
4116 recorded.contains("i-said-something"),
4117 "the artifact must keep what arrived before the kill, got {recorded:?}"
4118 );
4119 assert!(
4120 out.text.contains("i-said-something"),
4121 "and the graph must be able to see it too, got {:?}",
4122 out.text
4123 );
4124 }
4125
4126 #[test]
4127 fn missing_programs_reports_command_binaries() {
4128 let mut s = spec(AgentKind::Command, None);
4129 s.command = vec!["definitely-not-a-real-binary-xyz".to_owned()];
4130 assert_eq!(
4131 missing_programs(&[s]),
4132 ["definitely-not-a-real-binary-xyz".to_owned()]
4133 );
4134 }
4135
4136 fn pick_spec(id: &str, kind: AgentKind) -> AgentSpec {
4137 AgentSpec {
4138 id: id.to_owned(),
4139 kind,
4140 model: None,
4141 command: Vec::new(),
4142 extra_args: Vec::new(),
4143 env: BTreeMap::new(),
4144 prompt_delivery: None,
4145 max_turn_secs: None,
4146 }
4147 }
4148
4149 fn without<'a>(missing: &'a [&'a str]) -> impl Fn(&AgentSpec) -> bool + 'a {
4152 move |a: &AgentSpec| !missing.contains(&a.id.as_str())
4153 }
4154
4155 #[test]
4156 fn pick_prefers_the_claude_seat_even_when_it_is_not_first_in_the_roster() {
4157 let agents = [
4158 pick_spec("oc", AgentKind::Opencode),
4159 pick_spec("opus", AgentKind::Claude),
4160 pick_spec("agy", AgentKind::Antigravity),
4161 ];
4162 let got = pick(&agents, None, &without(&[])).expect("a pick");
4163 assert_eq!(got.id, "opus");
4164 }
4165
4166 #[test]
4167 fn pick_falls_back_to_the_first_installed_agent_in_roster_order() {
4168 let agents = [
4169 pick_spec("opus", AgentKind::Claude),
4170 pick_spec("oc", AgentKind::Opencode),
4171 pick_spec("agy", AgentKind::Antigravity),
4172 ];
4173 let got = pick(&agents, None, &without(&["opus", "oc"])).expect("a pick");
4174 assert_eq!(got.id, "agy");
4175 }
4176
4177 #[test]
4178 fn pick_on_an_empty_roster_says_what_to_install() {
4179 let msg = pick(&[], None, &without(&[]))
4180 .expect_err("nobody to ask")
4181 .to_string();
4182 assert!(msg.contains("roster is empty"), "{msg}");
4183 assert!(msg.contains("claude"), "{msg}");
4184 assert!(msg.contains("magi.toml"), "{msg}");
4185 }
4186
4187 #[test]
4188 fn pick_on_a_roster_with_nothing_installed_names_the_programs_that_are_missing() {
4189 let agents = [
4190 pick_spec("opus", AgentKind::Claude),
4191 pick_spec("oc", AgentKind::Opencode),
4192 ];
4193 let err = pick(&agents, None, &without(&["opus", "oc"])).expect_err("nothing runnable");
4194 let msg = format!("{err:#}");
4195 assert!(msg.contains("claude"), "{msg}");
4196 assert!(msg.contains("opencode"), "{msg}");
4197 }
4198
4199 #[test]
4200 fn an_explicitly_named_agent_wins_over_the_claude_preference() {
4201 let agents = [
4202 pick_spec("opus", AgentKind::Claude),
4203 pick_spec("oc", AgentKind::Opencode),
4204 ];
4205 let got = pick(&agents, Some("oc"), &without(&[])).expect("a pick");
4206 assert_eq!(got.id, "oc");
4207 }
4208
4209 #[test]
4210 fn an_unknown_agent_id_lists_the_ids_that_do_exist() {
4211 let agents = [
4212 pick_spec("opus", AgentKind::Claude),
4213 pick_spec("oc", AgentKind::Opencode),
4214 ];
4215 let msg = pick(&agents, Some("gemini"), &without(&[]))
4216 .expect_err("no such agent")
4217 .to_string();
4218 assert!(msg.contains("gemini"), "{msg}");
4219 assert!(msg.contains("opus, oc"), "{msg}");
4220 }
4221
4222 #[test]
4223 fn an_explicitly_named_agent_that_is_not_installed_is_an_error_not_a_fallback() {
4224 let agents = [
4225 pick_spec("opus", AgentKind::Claude),
4226 pick_spec("oc", AgentKind::Opencode),
4227 ];
4228 let msg = pick(&agents, Some("oc"), &without(&["oc"]))
4229 .expect_err("must not silently substitute another model")
4230 .to_string();
4231 assert!(msg.contains("opencode"), "{msg}");
4232 assert!(msg.contains("--agent"), "{msg}");
4233 }
4234
4235 fn named(id: &str) -> AgentSpec {
4236 AgentSpec {
4237 id: id.to_owned(),
4238 ..spec(AgentKind::Command, None)
4239 }
4240 }
4241
4242 fn output(text: &str, exit: i32, quota: bool) -> AgentOutput {
4243 AgentOutput {
4244 text: text.to_owned(),
4245 exit_code: Some(exit),
4246 timed_out: false,
4247 duration_ms: 0,
4248 artifacts: Vec::new(),
4249 quota: quota.then_some(Quota {
4250 reset: None,
4251 cause: QuotaCause::UsageLimit,
4252 agent: String::new(),
4253 }),
4254 dropped: None,
4255 commands: Vec::new(),
4256 context_tokens: None,
4257 }
4258 }
4259
4260 #[test]
4261 fn a_chain_keeps_the_written_order_and_a_string_is_a_chain_of_one() {
4262 let agents = [named("a"), named("b"), named("c")];
4263 let all = |_: &AgentSpec| true;
4264 let chain = AgentChoice::Chain(vec!["c".into(), "a".into()]);
4265 let got = pick_chain(&agents, Some(&chain), &all, "synthesizer").unwrap();
4266 assert_eq!(
4267 got.iter().map(|s| s.id.as_str()).collect::<Vec<_>>(),
4268 ["c", "a"]
4269 );
4270
4271 let one = AgentChoice::from("b");
4272 let got = pick_chain(&agents, Some(&one), &all, "synthesizer").unwrap();
4273 assert_eq!(got.len(), 1);
4274 assert_eq!(got[0].id, "b");
4275
4276 let got = pick_chain(&agents, None, &all, "synthesizer").unwrap();
4277 assert_eq!(got.len(), 1, "unset keeps pick's default");
4278 assert_eq!(got[0].id, "a");
4279 let empty = AgentChoice::Chain(Vec::new());
4280 assert_eq!(
4281 pick_chain(&agents, Some(&empty), &all, "x").unwrap()[0].id,
4282 "a"
4283 );
4284 }
4285
4286 #[test]
4287 fn a_chain_skips_unknown_and_uninstalled_ids_and_tries_each_once() {
4288 let agents = [named("a"), named("b")];
4289 let not_a = |s: &AgentSpec| s.id != "a";
4290 let chain = AgentChoice::Chain(
4291 ["a", "ghost", "b", "b"]
4292 .iter()
4293 .map(|s| (*s).to_owned())
4294 .collect(),
4295 );
4296 let got = pick_chain(&agents, Some(&chain), ¬_a, "chatter").unwrap();
4297 assert_eq!(got.iter().map(|s| s.id.as_str()).collect::<Vec<_>>(), ["b"]);
4298
4299 let dup = AgentChoice::Chain(vec!["b".into(), "a".into(), "b".into()]);
4300 let got = pick_chain(&agents, Some(&dup), &|_| true, "chatter").unwrap();
4301 assert_eq!(
4302 got.iter().map(|s| s.id.as_str()).collect::<Vec<_>>(),
4303 ["b", "a"]
4304 );
4305 }
4306
4307 #[test]
4308 fn a_chain_with_nothing_runnable_names_the_role() {
4309 let agents = [named("a")];
4310 let chain = AgentChoice::Chain(vec!["a".into(), "ghost".into()]);
4311 let err = pick_chain(&agents, Some(&chain), &|_| false, "conductor")
4312 .unwrap_err()
4313 .to_string();
4314 assert!(err.contains("conductor"), "{err}");
4315 }
4316
4317 #[test]
4318 fn a_chain_advances_on_error_quota_or_an_unusable_answer_only() {
4319 assert!(chain_advances(&Err(anyhow::anyhow!("spawn failed"))));
4320 assert!(chain_advances(&Ok(output("limit", 0, true))));
4321 assert!(chain_advances(&Ok(output("", 0, false))));
4322 assert!(chain_advances(&Ok(output("x", 1, false))));
4323 assert!(!chain_advances(&Ok(output("answer", 0, false))));
4324 }
4325
4326 #[test]
4327 fn claude_context_tokens_are_unknown_because_usage_is_aggregated() {
4328 for out in [
4329 r#"{"result":"ok","num_turns":1,"usage":{"input_tokens":10,"cache_read_input_tokens":3000}}"#,
4330 r#"{"result":"ok","num_turns":3,"usage":{"input_tokens":10}}"#,
4331 r#"{"result":"ok"}"#,
4332 "not json",
4333 ] {
4334 assert_eq!(context_tokens(AgentKind::Claude, out), None, "{out}");
4335 }
4336 }
4337
4338 #[test]
4339 fn opencode_context_tokens_take_the_last_step_finish() {
4340 let out = concat!(
4341 r#"{"type":"step_finish","sessionID":"s","part":{"type":"step-finish","tokens":{"input":100,"output":5,"cache":{"read":1000,"write":50}}}}"#,
4342 "\n",
4343 r#"{"type":"text","part":{"type":"text","text":"hi"}}"#,
4344 "\n",
4345 r#"{"type":"step_finish","sessionID":"s","part":{"type":"step-finish","tokens":{"input":120,"output":9,"cache":{"read":1500}}}}"#,
4346 "\n"
4347 );
4348 assert_eq!(context_tokens(AgentKind::Opencode, out), Some(1620));
4349 let none = r#"{"type":"step_finish","part":{"type":"step-finish"}}"#;
4350 assert_eq!(context_tokens(AgentKind::Opencode, none), None);
4351 assert_eq!(context_tokens(AgentKind::Opencode, ""), None);
4352 }
4353
4354 #[test]
4355 fn agy_context_tokens_are_unknown_because_usage_is_aggregated() {
4356 let out = r#"{"conversation_id":"c","status":"OK","response":"x","usage":{"input_tokens":260113,"cache_read_tokens":2200925}}"#;
4357 assert_eq!(context_tokens(AgentKind::Antigravity, out), None);
4358 }
4359
4360 #[test]
4361 fn codex_context_tokens_are_unknown_because_usage_is_cumulative() {
4362 let out = concat!(
4363 r#"{"type":"turn.completed","usage":{"input_tokens":1000,"cached_input_tokens":900}}"#,
4364 "\n"
4365 );
4366 assert_eq!(context_tokens(AgentKind::Codex, out), None);
4367 }
4368
4369 #[test]
4370 fn omp_context_tokens_come_from_messages_without_an_agent_end() {
4371 let out = concat!(
4372 r#"{"type":"session","id":"s"}"#,
4373 "\n",
4374 r#"{"type":"message_end","message":{"role":"assistant","content":[],"usage":{"input":50,"cacheRead":400,"cacheWrite":10}}}"#,
4375 "\n",
4376 r#"{"type":"turn_end","message":{"role":"assistant","content":[],"usage":{"input":70,"cacheRead":500}}}"#,
4377 "\n"
4378 );
4379 assert_eq!(context_tokens(AgentKind::Omp, out), Some(570));
4380 let user_only = r#"{"type":"message_end","message":{"role":"user","usage":{"input":9}}}"#;
4381 assert_eq!(context_tokens(AgentKind::Omp, user_only), None);
4382 let no_usage = r#"{"type":"message_end","message":{"role":"assistant","content":[]}}"#;
4383 assert_eq!(context_tokens(AgentKind::Omp, no_usage), None);
4384 }
4385
4386 #[test]
4387 fn command_agents_report_no_context_tokens() {
4388 let out = r#"{"usage":{"input_tokens":5}}"#;
4389 assert_eq!(context_tokens(AgentKind::Command, out), None);
4390 }
4391}