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 if matches!(
616 crate::chat_goal::current_source(),
617 crate::chat_goal::Source::Standing(_)
618 ) {
619 cmd.env(crate::chat_control::standing::ENV, "1");
620 }
621 let bridge = if inv.node == crate::queue::CHAT_NODE {
622 crate::run::try_home().and_then(|home| {
623 match Bridge::start(&home, inv.run, inv.artifacts) {
624 Ok(bridge) => Some(bridge),
625 Err(error) => {
626 tracing::warn!(%error, "chat controls unavailable; continuing conversation");
627 None
628 }
629 }
630 })
631 } else {
632 None
633 };
634 if let Some(bridge) = &bridge {
635 cmd.env("MAGI_HOME", std::fs::canonicalize(crate::run::home())?);
639 bridge.attach(&mut cmd);
640 }
641 bridge
642 };
643
644 let mut running = crate::seat_process::Running::spawn(cmd, lease, outputs)
645 .with_context(|| format!("spawn `{}` for seat {}", plan.argv[0], seat.key))?;
646 if let (Some(body), Some(mut sink)) = (plan.stdin.clone(), running.child().stdin.take()) {
650 tokio::spawn(async move {
651 sink.write_all(body.as_bytes()).await.ok();
652 sink.shutdown().await.ok();
653 });
654 }
655
656 let (out_buf, out_reader) = drain(running.child().stdout.take());
673 let (err_buf, err_reader) = drain(running.child().stderr.take());
674
675 let min_free = crate::run::RunState::load_under(inv.run, &crate::run::home())
676 .ok()
677 .map_or(0, |state| state.config.disk.min_free_bytes);
678 #[cfg(all(test, unix))]
679 let min_free = test_watchdog::floor(inv.run, min_free);
680 let mut paths = vec![inv.cwd.to_owned()];
681 if let Some(cache) = inv.cache_dir {
682 paths.push(cache.to_owned());
683 }
684 let mut pressure = None;
685 let waited = tokio::select! {
686 waited = tokio::time::timeout(inv.timeout, running.child().wait()) => Some(waited),
687 reason = crate::retention::emergency(paths, min_free) => {
688 pressure = Some(reason);
689 None
690 }
691 };
692 let (code, timed_out) = match waited {
693 Some(Ok(res)) => {
694 let status = res.with_context(|| format!("wait for seat {}", seat.key))?;
695 (status.code(), false)
696 }
697 Some(Err(_)) | None => {
698 if let Some(reason) = &pressure {
699 tracing::warn!(seat = %seat.key, %reason, "agent execution interrupted");
700 } else {
701 tracing::warn!(seat = %seat.key, secs = inv.timeout.as_secs(), "agent timed out");
702 }
703 if !running.coordinated() {
705 running
706 .child()
707 .kill()
708 .await
709 .context("stop timed-out seat")?;
710 }
711 (None, true)
712 }
713 };
714 running.finish().await;
715
716 let stdout = collect(&out_buf, out_reader, PIPE_GRACE).await;
721 let stderr = collect(&err_buf, err_reader, PIPE_GRACE).await;
722
723 let out_path = inv.artifacts.join(format!("{}.out", inv.stem));
724 let err_path = inv.artifacts.join(format!("{}.err", inv.stem));
725 tokio::fs::write(&out_path, &stdout).await.ok();
726 tokio::fs::write(&err_path, &stderr).await.ok();
727 if let Some(reason) = pressure {
728 return Err(
729 anyhow::Error::new(crate::repo_lock::ResourceBlocked(reason.clone()))
730 .context(ExecutionInterrupted(reason)),
731 );
732 }
733
734 if code != Some(0)
735 && (stdout.contains(crate::incremental::BLOCKED)
736 || stderr.contains(crate::incremental::BLOCKED))
737 {
738 let detail = if stderr.contains(crate::incremental::BLOCKED) {
739 &stderr
740 } else {
741 &stdout
742 };
743 return Err(crate::repo_lock::ResourceBlocked(tail_chars(detail, 2000)).into());
744 }
745
746 let mut extracted = extract(spec.kind, &stdout);
747 if spec.kind == AgentKind::Antigravity && extracted.quota.is_none() {
748 extracted.quota = agy_quota(&stdout, &stderr);
749 }
750 if let Some(quota) = &mut extracted.quota {
751 quota.agent.clone_from(&spec.id);
752 if quota.cause == QuotaCause::Authentication {
753 let _ = crate::notices::Notices::open().raise(crate::notices::Notice::warn(
754 &format!("agent-authentication:{}", spec.id),
755 format!("Agent `{}` cannot authenticate. Re-authenticate this agent, then resume the held task.", spec.id),
756 ));
757 }
758 extracted.dropped = None;
761 tracing::warn!(
762 seat = %seat.key,
763 agent = %spec.id,
764 reset = ?quota.reset,
765 cause = ?quota.cause,
766 "agent needs machine-side recovery"
767 );
768 }
769 if let Some(omp_session) = omp_session {
770 omp_session.record(seat, extracted.session, code == Some(0))?;
771 } else if let Some(session) = extracted.session {
772 match spec.kind {
773 AgentKind::Claude => seat.claude_session = Some(session),
774 AgentKind::Opencode | AgentKind::Antigravity | AgentKind::Codex => {
775 seat.captured_session = Some(session);
776 }
777 AgentKind::Command | AgentKind::Omp => {}
778 }
779 }
780 if let Some(status) = &extracted.status
781 && !status.eq_ignore_ascii_case("success")
782 {
783 tracing::warn!(seat = %seat.key, status = %status, "agent reported a non-success status");
784 }
785 let text = if extracted.text.trim().is_empty() {
786 if stdout.trim().is_empty() {
788 stderr.trim().to_owned()
789 } else {
790 stdout.trim().to_owned()
791 }
792 } else {
793 extracted.text
794 };
795 seat.turns += 1;
796
797 Ok(AgentOutput {
798 text,
799 exit_code: code,
800 timed_out,
801 duration_ms: started.elapsed().as_millis() as u64,
802 artifacts: vec![
803 file_name(&prompt_path),
804 file_name(&out_path),
805 file_name(&err_path),
806 ],
807 quota: extracted.quota,
808 dropped: extracted.dropped,
809 commands: extracted.commands,
810 context_tokens: extracted.context_tokens,
811 })
812}
813
814fn file_name(p: &Path) -> String {
815 p.file_name()
816 .unwrap_or_default()
817 .to_string_lossy()
818 .into_owned()
819}
820
821enum OmpSession {
822 Fresh(PathBuf),
823 Resume,
824}
825
826impl OmpSession {
827 fn prepare(
828 spec: &AgentSpec,
829 seat: &SeatState,
830 sessions: bool,
831 home: impl FnOnce() -> PathBuf,
832 ) -> Result<Self> {
833 let resume = has_session(AgentKind::Omp, seat, sessions);
834 if resume && seat.omp_session_dir.is_none() {
835 return Ok(Self::Resume);
837 }
838 for arg in &spec.extra_args {
839 let flag = arg.split_once('=').map_or(arg.as_str(), |(flag, _)| flag);
840 if matches!(
841 flag,
842 "--session-dir"
843 | "--no-session"
844 | "--resume"
845 | "--session"
846 | "--fork"
847 | "--restore"
848 | "--continue"
849 | "--from-claude"
850 | "--from-codex"
851 | "-r"
852 | "-c"
853 ) {
854 bail!("omp extra_args cannot set {flag} for isolated sessions");
855 }
856 }
857 if resume {
858 let dir = seat.omp_session_dir.as_ref().expect("managed resume");
859 anyhow::ensure!(
860 dir.is_absolute(),
861 "saved omp session directory is not absolute"
862 );
863 std::fs::read_dir(dir)
864 .with_context(|| format!("open saved omp session directory {}", dir.display()))?;
865 return Ok(Self::Resume);
866 }
867
868 let root = std::path::absolute(home().join("agent-sessions").join("omp"))
869 .context("resolve absolute omp session store")?;
870 anyhow::ensure!(
872 root.to_str().is_some(),
873 "omp session store is not valid Unicode"
874 );
875 std::fs::create_dir_all(&root)
876 .with_context(|| format!("create omp session store {}", root.display()))?;
877 let ids =
878 crate::id_reserve::IdSource::new(|| SplitMix64::new(crate::rng::entropy()).uuid_v4());
879 let id = ids.reserve(None, "omp session directory", |id| {
880 crate::id_reserve::create_dir(&root.join(id))
881 })?;
882 Ok(Self::Fresh(root.join(id)))
883 }
884
885 fn dir<'a>(&'a self, seat: &'a SeatState) -> Option<&'a Path> {
886 match self {
887 Self::Fresh(dir) => Some(dir),
888 Self::Resume => seat.omp_session_dir.as_deref(),
889 }
890 }
891
892 fn isolate_terminal_history(&self, cmd: &mut Command, seat: &SeatState) {
893 if self.dir(seat).is_none() {
894 return;
895 }
896 for key in [
900 "ZELLIJ_PANE_ID",
901 "TMUX_PANE",
902 "CMUX_SURFACE_ID",
903 "KITTY_WINDOW_ID",
904 "WEZTERM_PANE",
905 "TERM_SESSION_ID",
906 "WT_SESSION",
907 ] {
908 cmd.env_remove(key);
909 }
910 }
911
912 fn record(self, seat: &mut SeatState, reported: Option<String>, success: bool) -> Result<()> {
913 let reported = reported.filter(|id| !id.is_empty());
914 match self {
915 Self::Resume if seat.omp_session_dir.is_none() => {
916 if let Some(id) = reported {
918 seat.captured_session = Some(id);
919 }
920 }
921 Self::Resume => {
922 if let Some(id) = reported {
923 let previous = seat.captured_session.as_deref().expect("managed resume");
924 let dir = seat.omp_session_dir.as_deref().expect("managed resume");
925 if previous != id {
926 anyhow::ensure!(
927 omp_continues(dir, previous, &id)?,
928 "omp resumed a different session than requested"
929 );
930 seat.captured_session = Some(id);
931 }
932 } else if success {
933 bail!("omp did not confirm the requested session; see the seat output");
936 }
937 }
938 Self::Fresh(dir) => {
939 if let Some(id) = reported {
940 seat.captured_session = Some(id);
941 seat.omp_session_dir = Some(dir);
942 } else if success {
943 bail!("omp did not report a new session id; see the seat output");
944 }
945 }
946 }
947 Ok(())
948 }
949}
950
951fn omp_continues(dir: &Path, previous: &str, reported: &str) -> Result<bool> {
954 use std::io::{BufRead as _, BufReader, Read as _};
955
956 let mut parents = BTreeMap::new();
957 let mut line = Vec::new();
958 for entry in std::fs::read_dir(dir).context("read omp continuation directory")? {
959 let entry = entry?;
960 let path = entry.path();
961 if path.extension() != Some(OsStr::new("jsonl")) || !entry.file_type()?.is_file() {
962 continue;
963 }
964 line.clear();
965 BufReader::new(std::fs::File::open(path)?)
967 .take(64 * 1024)
968 .read_until(b'\n', &mut line)?;
969 if !line.ends_with(b"\n") {
970 continue;
971 }
972 let Ok(header) = serde_json::from_slice::<serde_json::Value>(&line) else {
973 continue;
974 };
975 if header["type"].as_str() != Some("session") {
976 continue;
977 }
978 if let Some(id) = header["id"].as_str() {
979 let parent = header["continuationOf"].as_str().map(str::to_owned);
980 if parents.insert(id.to_owned(), parent).is_some() {
981 return Ok(false);
982 }
983 }
984 }
985
986 let mut current = reported.to_owned();
987 while let Some(Some(parent)) = parents.remove(¤t) {
989 if parent == previous {
990 return Ok(true);
991 }
992 current = parent;
993 }
994 Ok(false)
995}
996
997#[derive(Debug)]
999struct Plan {
1000 argv: Vec<String>,
1001 stdin: Option<String>,
1002}
1003
1004impl Plan {
1005 fn args<'a>(&'a self, omp_dir: Option<&'a Path>) -> impl Iterator<Item = &'a OsStr> {
1007 omp_dir
1008 .into_iter()
1009 .flat_map(|dir| [OsStr::new("--session-dir"), dir.as_os_str()])
1010 .chain(self.argv[1..].iter().map(OsStr::new))
1011 }
1012
1013 fn logged_argv(&self) -> Vec<&str> {
1016 let mut settings_value = false;
1017 self.argv
1018 .iter()
1019 .map(|arg| {
1020 if settings_value {
1021 settings_value = false;
1022 "[redacted]"
1023 } else if arg == "--settings" {
1024 settings_value = true;
1025 arg.as_str()
1026 } else if arg.starts_with("--settings=") {
1027 "--settings=[redacted]"
1028 } else {
1029 arg.as_str()
1030 }
1031 })
1032 .collect()
1033 }
1034}
1035
1036fn pointer(kind: AgentKind, prompt_path: &Path) -> String {
1047 if matches!(kind, AgentKind::Antigravity) {
1048 return format!("@{}", prompt_path.display());
1049 }
1050 format!(
1051 "Read the file at {} and follow every instruction in it exactly. That \
1052 file is your complete task description; this message contains nothing \
1053 else.",
1054 prompt_path.display()
1055 )
1056}
1057
1058fn build_command(
1059 spec: &AgentSpec,
1060 seat: &SeatState,
1061 inv: &Invocation<'_>,
1062 prompt_path: &Path,
1063) -> Result<Plan> {
1064 let mut argv: Vec<String> = Vec::new();
1065 let mut stdin: Option<String> = None;
1066 let delivery = spec.delivery();
1067 let resuming = has_session(spec.kind, seat, inv.sessions);
1068
1069 match spec.kind {
1070 AgentKind::Claude => {
1071 argv.push("claude".to_owned());
1076 argv.push("-p".to_owned());
1077 argv.push("--output-format".to_owned());
1078 argv.push("json".to_owned());
1079 if let Some(m) = &spec.model {
1080 argv.push("--model".to_owned());
1081 argv.push(m.clone());
1082 }
1083 if inv.sessions {
1084 let uuid = seat
1085 .claude_session
1086 .as_deref()
1087 .context("claude seat is missing its session uuid")?;
1088 argv.push(if resuming { "--resume" } else { "--session-id" }.to_owned());
1089 argv.push(uuid.to_owned());
1090 }
1091 argv.push("--permission-mode".to_owned());
1092 argv.push("bypassPermissions".to_owned());
1093 if !inv.allow_write {
1094 argv.push("--disallowed-tools".to_owned());
1095 argv.push("Edit,Write,MultiEdit,NotebookEdit".to_owned());
1096 }
1097 }
1098 AgentKind::Opencode => {
1099 argv.push("opencode".to_owned());
1103 argv.push("run".to_owned());
1104 argv.push("--format".to_owned());
1105 argv.push("json".to_owned());
1106 argv.push("--dir".to_owned());
1107 argv.push(inv.cwd.to_string_lossy().into_owned());
1108 argv.push("--auto".to_owned());
1117 if let Some(m) = &spec.model {
1118 argv.push("-m".to_owned());
1119 argv.push(m.clone());
1120 }
1121 if resuming {
1122 argv.push("-s".to_owned());
1123 argv.push(
1124 seat.captured_session
1125 .clone()
1126 .expect("has_session checked the id is present"),
1127 );
1128 }
1129 }
1130 AgentKind::Antigravity => {
1131 argv.push("agy".to_owned());
1132 argv.push("--output-format".to_owned());
1133 argv.push("json".to_owned());
1134 argv.push("--print-timeout".to_owned());
1137 argv.push(format!("{}s", inv.timeout.as_secs()));
1138 argv.push("--mode".to_owned());
1139 argv.push(
1140 if inv.allow_write {
1141 "accept-edits"
1142 } else {
1143 "plan"
1144 }
1145 .to_owned(),
1146 );
1147 if inv.allow_write {
1148 argv.push("--dangerously-skip-permissions".to_owned());
1149 }
1150 if let Some(m) = &spec.model {
1151 argv.push("--model".to_owned());
1152 argv.push(m.clone());
1153 }
1154 if resuming {
1155 argv.push("--conversation".to_owned());
1156 argv.push(
1157 seat.captured_session
1158 .clone()
1159 .expect("has_session checked the id is present"),
1160 );
1161 }
1162 let mut add_dirs: Vec<String> = Vec::new();
1172 if delivery == Delivery::File || !inv.attachments.is_empty() {
1173 add_dirs.push(inv.artifacts.to_string_lossy().into_owned());
1174 }
1175 for path in inv.attachments {
1176 let Some(parent) = path.parent() else {
1177 continue;
1178 };
1179 if parent.starts_with(inv.artifacts) {
1180 continue;
1181 }
1182 let dir = parent.to_string_lossy().into_owned();
1183 if !add_dirs.contains(&dir) {
1184 add_dirs.push(dir);
1185 }
1186 }
1187 if inv.allow_write {
1188 for path in inv.writable {
1189 let dir = path.to_string_lossy().into_owned();
1190 if !add_dirs.contains(&dir) {
1191 add_dirs.push(dir);
1192 }
1193 }
1194 }
1195 for dir in add_dirs {
1196 argv.push("--add-dir".to_owned());
1197 argv.push(dir);
1198 }
1199 }
1200 AgentKind::Codex => {
1201 argv.push("codex".to_owned());
1207 argv.push("exec".to_owned());
1208 argv.push("--json".to_owned());
1209 argv.push("--skip-git-repo-check".to_owned());
1212 argv.push("-C".to_owned());
1213 argv.push(inv.cwd.to_string_lossy().into_owned());
1214 if repository_writer(inv) {
1224 argv.push("--dangerously-bypass-approvals-and-sandbox".to_owned());
1225 } else {
1226 argv.push("--sandbox".to_owned());
1227 argv.push(
1228 if inv.allow_write {
1229 "workspace-write"
1230 } else {
1231 "read-only"
1232 }
1233 .to_owned(),
1234 );
1235 argv.push("-c".to_owned());
1238 argv.push("approval_policy=\"never\"".to_owned());
1239 if inv.allow_write && !inv.writable.is_empty() {
1240 let roots: Vec<String> = inv
1241 .writable
1242 .iter()
1243 .map(|p| p.to_string_lossy().into_owned())
1244 .collect();
1245 argv.push("-c".to_owned());
1246 argv.push(format!(
1247 "sandbox_workspace_write.writable_roots={}",
1248 serde_json::to_string(&roots).unwrap_or_else(|_| "[]".to_owned())
1249 ));
1250 }
1251 }
1252 if let Some(m) = &spec.model {
1253 argv.push("-m".to_owned());
1254 argv.push(m.clone());
1255 }
1256 if resuming {
1262 argv.push("resume".to_owned());
1263 argv.push(
1264 seat.captured_session
1265 .clone()
1266 .expect("has_session checked the id is present"),
1267 );
1268 }
1269 }
1270 AgentKind::Omp => {
1271 argv.push("omp".to_owned());
1275 argv.push("-p".to_owned());
1276 argv.push("--mode=json".to_owned());
1277 argv.push("--auto-approve".to_owned());
1287 if let Some(m) = &spec.model {
1288 argv.push("--model".to_owned());
1289 argv.push(m.clone());
1290 }
1291 if resuming {
1297 argv.push("--resume".to_owned());
1298 argv.push(
1299 seat.captured_session
1300 .clone()
1301 .expect("has_session checked the id is present"),
1302 );
1303 }
1304 }
1305 AgentKind::Command => {
1306 if spec.command.is_empty() {
1311 bail!("agent `{}` has kind = \"command\" but no command", spec.id);
1312 }
1313 let vars: BTreeMap<&str, String> = BTreeMap::from([
1314 ("{prompt_file}", prompt_path.to_string_lossy().into_owned()),
1315 ("{cwd}", inv.cwd.to_string_lossy().into_owned()),
1316 ("{label}", seat.key.clone()),
1317 ("{session}", seat.claude_session.clone().unwrap_or_default()),
1318 ]);
1319 for raw in &spec.command {
1320 let mut arg = raw.clone();
1321 for (k, v) in &vars {
1322 if arg.contains(k) {
1323 arg = arg.replace(k, v);
1324 }
1325 }
1326 argv.push(arg);
1327 }
1328 }
1329 }
1330
1331 argv.extend(spec.extra_args.iter().cloned());
1332
1333 if spec.kind == AgentKind::Antigravity {
1336 argv.push("-p".to_owned());
1337 }
1338 if spec.kind == AgentKind::Codex && delivery == Delivery::Stdin {
1341 argv.push("-".to_owned());
1342 }
1343 match delivery {
1344 Delivery::Stdin if spec.kind == AgentKind::Antigravity => {
1345 argv.push(pointer(spec.kind, prompt_path));
1347 }
1348 Delivery::Stdin => stdin = Some(inv.prompt.to_owned()),
1349 Delivery::Argv => argv.push(inv.prompt.to_owned()),
1350 Delivery::File => argv.push(pointer(spec.kind, prompt_path)),
1351 }
1352
1353 Ok(Plan { argv, stdin })
1354}
1355
1356#[derive(Debug, Default)]
1358struct Extracted {
1359 text: String,
1360 session: Option<String>,
1361 status: Option<String>,
1362 quota: Option<Quota>,
1363 dropped: Option<Dropped>,
1364 commands: Vec<CommandEvidence>,
1365 context_tokens: Option<u64>,
1366}
1367
1368fn extract(kind: AgentKind, stdout: &str) -> Extracted {
1370 let mut extracted = extract_answer(kind, stdout);
1371 extracted.context_tokens = context_tokens(kind, stdout);
1372 extracted
1373}
1374
1375fn uint(v: &serde_json::Value, key: &str) -> Option<u64> {
1377 v.get(key).and_then(serde_json::Value::as_u64)
1378}
1379
1380fn input_side(usage: &serde_json::Value, input: &[&str], cache: &[&str]) -> Option<u64> {
1385 let first = |keys: &[&str]| keys.iter().find_map(|k| uint(usage, k));
1386 let base = first(input)?;
1387 let cached: u64 = cache.iter().filter_map(|k| uint(usage, k)).sum();
1388 Some(base.saturating_add(cached))
1389}
1390
1391fn context_tokens(kind: AgentKind, stdout: &str) -> Option<u64> {
1412 use serde_json::Value;
1413 let lines = || {
1414 stdout
1415 .lines()
1416 .filter_map(|l| serde_json::from_str::<Value>(l.trim()).ok())
1417 };
1418 match kind {
1419 AgentKind::Claude => None,
1420 AgentKind::Opencode => lines()
1421 .filter(|v| {
1422 v.get("type").and_then(|t| t.as_str()) == Some("step_finish")
1424 || v.get("part")
1425 .and_then(|p| p.get("type"))
1426 .and_then(|t| t.as_str())
1427 == Some("step-finish")
1428 })
1429 .filter_map(|v| {
1430 let tokens = v.get("part")?.get("tokens")?;
1431 let base = uint(tokens, "input")?;
1432 let cache = tokens.get("cache");
1433 let cached = ["read", "write"]
1434 .iter()
1435 .filter_map(|k| cache.and_then(|c| uint(c, k)))
1436 .sum::<u64>();
1437 Some(base.saturating_add(cached))
1438 })
1439 .next_back(),
1440 AgentKind::Antigravity => None,
1441 AgentKind::Codex => None,
1442 AgentKind::Omp => lines()
1443 .flat_map(|v| {
1444 match v.get("type").and_then(|t| t.as_str()) {
1447 Some("agent_end") => v
1448 .get("messages")
1449 .and_then(|m| m.as_array())
1450 .cloned()
1451 .unwrap_or_default(),
1452 Some("turn_end") | Some("message_end") => {
1453 v.get("message").cloned().into_iter().collect()
1454 }
1455 _ => Vec::new(),
1456 }
1457 })
1458 .filter(|m| m.get("role").and_then(|r| r.as_str()) == Some("assistant"))
1459 .filter_map(|m| {
1460 input_side(
1461 m.get("usage")?,
1462 &["input", "input_tokens"],
1463 &[
1464 "cacheRead",
1465 "cacheWrite",
1466 "cache_read_tokens",
1467 "cache_write_tokens",
1468 ],
1469 )
1470 })
1471 .next_back(),
1472 AgentKind::Command => None,
1473 }
1474}
1475
1476pub(crate) fn answer_text(kind: AgentKind, stdout: &str) -> String {
1479 extract_answer(kind, stdout).text
1480}
1481
1482fn extract_answer(kind: AgentKind, stdout: &str) -> Extracted {
1483 match kind {
1484 AgentKind::Claude => {
1485 let Ok(v) = serde_json::from_str::<serde_json::Value>(stdout.trim()) else {
1486 return Extracted {
1487 text: stdout.trim().to_owned(),
1488 ..Extracted::default()
1489 };
1490 };
1491 Extracted {
1492 text: v
1493 .get("result")
1494 .and_then(|r| r.as_str())
1495 .unwrap_or_default()
1496 .to_owned(),
1497 session: v
1498 .get("session_id")
1499 .and_then(|s| s.as_str())
1500 .map(str::to_owned),
1501 status: v.get("is_error").and_then(|e| e.as_bool()).map(|e| {
1502 if e {
1503 "error".to_owned()
1504 } else {
1505 "success".to_owned()
1506 }
1507 }),
1508 quota: claude_quota(&v),
1509 dropped: None,
1512 commands: Vec::new(),
1513 context_tokens: None,
1514 }
1515 }
1516 AgentKind::Opencode => {
1517 let mut text = String::new();
1519 let mut session = None;
1520 for line in stdout.lines() {
1521 let Ok(v) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
1522 continue;
1523 };
1524 if session.is_none() {
1525 session = v
1526 .get("sessionID")
1527 .and_then(|s| s.as_str())
1528 .map(str::to_owned);
1529 }
1530 let part = v.get("part").unwrap_or(&serde_json::Value::Null);
1531 if part.get("type").and_then(|t| t.as_str()) == Some("text")
1532 && let Some(t) = part.get("text").and_then(|t| t.as_str())
1533 {
1534 if !text.is_empty() {
1535 text.push('\n');
1536 }
1537 text.push_str(t);
1538 }
1539 }
1540 Extracted {
1541 text,
1542 session,
1543 status: None,
1544 quota: None,
1545 dropped: None,
1546 commands: Vec::new(),
1547 context_tokens: None,
1548 }
1549 }
1550 AgentKind::Antigravity => {
1551 let obj = stdout
1554 .lines()
1555 .rev()
1556 .find_map(|l| serde_json::from_str::<serde_json::Value>(l.trim()).ok());
1557 let Some(v) = obj else {
1558 return Extracted {
1559 text: stdout.trim().to_owned(),
1560 ..Extracted::default()
1561 };
1562 };
1563 Extracted {
1564 text: v
1565 .get("response")
1566 .and_then(|r| r.as_str())
1567 .unwrap_or_default()
1568 .trim()
1569 .to_owned(),
1570 session: v
1571 .get("conversation_id")
1572 .and_then(|s| s.as_str())
1573 .map(str::to_owned),
1574 status: v.get("status").and_then(|s| s.as_str()).map(str::to_owned),
1575 quota: None,
1576 dropped: dropped_stream(&v),
1577 commands: Vec::new(),
1578 context_tokens: None,
1579 }
1580 }
1581 AgentKind::Codex => {
1582 let mut text = String::new();
1604 let mut session = None;
1605 let mut status = None;
1606 let mut commands = Vec::new();
1607 for line in stdout.lines() {
1608 let Ok(v) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
1609 continue;
1610 };
1611 match v.get("type").and_then(|t| t.as_str()) {
1612 Some("thread.started") => {
1613 session = v
1614 .get("thread_id")
1615 .and_then(|s| s.as_str())
1616 .map(str::to_owned);
1617 }
1618 Some("item.completed") => {
1619 let item = v.get("item").unwrap_or(&serde_json::Value::Null);
1620 match item.get("type").and_then(|t| t.as_str()) {
1621 Some("agent_message") => {
1622 if let Some(t) = item.get("text").and_then(|t| t.as_str()) {
1623 text = t.trim().to_owned();
1624 }
1625 }
1626 Some("command_execution") => {
1627 commands.push(command_evidence(item));
1628 }
1629 _ => {}
1630 }
1631 }
1632 Some("turn.completed") => status = Some("success".to_owned()),
1633 Some("turn.failed") => status = Some("error".to_owned()),
1634 _ => {}
1635 }
1636 }
1637 Extracted {
1638 text,
1639 session,
1640 status,
1641 quota: codex_quota(stdout),
1642 dropped: None,
1643 commands,
1644 context_tokens: None,
1645 }
1646 }
1647 AgentKind::Omp => {
1648 let mut text = String::new();
1669 let mut session = None;
1670 for line in stdout.lines() {
1671 let Ok(v) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
1672 continue;
1673 };
1674 if v.get("type").and_then(|t| t.as_str()) == Some("session") {
1675 session = v.get("id").and_then(|s| s.as_str()).map(str::to_owned);
1676 continue;
1677 }
1678 let messages: Vec<&serde_json::Value> = match v.get("type").and_then(|t| t.as_str())
1682 {
1683 Some("agent_end") => v
1684 .get("messages")
1685 .and_then(|m| m.as_array())
1686 .map(|m| m.iter().collect())
1687 .unwrap_or_default(),
1688 Some("turn_end") | Some("message_end") => {
1689 v.get("message").into_iter().collect()
1690 }
1691 _ => continue,
1692 };
1693 for message in messages {
1694 if message.get("role").and_then(|r| r.as_str()) != Some("assistant") {
1695 continue;
1696 }
1697 let Some(parts) = message.get("content").and_then(|c| c.as_array()) else {
1698 continue;
1699 };
1700 for part in parts {
1701 if part.get("type").and_then(|t| t.as_str()) != Some("text") {
1702 continue;
1703 }
1704 if let Some(t) = part.get("text").and_then(|t| t.as_str())
1705 && !t.trim().is_empty()
1706 {
1707 text = t.trim().to_owned();
1708 }
1709 }
1710 }
1711 }
1712 Extracted {
1713 text,
1714 session,
1715 status: None,
1716 quota: None,
1717 dropped: None,
1718 commands: Vec::new(),
1719 context_tokens: None,
1720 }
1721 }
1722 AgentKind::Command => {
1723 let parsed = serde_json::from_str::<serde_json::Value>(stdout.trim()).ok();
1728 let quota = parsed.as_ref().and_then(claude_quota);
1729 let dropped = parsed.as_ref().and_then(dropped_stream);
1732 Extracted {
1733 text: stdout.trim().to_owned(),
1734 session: None,
1735 status: None,
1736 quota,
1737 dropped,
1738 commands: Vec::new(),
1739 context_tokens: None,
1740 }
1741 }
1742 }
1743}
1744
1745fn command_evidence(item: &serde_json::Value) -> CommandEvidence {
1752 let description = match item.get("command") {
1753 Some(serde_json::Value::String(s)) => s.clone(),
1754 Some(serde_json::Value::Array(parts)) => parts
1755 .iter()
1756 .filter_map(|p| p.as_str())
1757 .collect::<Vec<_>>()
1758 .join(" "),
1759 _ => String::new(),
1760 };
1761 let result_summary = item
1762 .get("aggregated_output")
1763 .and_then(|o| o.as_str())
1764 .map(|s| tail_chars(s.trim(), 400))
1765 .unwrap_or_default();
1766 CommandEvidence {
1767 id: item
1768 .get("id")
1769 .and_then(|s| s.as_str())
1770 .unwrap_or_default()
1771 .to_owned(),
1772 description,
1773 exit_code: item
1774 .get("exit_code")
1775 .and_then(serde_json::Value::as_i64)
1776 .map(|e| e as i32),
1777 result_summary,
1778 source: "codex".to_owned(),
1779 }
1780}
1781
1782fn tail_chars(s: &str, max: usize) -> String {
1784 let count = s.chars().count();
1785 if count <= max {
1786 return s.to_owned();
1787 }
1788 s.chars().skip(count - max).collect()
1789}
1790
1791fn codex_quota(stdout: &str) -> Option<Quota> {
1794 let mut message = None;
1795 let mut failed = false;
1796 for line in stdout.lines() {
1797 let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else {
1798 continue;
1799 };
1800 match v.get("type").and_then(serde_json::Value::as_str) {
1801 Some("error") => {
1802 if let Some(m) = v.get("message").and_then(serde_json::Value::as_str)
1803 && m.starts_with("You've hit your usage limit. Visit https://chatgpt.com/settings/usage to purchase more credits")
1804 {
1805 message = Some(m.to_owned());
1806 }
1807 }
1808 Some("turn.failed") => failed = true,
1809 _ => {}
1810 }
1811 }
1812 if !failed {
1813 return None;
1814 }
1815 let message = message?;
1816 Some(Quota {
1817 reset: message
1818 .split_once("try again at ")
1819 .map(|(_, hint)| hint.trim().trim_end_matches('.').trim().to_owned())
1820 .filter(|hint| !hint.is_empty()),
1821 cause: QuotaCause::UsageLimit,
1822 agent: String::new(),
1823 })
1824}
1825
1826fn claude_quota(v: &serde_json::Value) -> Option<Quota> {
1833 let is_err = v.get("is_error").and_then(|e| e.as_bool()).unwrap_or(false);
1834 if !is_err {
1835 return None;
1836 }
1837 let result = v.get("result").and_then(|r| r.as_str()).unwrap_or("");
1838 if v.get("terminal_reason").and_then(serde_json::Value::as_str) == Some("api_error")
1839 && result.starts_with("Failed to authenticate:")
1840 && result.contains("OAuth session expired and could not be refreshed")
1841 {
1842 return Some(Quota {
1843 reset: None,
1844 cause: QuotaCause::Authentication,
1845 agent: String::new(),
1846 });
1847 }
1848 let status = v.get("api_error_status");
1849 let usage_limit = (status.and_then(serde_json::Value::as_u64) == Some(429)
1850 || status.and_then(serde_json::Value::as_str) == Some("429"))
1851 && v.get("api_error").and_then(serde_json::Value::as_str) == Some("usage_limit_reached");
1852 if !usage_limit && !result.to_lowercase().contains("session limit") {
1853 return None;
1854 }
1855 let reset = result
1858 .split("resets ")
1859 .nth(1)
1860 .map(str::trim)
1861 .filter(|s| !s.is_empty())
1862 .map(str::to_owned);
1863 Some(Quota {
1864 reset,
1865 cause: QuotaCause::UsageLimit,
1866 agent: String::new(),
1867 })
1868}
1869
1870fn agy_quota(stdout: &str, stderr: &str) -> Option<Quota> {
1885 let from_stdout = stdout
1886 .lines()
1887 .rev()
1888 .find_map(|l| serde_json::from_str::<serde_json::Value>(l.trim()).ok())
1889 .and_then(|v| {
1890 let status = v.get("status").and_then(|s| s.as_str()).unwrap_or("");
1891 let error = v.get("error").and_then(|e| e.as_str()).unwrap_or("");
1892 (status.eq_ignore_ascii_case("error") && error.to_lowercase().contains("quota reached"))
1893 .then(|| error.to_owned())
1894 });
1895 let from_stderr = || {
1896 stderr.lines().find_map(|l| {
1897 let v: serde_json::Value =
1898 serde_json::from_str(l.trim().strip_prefix("AGY_ERROR:")?.trim()).ok()?;
1899 let exhausted = v.get("status").and_then(|s| s.as_str()) == Some("RESOURCE_EXHAUSTED");
1900 let code = v.get("error_code").and_then(serde_json::Value::as_u64) == Some(429);
1901 (exhausted && code).then(|| {
1902 v.get("short_error")
1903 .and_then(|e| e.as_str())
1904 .unwrap_or_default()
1905 .to_owned()
1906 })
1907 })
1908 };
1909 let text = from_stdout.or_else(from_stderr)?;
1910 let reset = text
1911 .split_once("Resets ")
1912 .map(|(_, rest)| rest.trim().trim_end_matches('.').trim())
1913 .filter(|s| !s.is_empty())
1914 .map(str::to_owned);
1915 Some(Quota {
1916 reset,
1917 cause: QuotaCause::UsageLimit,
1918 agent: String::new(),
1919 })
1920}
1921
1922fn dropped_stream(v: &serde_json::Value) -> Option<Dropped> {
1953 let status = v.get("status").and_then(|s| s.as_str()).unwrap_or("");
1954 if !status.eq_ignore_ascii_case("error") {
1955 return None;
1956 }
1957 let response = v.get("response").and_then(|r| r.as_str()).unwrap_or("");
1958 if !response.trim().is_empty() {
1959 return None;
1961 }
1962 let produced = v
1963 .get("usage")
1964 .and_then(|u| u.get("output_tokens"))
1965 .and_then(serde_json::Value::as_u64)
1966 .unwrap_or(0);
1967 if produced == 0 {
1968 return None;
1970 }
1971 Some(Dropped {
1972 why: v
1973 .get("error")
1974 .and_then(|e| e.as_str())
1975 .unwrap_or("the CLI ended the stream without delivering its answer")
1976 .trim()
1977 .to_owned(),
1978 output_tokens: produced,
1979 })
1980}
1981
1982pub fn missing_programs(specs: &[AgentSpec]) -> Vec<String> {
1984 let mut missing = Vec::new();
1985 for s in specs {
1986 let program = match s.kind {
1987 AgentKind::Command => s.command.first().map(String::as_str),
1988 other => other.program(),
1989 };
1990 if let Some(p) = program
1991 && !crate::config::which(p)
1992 && !Path::new(p).is_file()
1993 && !missing.iter().any(|m: &String| m == p)
1994 {
1995 missing.push(p.to_owned());
1996 }
1997 }
1998 missing
1999}
2000
2001pub fn artifacts_dir(run_dir: &Path) -> PathBuf {
2003 run_dir.join("artifacts")
2004}
2005
2006pub fn installed(spec: &AgentSpec) -> bool {
2008 spec.kind.program().is_none_or(crate::config::which)
2011}
2012
2013pub fn pick(
2035 agents: &[AgentSpec],
2036 want: Option<&str>,
2037 available: &dyn Fn(&AgentSpec) -> bool,
2038) -> Result<AgentSpec> {
2039 if let Some(id) = want {
2040 let spec = agents
2041 .iter()
2042 .find(|a| a.id == id)
2043 .with_context(|| format!("no agent `{id}` in the roster; it has {}", ids(agents)))?;
2044 if !available(spec) {
2045 bail!(
2046 "agent `{}` needs `{}` on PATH; install it or pass a different \
2047 --agent",
2048 spec.id,
2049 spec.kind.program().unwrap_or("its command")
2050 );
2051 }
2052 return Ok(spec.clone());
2053 }
2054
2055 if agents.is_empty() {
2056 bail!(
2057 "the agent roster is empty, so there is nobody to ask: install one \
2058 of claude, opencode or agy - magi derives a roster from what is on \
2059 PATH - or add an [[agents]] entry to magi.toml."
2060 );
2061 }
2062
2063 if let Some(spec) = agents
2064 .iter()
2065 .find(|a| a.kind == AgentKind::Claude && available(a))
2066 {
2067 return Ok(spec.clone());
2068 }
2069
2070 agents
2071 .iter()
2072 .find(|a| available(a))
2073 .cloned()
2074 .with_context(|| {
2075 let missing = agents
2076 .iter()
2077 .filter_map(|a| a.kind.program())
2078 .collect::<Vec<_>>()
2079 .join(", ");
2080 format!(
2081 "no agent in the roster can be run here: install one of \
2082 {missing}, or add an [[agents]] entry to magi.toml for a CLI \
2083 you do have"
2084 )
2085 })
2086}
2087
2088pub fn for_github_text(spec: &AgentSpec, github_language: &str, cwd: &Path) -> Result<AgentSpec> {
2101 let mut spec = spec.clone();
2102 if spec.kind == AgentKind::Claude {
2103 let mut existing = None;
2106 let mut args = spec.extra_args.iter().enumerate();
2107 while let Some((index, arg)) = args.next() {
2108 if arg == "--settings" {
2109 let (value_index, value) = args.next().context("--settings requires a value")?;
2110 existing = Some((value_index, value.as_str(), false));
2111 } else if let Some(value) = arg.strip_prefix("--settings=") {
2112 existing = Some((index, value, true));
2113 }
2114 }
2115 let mut settings = if let Some((_, value, _)) = existing {
2116 let json = if value.trim_start().starts_with('{') {
2117 value.to_owned()
2118 } else {
2119 std::fs::read_to_string(cwd.join(value))
2120 .context("cannot read existing seat --settings file")?
2121 };
2122 serde_json::from_str::<serde_json::Value>(&json)
2123 .context("cannot parse existing seat --settings JSON")?
2124 } else {
2125 serde_json::json!({})
2126 };
2127 settings
2128 .as_object_mut()
2129 .context("seat --settings must be a JSON object")?
2130 .insert(
2131 "language".to_owned(),
2132 serde_json::json!(crate::lang::name(github_language)),
2133 );
2134 let settings = settings.to_string();
2135 if let Some((index, _, equals)) = existing {
2136 spec.extra_args[index] = if equals {
2137 format!("--settings={settings}")
2138 } else {
2139 settings
2140 };
2141 } else {
2142 spec.extra_args.extend(["--settings".to_owned(), settings]);
2143 }
2144 }
2145 Ok(spec)
2146}
2147
2148pub fn pick_chain(
2156 agents: &[AgentSpec],
2157 choice: Option<&AgentChoice>,
2158 available: &dyn Fn(&AgentSpec) -> bool,
2159 role: &str,
2160) -> Result<Vec<AgentSpec>> {
2161 let wanted = choice.map(AgentChoice::ids).unwrap_or_default();
2162 if wanted.is_empty() {
2163 return pick(agents, None, available)
2164 .map(|s| vec![s])
2165 .with_context(|| format!("choose an agent for the {role} role"));
2166 }
2167 let mut chain: Vec<AgentSpec> = Vec::new();
2168 for id in wanted {
2169 if chain.iter().any(|s| s.id == id) {
2170 continue;
2171 }
2172 match pick(agents, Some(id), available) {
2173 Ok(spec) => chain.push(spec),
2174 Err(e) => tracing::warn!("[roles] {role}: skipping `{id}`: {e:#}"),
2175 }
2176 }
2177 if chain.is_empty() {
2178 bail!(
2179 "[roles] {role} names no agent that can run here; the roster has {}",
2180 ids(agents)
2181 );
2182 }
2183 Ok(chain)
2184}
2185
2186pub fn chain_advances(outcome: &Result<AgentOutput>) -> bool {
2192 match outcome {
2193 Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => false,
2194 Err(_) => true,
2195 Ok(out) => output_advances(out),
2196 }
2197}
2198
2199pub fn output_advances(out: &AgentOutput) -> bool {
2203 out.quota_exhausted() || !out.usable()
2204}
2205
2206fn ids(agents: &[AgentSpec]) -> String {
2207 if agents.is_empty() {
2208 return "no agents at all".to_owned();
2209 }
2210 agents
2211 .iter()
2212 .map(|a| a.id.clone())
2213 .collect::<Vec<_>>()
2214 .join(", ")
2215}
2216
2217#[cfg(all(test, unix))]
2220pub(crate) mod test_watchdog {
2221 use super::*;
2222 static FLOORS: Mutex<BTreeMap<String, u64>> = Mutex::new(BTreeMap::new());
2223
2224 pub(crate) struct Guard(String);
2225
2226 pub(crate) fn set(run: &str, floor: u64) -> Guard {
2227 assert!(
2228 FLOORS
2229 .lock()
2230 .unwrap()
2231 .insert(run.to_owned(), floor)
2232 .is_none()
2233 );
2234 Guard(run.to_owned())
2235 }
2236
2237 pub(super) fn floor(run: &str, configured: u64) -> u64 {
2238 FLOORS
2239 .lock()
2240 .unwrap()
2241 .get(run)
2242 .copied()
2243 .unwrap_or(configured)
2244 }
2245
2246 impl Drop for Guard {
2247 fn drop(&mut self) {
2248 FLOORS.lock().unwrap().remove(&self.0);
2249 }
2250 }
2251}
2252
2253#[cfg(test)]
2254mod tests {
2255 use super::*;
2256
2257 const COMMAND_HELPER_MODE: &str = "MAGI_TEST_COMMAND_HELPER_MODE";
2258
2259 fn command_helper(mode: &str) -> AgentSpec {
2262 crate::run::pin_test_home();
2264 AgentSpec {
2265 id: "helper".to_owned(),
2266 kind: AgentKind::Command,
2267 model: None,
2268 command: vec![
2269 std::env::current_exe()
2270 .expect("locate test helper")
2271 .to_string_lossy()
2272 .into_owned(),
2273 "--exact".to_owned(),
2274 "agent::tests::command_agent_test_helper".to_owned(),
2275 "--nocapture".to_owned(),
2276 ],
2277 extra_args: Vec::new(),
2278 env: BTreeMap::from([(COMMAND_HELPER_MODE.to_owned(), mode.to_owned())]),
2279 prompt_delivery: None,
2280 max_turn_secs: None,
2281 }
2282 }
2283
2284 #[test]
2285 fn command_agent_test_helper() {
2286 match std::env::var(COMMAND_HELPER_MODE).as_deref() {
2287 Ok("reply") => println!("hello {}", std::env::var("MAGI_SEAT").unwrap()),
2288 Ok("cache") => println!("{}", std::env::var("CARGO_TARGET_DIR").unwrap()),
2289 Ok("no-cache") => println!(
2290 "{}",
2291 std::env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| "ABSENT".to_owned())
2292 ),
2293 Ok("ignore-stdin") => println!("done"),
2294 Ok("chatty-sleep") => {
2295 println!("i-said-something");
2296 std::thread::sleep(Duration::from_secs(30));
2297 }
2298 Ok("sleep") => std::thread::sleep(Duration::from_secs(30)),
2299 Ok(other) => panic!("unknown command helper mode {other}"),
2300 Err(_) => {}
2301 }
2302 }
2303
2304 fn spec(kind: AgentKind, model: Option<&str>) -> AgentSpec {
2305 AgentSpec {
2306 id: "a".to_owned(),
2307 kind,
2308 model: model.map(str::to_owned),
2309 command: vec!["echo".to_owned(), "{label}".to_owned()],
2310 extra_args: Vec::new(),
2311 env: BTreeMap::new(),
2312 prompt_delivery: None,
2313 max_turn_secs: None,
2314 }
2315 }
2316
2317 fn inv<'a>(cwd: &'a Path, art: &'a Path, allow_write: bool) -> Invocation<'a> {
2318 Invocation {
2319 coordination: None,
2320 fetched_base: None,
2321 cwd,
2322 prompt: "do the thing",
2323 timeout: Duration::from_secs(900),
2324 allow_write,
2325 sessions: true,
2326 artifacts: art,
2327 stem: "t",
2328 run: "test-run",
2329 node: "test",
2330 cache_dir: None,
2331 attachments: &[],
2332 writable: &[],
2333 }
2334 }
2335
2336 fn plan_for(kind: AgentKind, seat: &SeatState, allow_write: bool) -> Plan {
2337 build_command(
2338 &spec(kind, None),
2339 seat,
2340 &inv(Path::new("."), Path::new("/art"), allow_write),
2341 Path::new("/art/p.md"),
2342 )
2343 .unwrap()
2344 }
2345
2346 #[test]
2347 fn editing_access_requires_fetch_evidence_and_keeps_snapshot() {
2348 let missing = editing_access_note(None);
2349 assert!(missing.contains("No successful launcher fetch evidence"));
2350 let base = crate::run::FetchedBase {
2351 remote: "origin".into(),
2352 branch: "main".into(),
2353 commit: "0123456789abcdef".into(),
2354 fetched_at: "2026-10-18T00:00:00Z".parse().unwrap(),
2355 };
2356 let note = editing_access_note(Some(&base));
2357 for expected in [
2358 "origin/main",
2359 "0123456789abcdef",
2360 "2026-10-18T00:00:00Z",
2361 "Do not fetch again",
2362 ] {
2363 assert!(note.contains(expected), "missing {expected}");
2364 }
2365 for text in [&missing, ¬e] {
2368 assert!(!text.to_lowercase().contains("sandbox"), "{text}");
2369 assert!(!text.contains("Network access is restricted"), "{text}");
2370 }
2371 let roundtrip: crate::run::FetchedBase =
2372 serde_json::from_str(&serde_json::to_string(&base).unwrap()).unwrap();
2373 assert_eq!(editing_access_note(Some(&roundtrip)), note);
2374 }
2375
2376 #[test]
2377 fn codex_editing_seats_bypass_the_sandbox_on_initial_and_resume() {
2378 const BYPASS: &str = "--dangerously-bypass-approvals-and-sandbox";
2379 let roots = [PathBuf::from("/shared/git"), PathBuf::from("/questions")];
2380 for resumed in [false, true] {
2381 let mut seat = SeatState::new("impl-A", "a", 7);
2382 if resumed {
2383 seat.turns = 1;
2384 seat.captured_session = Some("fixture-thread".into());
2385 }
2386 let build = |invocation: &Invocation<'_>| {
2387 build_command(
2388 &spec(AgentKind::Codex, None),
2389 &seat,
2390 invocation,
2391 Path::new("/art/p.md"),
2392 )
2393 .unwrap()
2394 };
2395 for node in [
2396 "implement",
2397 "fix",
2398 "graft",
2399 "gate-fix",
2400 "land",
2401 "rebase",
2402 "base-conflict",
2403 crate::queue::CHAT_NODE,
2404 "external-chat",
2405 ] {
2406 let mut invocation = inv(Path::new("."), Path::new("/art"), true);
2407 invocation.node = node;
2408 invocation.writable = &roots;
2409 let plan = build(&invocation);
2410 let at = plan.argv.iter().position(|s| s == BYPASS);
2411 assert!(at.is_some(), "{node}: {:?}", plan.argv);
2412 if resumed {
2413 let resume = plan.argv.iter().position(|s| s == "resume").unwrap();
2414 assert!(at.unwrap() < resume, "{node}: {:?}", plan.argv);
2415 }
2416 assert!(!plan.argv.iter().any(|s| s == "--sandbox"), "{node}");
2418 assert!(!plan.argv.iter().any(|s| s == "-c"), "{node}");
2419 }
2420 for (node, write) in [
2421 ("review", false),
2422 ("judge", false),
2423 ("advise", false),
2424 ("implement", false),
2425 ("fix", false),
2426 ("dupes", false),
2427 ("conduct", false),
2428 ("waiter", false),
2429 ("talk-title", false),
2430 (crate::queue::CHAT_NODE, false),
2431 ("external-chat", false),
2432 ("deputy", true),
2433 ] {
2434 let mut invocation = inv(Path::new("."), Path::new("/art"), write);
2435 invocation.node = node;
2436 let plan = build(&invocation);
2437 assert!(!plan.argv.iter().any(|s| s == BYPASS), "{node}");
2438 let mode = if write {
2439 "workspace-write"
2440 } else {
2441 "read-only"
2442 };
2443 assert!(
2444 plan.argv.windows(2).any(|w| w == ["--sandbox", mode]),
2445 "{node}: {:?}",
2446 plan.argv
2447 );
2448 assert!(
2449 plan.argv
2450 .windows(2)
2451 .any(|w| w == ["-c", "approval_policy=\"never\""]),
2452 "{node}"
2453 );
2454 }
2455 }
2456 }
2457
2458 #[test]
2459 fn claude_mints_then_resumes_the_same_uuid() {
2460 let mut seat = SeatState::new("judge-1", "a", 7);
2461 let uuid = seat.claude_session.clone().unwrap();
2462 let first = plan_for(AgentKind::Claude, &seat, true);
2463 assert!(first.argv.windows(2).any(|w| w == ["--session-id", &uuid]));
2464 assert!(!first.argv.iter().any(|a| a == "--resume"));
2465
2466 seat.turns = 1;
2467 let second = plan_for(AgentKind::Claude, &seat, true);
2468 assert!(second.argv.windows(2).any(|w| w == ["--resume", &uuid]));
2469 assert!(!second.argv.iter().any(|a| a == "--session-id"));
2470 }
2471
2472 #[test]
2473 fn github_bound_claude_seats_override_the_operators_answer_language() {
2474 let seat = SeatState::new("change-summary", "a", 7);
2475 let art = Path::new("/art");
2476 for (language, name) in [("en", "English"), ("", "English"), ("ja", "Japanese")] {
2477 let claude =
2478 for_github_text(&spec(AgentKind::Claude, None), language, Path::new(".")).unwrap();
2479 let plan = build_command(
2480 &claude,
2481 &seat,
2482 &inv(Path::new("."), art, false),
2483 Path::new("/art/p.md"),
2484 )
2485 .unwrap();
2486 let settings = format!(r#"{{"language":"{name}"}}"#);
2487 assert!(
2488 plan.argv
2489 .windows(2)
2490 .any(|w| w == ["--settings", settings.as_str()]),
2491 "{:?}",
2492 plan.argv
2493 );
2494 assert_eq!(plan.stdin.as_deref(), Some("do the thing"));
2497 }
2498 for kind in [
2499 AgentKind::Codex,
2500 AgentKind::Opencode,
2501 AgentKind::Antigravity,
2502 AgentKind::Omp,
2503 ] {
2504 assert!(
2505 for_github_text(&spec(kind, None), "en", Path::new("."))
2506 .unwrap()
2507 .extra_args
2508 .is_empty()
2509 );
2510 }
2511 }
2512
2513 #[test]
2514 fn github_text_preserves_existing_settings() {
2515 let dir = tempfile::tempdir().unwrap();
2516 let original = serde_json::json!({
2517 "language": "Japanese",
2518 "env": { "SEAT_MODE": "configured" },
2519 "apiKeyHelper": "credential-helper",
2520 "hooks": { "Stop": [] }
2521 });
2522 std::fs::write(dir.path().join("seat-settings.json"), original.to_string()).unwrap();
2523 for value in [original.to_string(), "./seat-settings.json".to_owned()] {
2524 for equals in [false, true] {
2525 let mut spec = spec(AgentKind::Claude, None);
2526 spec.extra_args = vec!["--settings={\"language\":\"French\"}".to_owned()];
2528 if equals {
2529 spec.extra_args.push(format!("--settings={value}"));
2530 } else {
2531 spec.extra_args
2532 .extend(["--settings".to_owned(), value.clone()]);
2533 }
2534 spec.extra_args.push("--verbose".to_owned());
2535 let updated = for_github_text(&spec, "en", dir.path()).unwrap();
2536 assert_eq!(updated.extra_args.len(), spec.extra_args.len());
2537 assert_eq!(updated.extra_args[0], spec.extra_args[0]);
2538 assert_eq!(updated.extra_args.last(), spec.extra_args.last());
2539 let value = &updated.extra_args[updated.extra_args.len() - 2];
2540 let actual: serde_json::Value =
2541 serde_json::from_str(value.strip_prefix("--settings=").unwrap_or(value))
2542 .unwrap();
2543 let mut expected = original.clone();
2544 expected["language"] = serde_json::json!("English");
2545 assert_eq!(actual, expected);
2546 }
2547 }
2548 let on_disk: serde_json::Value = serde_json::from_str(
2549 &std::fs::read_to_string(dir.path().join("seat-settings.json")).unwrap(),
2550 )
2551 .unwrap();
2552 assert_eq!(on_disk, original);
2553 }
2554
2555 #[test]
2556 fn github_text_settings_are_redacted_from_command_logging() {
2557 let dir = tempfile::tempdir().unwrap();
2558 let settings = serde_json::json!({ "env": { "AUTH_TOKEN": "test-only-secret" } });
2559 std::fs::write(dir.path().join("seat-settings.json"), settings.to_string()).unwrap();
2560 for equals in [false, true] {
2561 let mut spec = spec(AgentKind::Claude, None);
2562 spec.extra_args =
2563 vec!["--settings={\"env\":{\"AUTH_TOKEN\":\"earlier-secret\"}}".to_owned()];
2564 if equals {
2565 spec.extra_args
2566 .push("--settings=./seat-settings.json".to_owned());
2567 } else {
2568 spec.extra_args
2569 .extend(["--settings".to_owned(), "./seat-settings.json".to_owned()]);
2570 }
2571 let spec = for_github_text(&spec, "en", dir.path()).unwrap();
2572 let plan = build_command(
2573 &spec,
2574 &SeatState::new("change-summary", "a", 7),
2575 &inv(dir.path(), dir.path(), false),
2576 &dir.path().join("prompt.md"),
2577 )
2578 .unwrap();
2579 let actual = plan.argv.last().unwrap();
2581 let actual: serde_json::Value =
2582 serde_json::from_str(actual.strip_prefix("--settings=").unwrap_or(actual)).unwrap();
2583 assert_eq!(actual["env"]["AUTH_TOKEN"], "test-only-secret");
2584 assert_eq!(actual["language"], "English");
2585 let logged = format!("{:?}", plan.logged_argv());
2586 assert!(!logged.contains("secret"));
2587 assert!(!logged.contains("AUTH_TOKEN"));
2588 assert!(logged.contains("[redacted]"));
2589 assert_eq!(plan.logged_argv()[0], "claude");
2590 assert!(plan.logged_argv().contains(&"--output-format"));
2591 }
2592 }
2593
2594 #[test]
2595 fn github_text_rejects_unreadable_or_invalid_settings() {
2596 let dir = tempfile::tempdir().unwrap();
2597 std::fs::write(dir.path().join("bad.json"), "invalid json").unwrap();
2598 std::fs::write(dir.path().join("array.json"), "[]").unwrap();
2599 for args in [
2600 vec!["--settings"],
2601 vec!["--settings", "missing.json"],
2602 vec!["--settings=bad.json"],
2603 vec!["--settings", "array.json"],
2604 ] {
2605 let mut spec = spec(AgentKind::Claude, None);
2606 spec.extra_args = args.into_iter().map(str::to_owned).collect();
2607 assert!(for_github_text(&spec, "en", dir.path()).is_err());
2608 }
2609 }
2610
2611 #[test]
2612 fn read_only_seats_cannot_edit() {
2613 let seat = SeatState::new("judge-1", "a", 7);
2614 let claude = plan_for(AgentKind::Claude, &seat, false);
2615 assert!(claude.argv.iter().any(|a| a == "--disallowed-tools"));
2616 assert!(
2617 !plan_for(AgentKind::Claude, &seat, true)
2618 .argv
2619 .iter()
2620 .any(|a| a == "--disallowed-tools")
2621 );
2622
2623 let agy = plan_for(AgentKind::Antigravity, &seat, false);
2624 assert!(agy.argv.windows(2).any(|w| w == ["--mode", "plan"]));
2625 assert!(
2626 !agy.argv
2627 .iter()
2628 .any(|a| a == "--dangerously-skip-permissions")
2629 );
2630 let agy_rw = plan_for(AgentKind::Antigravity, &seat, true);
2631 assert!(
2632 agy_rw
2633 .argv
2634 .windows(2)
2635 .any(|w| w == ["--mode", "accept-edits"])
2636 );
2637 assert!(
2638 agy_rw
2639 .argv
2640 .iter()
2641 .any(|a| a == "--dangerously-skip-permissions")
2642 );
2643 let agy_prompt = agy_rw
2648 .argv
2649 .iter()
2650 .position(|a| a == "-p")
2651 .map(|i| agy_rw.argv[i + 1].clone())
2652 .expect("agy takes its prompt with -p");
2653 assert!(
2654 agy_prompt.starts_with('@'),
2655 "agy must get a file reference, got {agy_prompt:?}"
2656 );
2657 assert!(
2658 !agy_prompt.contains("Read the file at"),
2659 "the prose pointer is for CLIs with no file syntax"
2660 );
2661
2662 for allow_write in [false, true] {
2667 assert!(
2668 plan_for(AgentKind::Opencode, &seat, allow_write)
2669 .argv
2670 .iter()
2671 .any(|a| a == "--auto"),
2672 "opencode needs --auto even to read (allow_write = {allow_write})"
2673 );
2674 }
2675 }
2676
2677 #[test]
2680 fn codex_gets_extra_writable_roots_only_when_it_may_write() {
2681 let seat = SeatState::new("deputy-x", "a", 7);
2682 let roots = [PathBuf::from("/data/questions")];
2683 let mk = |allow_write: bool| {
2684 let mut i = inv(Path::new("."), Path::new("/art"), allow_write);
2685 i.writable = &roots;
2686 build_command(
2687 &spec(AgentKind::Codex, None),
2688 &seat,
2689 &i,
2690 Path::new("/art/p.md"),
2691 )
2692 .unwrap()
2693 };
2694 let want = "sandbox_workspace_write.writable_roots=[\"/data/questions\"]";
2695 assert!(mk(true).argv.windows(2).any(|w| w == ["-c", want]));
2696 assert!(!mk(false).argv.iter().any(|a| a.contains("writable_roots")));
2697 }
2698
2699 #[test]
2700 fn repository_write_scope_covers_editing_nodes_without_changing_other_roles() {
2701 let mut i = inv(Path::new("."), Path::new("/art"), true);
2702 for node in [
2703 "implement",
2704 "fix",
2705 "graft",
2706 "gate-fix",
2707 "land",
2708 "rebase",
2709 "base-conflict",
2710 "chat",
2711 "external-chat",
2712 ] {
2713 i.node = node;
2714 assert!(repository_writer(&i), "{node}");
2715 i.allow_write = false;
2716 assert!(!repository_writer(&i), "{node}");
2717 i.allow_write = true;
2718 }
2719 for node in ["deputy", "judge", "review", "bump", "conduct", "talk-title"] {
2720 i.node = node;
2721 assert!(!repository_writer(&i), "{node}");
2722 }
2723 i.node = "chat";
2724 let roots = [PathBuf::from("/questions")];
2725 i.writable = &roots;
2726 assert!(
2727 repository_writer(&i),
2728 "explicit roots do not change the role"
2729 );
2730 assert!(
2731 !repository_seat(&i),
2732 "chat turns bypass repository scheduling"
2733 );
2734 }
2735
2736 #[test]
2737 fn coordination_classification_is_independent_of_write_grants() {
2738 let roots = [PathBuf::from("/questions")];
2739 for node in [
2740 crate::queue::CHAT_NODE,
2741 "external-chat",
2742 "implement",
2743 "fix",
2744 "graft",
2745 "gate-fix",
2746 "land",
2747 "rebase",
2748 "base-conflict",
2749 "review",
2750 "judge",
2751 "advise",
2752 "deputy",
2753 "waiter",
2754 "conduct",
2755 "dupes",
2756 "talk-title",
2757 ] {
2758 for allow_write in [false, true] {
2759 for writable in [&[][..], &roots[..]] {
2760 let mut i = inv(Path::new("."), Path::new("/art"), allow_write);
2761 i.node = node;
2762 i.writable = writable;
2763 assert_eq!(
2764 repository_seat(&i),
2765 !matches!(
2766 node,
2767 crate::queue::CHAT_NODE
2768 | "external-chat"
2769 | "talk-title"
2770 | "deputy"
2771 | "conduct"
2772 | "dupes"
2773 ),
2774 "{node}, allow_write={allow_write}, writable={writable:?}"
2775 );
2776 if matches!(node, crate::queue::CHAT_NODE | "external-chat") {
2777 assert_eq!(repository_writer(&i), allow_write);
2778 }
2779 }
2780 }
2781 }
2782 }
2783
2784 #[test]
2785 fn writable_directories_reach_initial_and_resumed_adapter_commands() {
2786 let roots = [
2787 PathBuf::from("/shared/git"),
2788 PathBuf::from("/state/questions"),
2789 ];
2790 for kind in [AgentKind::Codex, AgentKind::Antigravity] {
2791 for resumed in [false, true] {
2792 let mut seat = SeatState::new("impl-A", "a", 7);
2793 if resumed {
2794 seat.turns = 1;
2795 seat.captured_session = Some("session-id".into());
2796 }
2797 for allow_write in [false, true] {
2798 let mut i = inv(Path::new("."), Path::new("/art"), allow_write);
2799 i.writable = &roots;
2800 let plan = build_command(&spec(kind, None), &seat, &i, Path::new("/art/p.md"))
2801 .unwrap();
2802 for root in &roots {
2803 if kind == AgentKind::Antigravity {
2804 assert_eq!(
2805 plan.argv.windows(2).any(|w| {
2806 w[0] == "--add-dir" && w[1] == root.to_str().unwrap()
2807 }),
2808 allow_write,
2809 "resumed={resumed}: {:?}",
2810 plan.argv
2811 );
2812 }
2813 assert_eq!(
2814 plan.argv
2815 .iter()
2816 .any(|arg| arg.contains(root.to_str().unwrap())),
2817 allow_write,
2818 "{kind:?}, resumed={resumed}: {:?}",
2819 plan.argv
2820 );
2821 }
2822 if kind == AgentKind::Codex && resumed {
2823 let at = plan.argv.iter().position(|s| s == "resume").unwrap();
2824 assert!(!plan.argv[at..].iter().any(|s| s == "-c"));
2825 }
2826 }
2827 }
2828 }
2829 }
2830
2831 #[test]
2832 fn codex_is_sandboxed_reads_stdin_and_puts_resume_last() {
2833 let mut seat = SeatState::new("judge-1", "a", 7);
2834
2835 let ro = plan_for(AgentKind::Codex, &seat, false);
2841 assert!(ro.argv.windows(2).any(|w| w == ["--sandbox", "read-only"]));
2842 let rw = plan_for(AgentKind::Codex, &seat, true);
2843 assert!(
2844 rw.argv
2845 .windows(2)
2846 .any(|w| w == ["--sandbox", "workspace-write"])
2847 );
2848 for p in [&ro, &rw] {
2849 assert!(
2850 !p.argv
2851 .iter()
2852 .any(|a| a == "--dangerously-bypass-approvals-and-sandbox"),
2853 "the bypass defeats the only enforced read-only mode we have"
2854 );
2855 assert!(
2857 p.argv
2858 .windows(2)
2859 .any(|w| w == ["-c", "approval_policy=\"never\""]),
2860 "an unattended seat that asks for approval blocks until timeout"
2861 );
2862 }
2863
2864 assert_eq!(ro.stdin.as_deref(), Some("do the thing"));
2866 assert_eq!(
2867 ro.argv.last().map(String::as_str),
2868 Some("-"),
2869 "without the `-` argument codex waits for a prompt it never gets"
2870 );
2871
2872 seat.turns = 1;
2876 assert!(!has_session(AgentKind::Codex, &seat, true));
2877 assert!(
2878 !plan_for(AgentKind::Codex, &seat, true)
2879 .argv
2880 .iter()
2881 .any(|a| a == "resume")
2882 );
2883 seat.captured_session = Some("01a07440-4545-7492-85c1-024e3259a90a".to_owned());
2884 let resumed = plan_for(AgentKind::Codex, &seat, true);
2885 let at = resumed
2886 .argv
2887 .iter()
2888 .position(|a| a == "resume")
2889 .expect("resumes by subcommand");
2890 assert_eq!(resumed.argv[at + 1], "01a07440-4545-7492-85c1-024e3259a90a");
2891 assert!(
2892 resumed.argv[..at].iter().any(|a| a == "--sandbox"),
2893 "every option precedes the subcommand"
2894 );
2895 assert_eq!(resumed.argv.last().map(String::as_str), Some("-"));
2896 }
2897
2898 #[test]
2901 fn omp_reads_stdin_auto_approves_and_resumes_by_id() {
2902 let mut seat = SeatState::new("review-1", "a", 7);
2903
2904 let first = plan_for(AgentKind::Omp, &seat, false);
2908 assert!(first.argv.iter().any(|a| a == "-p"));
2909 assert!(first.argv.iter().any(|a| a == "--mode=json"));
2910 assert_eq!(first.stdin.as_deref(), Some("do the thing"));
2911 assert!(
2912 !first.argv.iter().any(|a| a == "do the thing"),
2913 "the prompt reached argv, where Windows caps it"
2914 );
2915
2916 for allow_write in [false, true] {
2922 let p = plan_for(AgentKind::Omp, &seat, allow_write);
2923 assert!(
2924 p.argv.iter().any(|a| a == "--auto-approve"),
2925 "omp needs --auto-approve even to read (allow_write = {allow_write})"
2926 );
2927 assert!(
2928 !p.argv
2929 .iter()
2930 .any(|a| a == "--dangerously-bypass-approvals-and-sandbox"),
2931 "nothing ever asks for the bypass"
2932 );
2933 }
2934
2935 seat.turns = 1;
2938 assert!(!has_session(AgentKind::Omp, &seat, true));
2939 assert!(
2940 !plan_for(AgentKind::Omp, &seat, true)
2941 .argv
2942 .iter()
2943 .any(|a| a == "--resume")
2944 );
2945 seat.captured_session = Some("01a09fe9-4e31-7226-85b3-fda6f46689d5".to_owned());
2946 let resumed = plan_for(AgentKind::Omp, &seat, true);
2947 assert!(
2948 resumed
2949 .argv
2950 .windows(2)
2951 .any(|w| w == ["--resume", "01a09fe9-4e31-7226-85b3-fda6f46689d5"]),
2952 "a captured id is what makes the next turn a resume"
2953 );
2954 assert!(!resumed.argv.iter().any(|a| a == "--continue"));
2957 assert_eq!(resumed.stdin.as_deref(), Some("do the thing"));
2959 }
2960
2961 #[test]
2962 fn omp_terminal_breadcrumbs_are_disabled_only_for_managed_sessions() {
2963 let mut seat = SeatState::new("review-1", "a", 7);
2964 let mut cmd = Command::new("omp");
2965 cmd.envs([
2966 ("ZELLIJ_PANE_ID", "1"),
2967 ("TMUX_PANE", "%2"),
2968 ("CMUX_SURFACE_ID", "terminal"),
2969 ("KITTY_WINDOW_ID", "3"),
2970 ("WEZTERM_PANE", "4"),
2971 ("TERM_SESSION_ID", "terminal"),
2972 ("WT_SESSION", "terminal"),
2973 ("OMP_PROFILE", "work"),
2974 ]);
2975 let envs = |cmd: &Command| {
2976 cmd.as_std()
2977 .get_envs()
2978 .filter(|(_, value)| value.is_some())
2979 .count()
2980 };
2981 OmpSession::Resume.isolate_terminal_history(&mut cmd, &seat);
2982 assert_eq!(envs(&cmd), 8);
2983 OmpSession::Fresh(PathBuf::from("managed")).isolate_terminal_history(&mut cmd, &seat);
2984 assert_eq!(envs(&cmd), 1);
2985 assert!(
2986 cmd.as_std()
2987 .get_envs()
2988 .any(|(key, value)| { key == "OMP_PROFILE" && value == Some(OsStr::new("work")) })
2989 );
2990
2991 seat.omp_session_dir = Some(PathBuf::from("managed"));
2992 cmd.env("WT_SESSION", "terminal");
2993 OmpSession::Resume.isolate_terminal_history(&mut cmd, &seat);
2994 assert_eq!(envs(&cmd), 1);
2995 }
2996
2997 #[test]
2998 fn omp_managed_session_persists_native_path_and_reuses_it_after_reload() {
2999 let tmp = tempfile::tempdir().unwrap();
3000 let home = tmp.path().join("magi home 日本語");
3001 let spec = spec(AgentKind::Omp, None);
3002 let mut seat = SeatState::new("review-1", "a", 7);
3003 let art = tmp.path().join("art");
3004 let cwd = tmp.path().join("other checkout");
3005 let mut invocation = inv(&cwd, &art, false);
3006 let prompt = art.join("p.md");
3007
3008 let fresh = OmpSession::prepare(&spec, &seat, true, || home.clone()).unwrap();
3009 let dir = fresh.dir(&seat).unwrap().to_owned();
3010 assert_eq!(dir.parent().unwrap(), home.join("agent-sessions/omp"));
3011 assert!(dir.is_absolute() && dir.is_dir());
3012 assert!(
3013 !dir.file_name()
3014 .unwrap()
3015 .to_str()
3016 .unwrap()
3017 .contains(&seat.key)
3018 );
3019 let plan = build_command(&spec, &seat, &invocation, &prompt).unwrap();
3020 let args: Vec<_> = plan.args(Some(&dir)).collect();
3021 assert_eq!(&args[..2], [OsStr::new("--session-dir"), dir.as_os_str()]);
3022 assert!(!args.contains(&OsStr::new("--resume")));
3023 fresh
3024 .record(&mut seat, Some("first-id".into()), true)
3025 .unwrap();
3026 seat.turns += 1;
3027
3028 let mut seat: SeatState =
3029 serde_json::from_slice(&serde_json::to_vec(&seat).unwrap()).unwrap();
3030 let resumed = OmpSession::prepare(&spec, &seat, true, || {
3031 panic!("resume must not resolve home")
3032 })
3033 .unwrap();
3034 let plan = build_command(&spec, &seat, &invocation, &prompt).unwrap();
3035 let args: Vec<_> = plan.args(resumed.dir(&seat)).collect();
3036 assert_eq!(&args[..2], [OsStr::new("--session-dir"), dir.as_os_str()]);
3037 assert!(args.windows(2).any(|w| w == ["--resume", "first-id"]));
3038 let before = seat.clone();
3039 assert!(
3040 resumed
3041 .record(&mut seat, Some("other-id".into()), true)
3042 .is_err()
3043 );
3044 assert!(OmpSession::Resume.record(&mut seat, None, true).is_err());
3045 assert_eq!(seat, before);
3046 OmpSession::Resume.record(&mut seat, None, false).unwrap();
3048 assert_eq!(seat, before);
3049
3050 let fallback = SeatState::new("review-1", "b", 7);
3051 let next = OmpSession::prepare(&spec, &fallback, true, || home.clone()).unwrap();
3052 assert_ne!(next.dir(&fallback).unwrap(), dir);
3053 invocation.sessions = false;
3055 let fresh = OmpSession::prepare(&spec, &seat, false, || home.clone()).unwrap();
3056 let new_dir = fresh.dir(&seat).unwrap().to_owned();
3057 assert_ne!(new_dir, dir);
3058 assert_ne!(next.dir(&fallback).unwrap(), new_dir);
3059 assert!(
3060 !build_command(&spec, &seat, &invocation, &prompt)
3061 .unwrap()
3062 .args(Some(&new_dir))
3063 .any(|arg| arg == "--resume")
3064 );
3065 fresh
3066 .record(&mut seat, Some("fresh-id".into()), true)
3067 .unwrap();
3068 assert_eq!(seat.omp_session_dir.as_deref(), Some(new_dir.as_path()));
3069 assert_eq!(seat.captured_session.as_deref(), Some("fresh-id"));
3070
3071 std::fs::remove_dir(new_dir).unwrap();
3072 assert!(OmpSession::prepare(&spec, &seat, true, || home.clone()).is_err());
3073 }
3074
3075 #[test]
3076 fn omp_pre_isolation_json_resumes_without_a_session_directory() {
3077 let mut seat: SeatState = serde_json::from_str(
3078 r#"{"key":"review-1","agent":"a","turns":1,"claude_session":null,"captured_session":"legacy-id"}"#,
3079 )
3080 .unwrap();
3081 let resume = OmpSession::prepare(&spec(AgentKind::Omp, None), &seat, true, || {
3082 panic!("legacy resume must not resolve or create a store")
3083 })
3084 .unwrap();
3085 let plan = plan_for(AgentKind::Omp, &seat, false);
3086 let args: Vec<_> = plan.args(resume.dir(&seat)).collect();
3087 assert!(!args.contains(&OsStr::new("--session-dir")));
3088 assert!(args.windows(2).any(|w| w == ["--resume", "legacy-id"]));
3089 resume
3090 .record(&mut seat, Some("continuation-id".into()), true)
3091 .unwrap();
3092 assert!(seat.omp_session_dir.is_none());
3093 assert_eq!(seat.captured_session.as_deref(), Some("continuation-id"));
3094 let plan = plan_for(AgentKind::Omp, &seat, false);
3095 assert!(
3096 plan.args(None)
3097 .zip(plan.args(None).skip(1))
3098 .any(|(flag, id)| flag == "--resume" && id == "continuation-id")
3099 );
3100 }
3101
3102 #[test]
3103 fn omp_managed_resume_tracks_only_local_continuation_lineage() {
3104 let tmp = tempfile::tempdir().unwrap();
3105 let managed = tmp.path().join("managed");
3106 std::fs::create_dir(&managed).unwrap();
3107 let mut seat = SeatState::new("review-1", "a", 7);
3108 seat.turns = 1;
3109 seat.captured_session = Some("original".into());
3110 seat.omp_session_dir = Some(managed.clone());
3111
3112 let write_header = |dir: &Path, id: &str, parent: &str| {
3113 let header = serde_json::json!({
3114 "type": "session", "version": 3, "id": id, "continuationOf": parent,
3115 });
3116 std::fs::write(dir.join(format!("{id}.jsonl")), format!("{header}\n")).unwrap();
3117 };
3118 write_header(tmp.path(), "outside", "original");
3119 write_header(&managed, "unrelated", "other-seat");
3120 write_header(&managed, "middle", "original");
3121 write_header(&managed, "latest", "middle");
3122 for id in ["outside", "unrelated"] {
3123 assert!(
3124 OmpSession::Resume
3125 .record(&mut seat, Some(id.into()), true)
3126 .is_err()
3127 );
3128 assert_eq!(seat.captured_session.as_deref(), Some("original"));
3129 }
3130
3131 OmpSession::Resume
3132 .record(&mut seat, Some("latest".into()), true)
3133 .unwrap();
3134 assert_eq!(seat.omp_session_dir.as_deref(), Some(managed.as_path()));
3135 let plan = plan_for(AgentKind::Omp, &seat, false);
3136 assert!(plan.argv.windows(2).any(|w| w == ["--resume", "latest"]));
3137 }
3138
3139 #[test]
3140 fn omp_managed_session_rejects_extra_args_that_override_history() {
3141 let mut spec = spec(AgentKind::Omp, None);
3142 let mut seat = SeatState::new("review-1", "a", 7);
3143 for arg in [
3144 "--session-dir",
3145 "--session-dir=other",
3146 "--no-session",
3147 "--continue",
3148 "--resume=other",
3149 "--session",
3150 "--session=operator.jsonl",
3151 "--fork",
3152 "--fork=operator.jsonl",
3153 "--restore",
3154 "--from-claude",
3155 "--from-codex",
3156 "-c",
3157 "-r=other",
3158 ] {
3159 spec.extra_args = vec![arg.into()];
3160 for sessions in [false, true] {
3161 let error = OmpSession::prepare(&spec, &seat, sessions, || panic!("invalid arg"))
3162 .err()
3163 .unwrap();
3164 assert!(error.to_string().contains("omp extra_args"));
3165 }
3166 seat.turns = 1;
3167 seat.captured_session = Some("existing-id".into());
3168 seat.omp_session_dir = Some(PathBuf::from("not-opened"));
3169 }
3170 }
3171
3172 #[test]
3177 fn omp_takes_the_answer_without_an_agent_end_line() {
3178 let stream = concat!(
3179 r#"{"type":"session","version":3,"id":"01a09fe9-4e31-7226-85b3-fda6f46689d5","cwd":"C:\\w"}"#,
3180 "\n",
3181 r#"{"type":"agent_start"}"#,
3182 "\n",
3183 r#"{"type":"turn_start"}"#,
3184 "\n",
3185 r#"{"type":"message_update","assistantMessageEvent":{"type":"text_delta","contentIndex":1,"delta":"."}}"#,
3186 "\n",
3187 r#"{"type":"message_end","message":{"role":"assistant","content":[{"type":"thinking","thinking":"checking"},{"type":"text","text":"."}]}}"#,
3188 "\n",
3189 r#"{"type":"turn_end","message":{"role":"assistant","content":[{"type":"thinking","thinking":"done"},{"type":"text","text":"{\"vote\":\"approve\"}"}]}}"#,
3190 "\n",
3191 );
3192 let out = extract(AgentKind::Omp, stream);
3193 assert_eq!(
3194 out.text, "{\"vote\":\"approve\"}",
3195 "the last assistant text block is the answer even with no agent_end"
3196 );
3197 assert_eq!(
3198 out.session.as_deref(),
3199 Some("01a09fe9-4e31-7226-85b3-fda6f46689d5")
3200 );
3201 }
3202
3203 #[test]
3207 fn omp_walks_agent_end_and_ignores_tool_loop_narration() {
3208 let stream = concat!(
3209 r#"{"type":"session","version":3,"id":"s1"}"#,
3210 "\n",
3211 "{\"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問題ありません。\"}]}]}",
3212 "\n",
3213 );
3214 let out = extract(AgentKind::Omp, stream);
3215 assert_eq!(
3216 out.text, "## 判定\n\n問題ありません。",
3217 "the narration is not the answer, and non-ASCII survives intact"
3218 );
3219 assert_eq!(out.session.as_deref(), Some("s1"));
3220 }
3221
3222 #[test]
3225 fn omp_skips_non_json_lines() {
3226 let stream = concat!(
3227 "Warning: some omp notice\n",
3228 r#"{"type":"session","version":3,"id":"s2"}"#,
3229 "\n",
3230 r#"{"type":"message_end","message":{"role":"assistant","content":[{"type":"text","text":"the answer"}]}}"#,
3231 "\n",
3232 "trailing junk",
3233 "\n",
3234 );
3235 let out = extract(AgentKind::Omp, stream);
3236 assert_eq!(out.text, "the answer");
3237 assert_eq!(out.session.as_deref(), Some("s2"));
3238 }
3239
3240 #[test]
3242 fn codex_takes_the_last_agent_message_and_the_thread_id() {
3243 let stream = concat!(
3244 "2026-09-06T01:05:49.394445Z ERROR codex_models_manager: failed to load models cache\n",
3245 r#"{"type":"thread.started","thread_id":"01a07440-4545-7492-85c1-024e3259a90a"}"#,
3246 "\n",
3247 r#"{"type":"turn.started"}"#,
3248 "\n",
3249 r#"{"type":"item.completed","item":{"id":"item_0","type":"agent_message","text":"Looking into it."}}"#,
3250 "\n",
3251 r#"{"type":"item.completed","item":{"id":"item_1","type":"command_execution","text":"cargo test"}}"#,
3252 "\n",
3253 r#"{"type":"item.completed","item":{"id":"item_2","type":"agent_message","text":"{\"verdict\": \"ok\"}"}}"#,
3254 "\n",
3255 r#"{"type":"turn.completed","usage":{"input_tokens":17137}}"#,
3256 "\n",
3257 );
3258 let out = extract(AgentKind::Codex, stream);
3259 assert_eq!(
3260 out.text, "{\"verdict\": \"ok\"}",
3261 "the last agent message is the answer; earlier ones narrate"
3262 );
3263 assert_eq!(
3264 out.session.as_deref(),
3265 Some("01a07440-4545-7492-85c1-024e3259a90a")
3266 );
3267 assert_eq!(out.status.as_deref(), Some("success"));
3268
3269 let failed = concat!(
3270 r#"{"type":"thread.started","thread_id":"t1"}"#,
3271 "\n",
3272 r#"{"type":"turn.failed","error":{"message":"nope"}}"#,
3273 "\n",
3274 );
3275 assert_eq!(
3276 extract(AgentKind::Codex, failed).status.as_deref(),
3277 Some("error")
3278 );
3279 }
3280
3281 #[test]
3282 fn captured_sessions_resume_only_once_reported() {
3283 let mut seat = SeatState::new("impl-A", "a", 7);
3284 seat.turns = 1;
3285 for kind in [AgentKind::Opencode, AgentKind::Antigravity] {
3286 assert!(!has_session(kind, &seat, true));
3287 let p = plan_for(kind, &seat, true);
3288 assert!(!p.argv.iter().any(|a| a == "-s" || a == "--conversation"));
3289 }
3290
3291 seat.captured_session = Some("sid".to_owned());
3292 assert!(has_session(AgentKind::Opencode, &seat, true));
3293 assert!(
3294 plan_for(AgentKind::Opencode, &seat, true)
3295 .argv
3296 .windows(2)
3297 .any(|w| w == ["-s", "sid"])
3298 );
3299 assert!(
3300 plan_for(AgentKind::Antigravity, &seat, true)
3301 .argv
3302 .windows(2)
3303 .any(|w| w == ["--conversation", "sid"])
3304 );
3305 }
3306
3307 #[test]
3308 fn sessions_disabled_never_resumes() {
3309 let mut seat = SeatState::new("impl-A", "a", 7);
3310 seat.turns = 3;
3311 seat.captured_session = Some("sid".to_owned());
3312 for kind in [
3313 AgentKind::Claude,
3314 AgentKind::Opencode,
3315 AgentKind::Antigravity,
3316 ] {
3317 assert!(!has_session(kind, &seat, false));
3318 }
3319 }
3320
3321 #[test]
3322 fn long_prompts_never_reach_argv_for_file_delivery_clis() {
3323 let seat = SeatState::new("judge-1", "a", 7);
3324 for kind in [AgentKind::Opencode, AgentKind::Antigravity] {
3325 let p = plan_for(kind, &seat, false);
3326 assert!(
3327 p.argv.iter().all(|a| a != "do the thing"),
3328 "{kind:?} put the prompt on the command line"
3329 );
3330 assert!(p.argv.iter().any(|a| a.contains("/art/p.md")));
3331 }
3332 let p = plan_for(AgentKind::Antigravity, &seat, false);
3334 let at = p.argv.iter().position(|a| a == "-p").unwrap();
3335 assert!(p.argv.get(at + 1).is_some_and(|v| v.contains("p.md")));
3336 assert!(p.stdin.is_none());
3337 }
3338
3339 #[test]
3340 fn agy_print_timeout_tracks_the_node_budget() {
3341 let seat = SeatState::new("impl-A", "a", 7);
3342 let p = build_command(
3343 &spec(AgentKind::Antigravity, None),
3344 &seat,
3345 &Invocation {
3346 coordination: None,
3347 fetched_base: None,
3348 cwd: Path::new("."),
3349 prompt: "p",
3350 timeout: Duration::from_secs(3600),
3351 allow_write: true,
3352 sessions: true,
3353 artifacts: Path::new("/art"),
3354 stem: "t",
3355 run: "test-run",
3356 node: "test",
3357 cache_dir: None,
3358 attachments: &[],
3359 writable: &[],
3360 },
3361 Path::new("/art/p.md"),
3362 )
3363 .unwrap();
3364 assert!(p.argv.windows(2).any(|w| w == ["--print-timeout", "3600s"]));
3365 }
3366
3367 #[test]
3374 fn attachments_widen_antigravitys_add_dir_even_off_file_delivery() {
3375 let mut s = spec(AgentKind::Antigravity, None);
3376 s.prompt_delivery = Some(Delivery::Argv);
3377 let seat = SeatState::new("talk", "a", 7);
3378 let atts = [PathBuf::from("/art/attachments/abc.png")];
3379
3380 let without = build_command(
3381 &s,
3382 &seat,
3383 &Invocation {
3384 attachments: &[],
3385 writable: &[],
3386 ..inv(Path::new("."), Path::new("/art"), true)
3387 },
3388 Path::new("/art/p.md"),
3389 )
3390 .unwrap();
3391 assert!(
3392 !without.argv.iter().any(|a| a == "--add-dir"),
3393 "no attachment, no reason to widen the sandbox: {without:?}"
3394 );
3395
3396 let with = build_command(
3397 &s,
3398 &seat,
3399 &Invocation {
3400 attachments: &atts,
3401 writable: &[],
3402 ..inv(Path::new("."), Path::new("/art"), true)
3403 },
3404 Path::new("/art/p.md"),
3405 )
3406 .unwrap();
3407 assert!(
3408 with.argv.windows(2).any(|w| w == ["--add-dir", "/art"]),
3409 "an attachment outside cwd must widen the sandbox even off File delivery: {with:?}"
3410 );
3411 }
3412
3413 #[test]
3419 fn an_inherited_attachment_outside_this_conversations_artifacts_dir_gets_its_own_add_dir() {
3420 let seat = SeatState::new("plan", "a", 7);
3421 let atts = [
3422 PathBuf::from("/art/attachments/own.png"),
3423 PathBuf::from("/other-chat/attachments/inherited.png"),
3424 ];
3425
3426 let p = build_command(
3427 &spec(AgentKind::Antigravity, None),
3428 &seat,
3429 &Invocation {
3430 attachments: &atts,
3431 writable: &[],
3432 ..inv(Path::new("."), Path::new("/art"), true)
3433 },
3434 Path::new("/art/p.md"),
3435 )
3436 .unwrap();
3437
3438 assert!(
3439 p.argv.windows(2).any(|w| w == ["--add-dir", "/art"]),
3440 "this conversation's own artifacts dir must still be granted: {p:?}"
3441 );
3442 assert!(
3443 p.argv
3444 .windows(2)
3445 .any(|w| w == ["--add-dir", "/other-chat/attachments"]),
3446 "the inherited attachment's own directory must be granted too: {p:?}"
3447 );
3448 }
3449
3450 #[test]
3451 fn command_agents_get_placeholders_substituted() {
3452 let seat = SeatState::new("impl-A", "a", 7);
3453 let p = plan_for(AgentKind::Command, &seat, true);
3454 assert_eq!(p.argv[0], "echo");
3455 assert_eq!(p.argv[1], "impl-A");
3456 assert_eq!(p.stdin.as_deref(), Some("do the thing"));
3457 }
3458
3459 const EXPIRED_AUTH: &str = r#"{"is_error":true,"terminal_reason":"api_error","result":"Failed to authenticate: OAuth session expired and could not be refreshed"}"#;
3460 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."}
3461{"type":"turn.failed","error":{"message":"You've hit your usage limit."}}"#;
3462
3463 #[test]
3464 fn observed_machine_failures_are_detected_conservatively() {
3465 let auth = extract(AgentKind::Claude, EXPIRED_AUTH).quota.unwrap();
3466 assert_eq!(auth.cause, QuotaCause::Authentication);
3467 assert_eq!(auth.reset, None);
3468 let limit = extract(AgentKind::Codex, CODEX_LIMIT).quota.unwrap();
3469 assert_eq!(limit.cause, QuotaCause::UsageLimit);
3470 assert_eq!(limit.reset.as_deref(), Some("Oct 27th, 2026 6:18 PM"));
3471 assert!(
3473 extract(AgentKind::Codex, &format!("{CODEX_LIMIT}\n{CODEX_LIMIT}"))
3474 .quota
3475 .is_some()
3476 );
3477 let without_reset = CODEX_LIMIT.replace(" or try again at Oct 27th, 2026 6:18 PM", "");
3478 assert!(
3479 extract(AgentKind::Codex, &without_reset)
3480 .quota
3481 .unwrap()
3482 .reset
3483 .is_none()
3484 );
3485 for text in [
3486 EXPIRED_AUTH.replace("true", "false"),
3487 EXPIRED_AUTH.replace("api_error", "unknown"),
3488 EXPIRED_AUTH.replace(
3489 "OAuth session expired and could not be refreshed",
3490 "unknown error",
3491 ),
3492 ] {
3493 assert!(extract(AgentKind::Claude, &text).quota.is_none());
3494 }
3495 assert!(
3496 extract(AgentKind::Codex, CODEX_LIMIT.lines().next().unwrap())
3497 .quota
3498 .is_none()
3499 );
3500 assert!(
3501 extract(
3502 AgentKind::Codex,
3503 &CODEX_LIMIT.replace("You've hit your usage limit.", "Something failed.")
3504 )
3505 .quota
3506 .is_none()
3507 );
3508 let quoted = serde_json::json!({"type":"item.completed","item":{"type":"agent_message","text":CODEX_LIMIT}}).to_string();
3509 assert!(extract(AgentKind::Codex, "ed).quota.is_none());
3510 assert!(extract(AgentKind::Codex, EXPIRED_AUTH).quota.is_none());
3511 assert!(
3512 extract(AgentKind::Antigravity, EXPIRED_AUTH)
3513 .quota
3514 .is_none()
3515 );
3516 let legacy: Quota = serde_json::from_str(r#"{"reset":null}"#).unwrap();
3517 assert_eq!(legacy.cause, QuotaCause::UsageLimit);
3518 }
3519
3520 #[test]
3521 fn claude_rate_limit_is_detected_and_reset_read_when_present() {
3522 let stdout = r#"{"is_error": true, "terminal_reason": "api_error",
3524 "result": "You've hit your session limit · resets 4:50am (Asia/Tokyo)",
3525 "session_id": "b8e928f1-754e-4bd3-86c5-0567763654e3"}"#;
3526 let out = extract(AgentKind::Claude, stdout);
3527 let quota = out.quota.as_ref().expect("rate limit must be detected");
3528 assert_eq!(
3529 quota.reset.as_deref(),
3530 Some("4:50am (Asia/Tokyo)"),
3531 "reset time read from the body"
3532 );
3533 }
3534
3535 #[test]
3536 fn claude_rate_limit_without_a_readable_reset_is_still_detected() {
3537 let out = extract(
3538 AgentKind::Claude,
3539 r#"{"is_error":true,"result":"session limit reached"}"#,
3540 );
3541 let quota = out.quota.expect("rate limit detected without a reset");
3542 assert!(quota.reset.is_none(), "unknown reset is kept as unknown");
3543 }
3544
3545 #[test]
3546 fn claude_structured_usage_limit_requires_the_error_and_exact_pair() {
3547 for kind in [AgentKind::Claude, AgentKind::Command] {
3548 for reply in [
3549 r#"{"is_error":true,"api_error_status":429,"api_error":"usage_limit_reached"}"#,
3550 r#"{"is_error":true,"api_error_status":"429","api_error":"usage_limit_reached"}"#,
3551 ] {
3552 assert!(extract(kind, reply).quota.is_some(), "{reply}");
3553 }
3554 for reply in [
3555 r#"{"is_error":false,"api_error_status":429,"api_error":"usage_limit_reached"}"#,
3556 r#"{"is_error":true,"api_error_status":500,"api_error":"usage_limit_reached"}"#,
3557 r#"{"is_error":true,"api_error_status":429,"api_error":"other_error"}"#,
3558 r#"{"is_error":false,"api_error_status":"429","api_error":"usage_limit_reached"}"#,
3559 r#"{"is_error":true,"api_error_status":"500","api_error":"usage_limit_reached"}"#,
3560 r#"{"is_error":true,"api_error_status":"429","api_error":"other_error"}"#,
3561 r#"{"is_error":true,"api_error":"usage_limit_reached"}"#,
3562 ] {
3563 assert!(extract(kind, reply).quota.is_none(), "{reply}");
3564 }
3565 }
3566 }
3567
3568 #[test]
3569 fn ordinary_failures_are_never_quota() {
3570 let claude_fail = extract(
3572 AgentKind::Claude,
3573 r#"{"is_error":true,"result":"account does not exist"}"#,
3574 );
3575 assert!(claude_fail.quota.is_none());
3576
3577 let cmd_fail = extract(AgentKind::Command, "boom");
3579 assert!(cmd_fail.quota.is_none());
3580
3581 let success = extract(
3583 AgentKind::Command,
3584 r#"{"is_error":false,"result":"session limit is fine"}"#,
3585 );
3586 assert!(success.quota.is_none());
3587 }
3588
3589 #[test]
3597 fn codex_command_execution_events_are_captured_alongside_the_final_message() {
3598 let stream = concat!(
3599 r#"{"type":"thread.started","thread_id":"t1"}"#,
3600 "\n",
3601 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"}}"#,
3602 "\n",
3603 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"}}"#,
3604 "\n",
3605 r#"{"type":"item.completed","item":{"id":"item99","type":"agent_message","text":"Both tests in the target pass."}}"#,
3606 "\n",
3607 r#"{"type":"turn.completed"}"#,
3608 "\n",
3609 );
3610 let out = extract(AgentKind::Codex, stream);
3611 assert_eq!(out.text, "Both tests in the target pass.");
3612 assert_eq!(out.commands.len(), 2, "{:?}", out.commands);
3613
3614 let paired = &out.commands[0];
3615 assert_eq!(paired.id, "item49");
3616 assert_eq!(paired.exit_code, Some(1));
3617 assert!(paired.description.contains("graph_cached_gate"));
3618 assert!(paired.result_summary.contains("1 failed"));
3619
3620 let solo = &out.commands[1];
3621 assert_eq!(solo.exit_code, Some(0));
3622
3623 assert!(
3627 out.commands
3628 .iter()
3629 .any(|c| c.exit_code != Some(0) && c.description.contains("graph_cached_gate")),
3630 "a failed run of the actual target must still be visible: {:?}",
3631 out.commands
3632 );
3633 }
3634
3635 #[test]
3636 fn command_agent_can_carry_the_claude_quota_shape() {
3637 let out = extract(
3638 AgentKind::Command,
3639 r#"{"is_error":true,"result":"You've hit your session limit · resets 1:00am (UTC)"}"#,
3640 );
3641 assert!(
3642 out.quota.is_some(),
3643 "a wrapper emitting the claude shape counts as quota"
3644 );
3645 }
3646
3647 #[test]
3648 fn claude_json_result_is_extracted() {
3649 let out = extract(
3650 AgentKind::Claude,
3651 r#"{"result":"all done","session_id":"abc","is_error":false}"#,
3652 );
3653 assert_eq!(out.text, "all done");
3654 assert_eq!(out.session.as_deref(), Some("abc"));
3655 assert_eq!(out.status.as_deref(), Some("success"));
3656 }
3657
3658 #[test]
3673 fn a_clean_cli_turn_is_not_the_same_fact_as_the_nodes_own_work_being_done() {
3674 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"}"#;
3675 let out = extract(AgentKind::Claude, stdout);
3676 assert_eq!(out.status.as_deref(), Some("success"));
3677 assert!(out.quota.is_none());
3678 assert!(!out.text.trim().is_empty());
3679
3680 let agent_out = AgentOutput {
3681 text: out.text.clone(),
3682 exit_code: Some(0),
3683 timed_out: false,
3684 duration_ms: 500,
3685 artifacts: Vec::new(),
3686 quota: out.quota,
3687 dropped: out.dropped,
3688 commands: out.commands,
3689 context_tokens: None,
3690 };
3691 assert!(
3692 agent_out.usable(),
3693 "the CLI turn itself ended cleanly and must read as usable"
3694 );
3695 assert!(
3696 crate::verdict::extract_json::<crate::verdict::FixReport>(&agent_out.text).is_err(),
3697 "a clean CLI turn is not proof the node's own report ever arrived"
3698 );
3699 }
3700
3701 #[test]
3702 fn opencode_event_stream_is_concatenated() {
3703 let stream = concat!(
3704 r#"{"type":"step_start","sessionID":"ses_1","part":{"type":"step-start"}}"#,
3705 "\n",
3706 r#"{"type":"text","sessionID":"ses_1","part":{"type":"text","text":"first"}}"#,
3707 "\n",
3708 "garbage line\n",
3709 r#"{"type":"text","sessionID":"ses_1","part":{"type":"text","text":"second"}}"#,
3710 "\n"
3711 );
3712 let out = extract(AgentKind::Opencode, stream);
3713 assert_eq!(out.text, "first\nsecond");
3714 assert_eq!(out.session.as_deref(), Some("ses_1"));
3715 }
3716
3717 #[test]
3718 fn agy_json_survives_a_leading_warning_line() {
3719 let stdout = concat!(
3720 "warning: --mode plan has no effect while slash commands are disabled.\n",
3721 r#"{"conversation_id":"eaf2d00a","status":"SUCCESS","response":"persimmon\n"}"#,
3722 "\n"
3723 );
3724 let out = extract(AgentKind::Antigravity, stdout);
3725 assert_eq!(out.text, "persimmon");
3726 assert_eq!(out.session.as_deref(), Some("eaf2d00a"));
3727 assert_eq!(out.status.as_deref(), Some("SUCCESS"));
3728 }
3729
3730 const AGY_DROPPED: &str = concat!(
3737 r#"{"conversation_id":"36743d06-c0b3-4b79-9fa2-23869289d7b6","status":"ERROR","#,
3738 r#""response":"","error":"the connection to the agent was interrupted before "#,
3739 r#"the response finished: subscriber fell behind updates, stalled for 5s","#,
3740 r#""duration_seconds":431.1941803,"num_turns":1,"usage":{"input_tokens":260113,"#,
3741 r#""output_tokens":14267,"thinking_tokens":9695,"cache_read_tokens":2200925,"#,
3742 r#""total_tokens":274380}}"#
3743 );
3744
3745 const AGY_QUOTA_OUT: &str = concat!(
3747 r#"{"conversation_id":"323c3b5b-0000","status":"ERROR","response":"","#,
3748 r#""error":"Individual quota reached. Please upgrade your subscription to "#,
3749 r#"increase your limits. Resets in 1h2m49s.","duration_seconds":265.9,"#,
3750 r#""num_turns":2,"usage":{"input_tokens":1000,"output_tokens":50}}"#
3751 );
3752 const AGY_QUOTA_ERR: &str = concat!(
3753 "error: Individual quota reached. Resets in 1h2m49s.\n",
3754 r#"AGY_ERROR: {"short_error":"RESOURCE_EXHAUSTED (code 429): Individual quota "#,
3755 r#"reached.","status":"RESOURCE_EXHAUSTED","error_code":429,"code_kind":"http","#,
3756 r#""retryable":true}"#,
3757 "\n"
3758 );
3759
3760 #[test]
3761 fn agy_out_of_quota_is_a_quota_with_the_reset_hint() {
3762 let both = agy_quota(AGY_QUOTA_OUT, AGY_QUOTA_ERR).expect("both streams");
3763 assert_eq!(both.reset.as_deref(), Some("in 1h2m49s"));
3764 let stdout_only = agy_quota(AGY_QUOTA_OUT, "").expect("stdout alone");
3765 assert_eq!(stdout_only.reset.as_deref(), Some("in 1h2m49s"));
3766 let stderr_only = agy_quota("not json", AGY_QUOTA_ERR).expect("stderr alone");
3768 assert!(stderr_only.reset.is_none());
3769 }
3770
3771 #[test]
3772 fn ordinary_agy_failures_are_not_a_quota() {
3773 assert!(agy_quota(AGY_DROPPED, "").is_none());
3774 assert!(agy_quota(r#"{"status":"ERROR","error":"boom"}"#, "").is_none());
3775 assert!(
3776 agy_quota(
3777 "",
3778 r#"AGY_ERROR: {"status":"RESOURCE_EXHAUSTED","error_code":500}"#
3779 )
3780 .is_none()
3781 );
3782 assert!(
3783 agy_quota(
3784 "",
3785 r#"AGY_ERROR: {"status":"UNAVAILABLE","error_code":429}"#
3786 )
3787 .is_none()
3788 );
3789 assert!(agy_quota(r#"{"status":"SUCCESS","response":"ok"}"#, "").is_none());
3790 }
3791
3792 #[test]
3793 fn a_cli_that_hangs_up_on_billed_work_is_not_an_agent_that_produced_nothing() {
3794 let out = extract(AgentKind::Antigravity, AGY_DROPPED);
3795 let dropped = out.dropped.expect("recognised as undelivered work");
3796 assert_eq!(dropped.output_tokens, 14267);
3797 assert!(
3798 dropped.why.contains("subscriber fell behind"),
3799 "the CLI's own words are kept for the record: {}",
3800 dropped.why
3801 );
3802 assert_eq!(
3805 out.session.as_deref(),
3806 Some("36743d06-c0b3-4b79-9fa2-23869289d7b6")
3807 );
3808 assert!(out.quota.is_none(), "a dropped stream is not a rate limit");
3809 }
3810
3811 #[test]
3812 fn an_error_with_nothing_produced_stays_an_ordinary_failure() {
3813 let bare = r#"{"conversation_id":"c1","status":"ERROR","response":"","error":"boom"}"#;
3817 assert!(extract(AgentKind::Antigravity, bare).dropped.is_none());
3818
3819 let answered = concat!(
3822 r#"{"conversation_id":"c2","status":"ERROR","response":"here it is","#,
3823 r#""usage":{"output_tokens":10}}"#
3824 );
3825 assert!(extract(AgentKind::Antigravity, answered).dropped.is_none());
3826
3827 let ok = concat!(
3829 r#"{"conversation_id":"c3","status":"SUCCESS","response":"done","#,
3830 r#""usage":{"output_tokens":10}}"#
3831 );
3832 assert!(extract(AgentKind::Antigravity, ok).dropped.is_none());
3833 }
3834
3835 #[test]
3836 fn an_undelivered_output_is_not_usable_but_is_worth_asking_again() {
3837 let out = AgentOutput {
3838 text: String::new(),
3839 exit_code: Some(1),
3840 timed_out: false,
3841 duration_ms: 431_194,
3842 artifacts: Vec::new(),
3843 quota: None,
3844 dropped: Some(Dropped {
3845 why: "subscriber fell behind updates".to_owned(),
3846 output_tokens: 14267,
3847 }),
3848 commands: Vec::new(),
3849 context_tokens: None,
3850 };
3851 assert!(!out.usable());
3852 assert!(out.work_undelivered());
3853 assert!(!out.quota_exhausted());
3856 }
3857
3858 #[test]
3859 fn non_json_stdout_falls_back_to_raw_text() {
3860 let out = extract(AgentKind::Antigravity, "plain answer\n");
3861 assert_eq!(out.text, "plain answer");
3862 assert!(out.session.is_none());
3863 }
3864
3865 #[tokio::test]
3866 async fn command_agent_round_trip_writes_artifacts() {
3867 let dir = tempfile::tempdir().unwrap();
3868 let art = dir.path().join("artifacts");
3869 let mut seat = SeatState::new("impl-A", "a", 7);
3870 let s = command_helper("reply");
3871 let out = invoke(
3872 &s,
3873 &mut seat,
3874 &Invocation {
3875 coordination: None,
3876 fetched_base: None,
3877 cwd: dir.path(),
3878 prompt: "unused",
3879 timeout: Duration::from_secs(30),
3880 allow_write: true,
3881 sessions: true,
3882 artifacts: &art,
3883 stem: "impl-A",
3884 run: "test-run",
3885 node: "test",
3886 cache_dir: None,
3887 attachments: &[],
3888 writable: &[],
3889 },
3890 )
3891 .await
3892 .unwrap();
3893 assert!(out.usable(), "{out:?}");
3894 assert!(out.text.contains("hello impl-A"), "{}", out.text);
3895 assert_eq!(seat.turns, 1);
3896 assert!(art.join("impl-A.prompt.md").is_file());
3897 assert!(art.join("impl-A.out").is_file());
3898 }
3899
3900 #[tokio::test]
3901 async fn the_invocation_cache_dir_reaches_the_seat_as_cargo_target_dir() {
3902 crate::run::pin_test_home();
3903 let dir = tempfile::tempdir().unwrap();
3907 let cache = dir.path().join("magi-cache");
3908 let mut seat = SeatState::new("impl-A", "a", 7);
3909 let s = command_helper("cache");
3910 let out = invoke(
3911 &s,
3912 &mut seat,
3913 &Invocation {
3914 coordination: None,
3915 fetched_base: None,
3916 cwd: dir.path(),
3917 prompt: "unused",
3918 timeout: Duration::from_secs(30),
3919 allow_write: true,
3920 sessions: true,
3921 artifacts: &dir.path().join("artifacts"),
3922 stem: "cache",
3923 run: "test-run",
3924 node: "test",
3925 cache_dir: Some(&cache),
3926 attachments: &[],
3927 writable: &[],
3928 },
3929 )
3930 .await
3931 .unwrap();
3932 assert!(out.usable(), "{out:?}");
3933 assert!(
3934 out.text.contains(cache.to_string_lossy().as_ref()),
3935 "the seat must see CARGO_TARGET_DIR = the shared cache"
3936 );
3937 }
3938
3939 #[tokio::test]
3940 async fn cache_dir_none_strips_a_cargo_target_dir_inherited_from_this_process() {
3941 let previous = std::env::var("CARGO_TARGET_DIR").ok();
3949 unsafe {
3954 std::env::set_var("CARGO_TARGET_DIR", "/should/never/reach/a/read-only/seat");
3955 }
3956 let dir = tempfile::tempdir().unwrap();
3957 let mut seat = SeatState::new("review-1", "a", 7);
3958 let s = command_helper("no-cache");
3959 let result = invoke(
3960 &s,
3961 &mut seat,
3962 &Invocation {
3963 coordination: None,
3964 fetched_base: None,
3965 cwd: dir.path(),
3966 prompt: "unused",
3967 timeout: Duration::from_secs(30),
3968 allow_write: false,
3969 sessions: true,
3970 artifacts: &dir.path().join("artifacts"),
3971 stem: "no-cache",
3972 run: "test-run",
3973 node: "test",
3974 cache_dir: None,
3975 attachments: &[],
3976 writable: &[],
3977 },
3978 )
3979 .await;
3980 unsafe {
3985 match &previous {
3986 Some(v) => std::env::set_var("CARGO_TARGET_DIR", v),
3987 None => std::env::remove_var("CARGO_TARGET_DIR"),
3988 }
3989 }
3990 let out = result.unwrap();
3991 assert!(out.usable(), "{out:?}");
3992 assert!(
3993 out.text.contains("ABSENT"),
3994 "a read-only seat must never inherit the process's own CARGO_TARGET_DIR: {}",
3995 out.text
3996 );
3997 }
3998
3999 #[tokio::test]
4000 async fn a_prompt_larger_than_the_pipe_buffer_does_not_deadlock() {
4001 let dir = tempfile::tempdir().unwrap();
4002 let mut seat = SeatState::new("impl-A", "a", 7);
4003 let s = command_helper("ignore-stdin");
4006 let big = "x".repeat(1_000_000);
4007 let out = invoke(
4008 &s,
4009 &mut seat,
4010 &Invocation {
4011 coordination: None,
4012 fetched_base: None,
4013 cwd: dir.path(),
4014 prompt: &big,
4015 timeout: Duration::from_secs(60),
4016 allow_write: true,
4017 sessions: true,
4018 artifacts: &dir.path().join("artifacts"),
4019 stem: "big",
4020 run: "test-run",
4021 node: "test",
4022 cache_dir: None,
4023 attachments: &[],
4024 writable: &[],
4025 },
4026 )
4027 .await
4028 .unwrap();
4029 assert!(out.usable(), "{out:?}");
4030 assert!(out.text.contains("done"), "{}", out.text);
4031 }
4032
4033 #[tokio::test]
4034 async fn agent_turn_cap_limits_a_direct_invocation() {
4035 let dir = tempfile::tempdir().unwrap();
4036 let artifacts = dir.path().join("artifacts");
4037 let mut seat = SeatState::new("impl-A", "helper", 7);
4038 let mut s = command_helper("sleep");
4039 s.max_turn_secs = Some(2);
4040 let out = invoke(&s, &mut seat, &inv(dir.path(), &artifacts, false))
4041 .await
4042 .unwrap();
4043 assert!(out.timed_out, "{out:?}");
4044 assert!(out.duration_ms < 20_000, "{out:?}");
4047 }
4048
4049 #[tokio::test]
4050 async fn timeout_is_reported_not_hung() {
4051 let dir = tempfile::tempdir().unwrap();
4052 let mut seat = SeatState::new("impl-A", "a", 7);
4053 let s = command_helper("sleep");
4054 let out = invoke(
4055 &s,
4056 &mut seat,
4057 &Invocation {
4058 coordination: None,
4059 fetched_base: None,
4060 cwd: dir.path(),
4061 prompt: "unused",
4062 timeout: Duration::from_millis(300),
4063 allow_write: true,
4064 sessions: true,
4065 artifacts: &dir.path().join("artifacts"),
4066 stem: "slow",
4067 run: "test-run",
4068 node: "test",
4069 cache_dir: None,
4070 attachments: &[],
4071 writable: &[],
4072 },
4073 )
4074 .await
4075 .unwrap();
4076 assert!(out.timed_out);
4077 assert!(!out.usable());
4078 }
4079
4080 #[tokio::test]
4081 async fn a_timeout_keeps_what_the_agent_had_already_printed() {
4082 let dir = tempfile::tempdir().unwrap();
4088 let artifacts = dir.path().join("artifacts");
4089 let mut seat = SeatState::new("impl-A", "a", 7);
4090 let s = command_helper("chatty-sleep");
4091 let out = invoke(
4092 &s,
4093 &mut seat,
4094 &Invocation {
4095 coordination: None,
4096 fetched_base: None,
4097 cwd: dir.path(),
4098 prompt: "unused",
4099 timeout: Duration::from_secs(10),
4104 allow_write: true,
4105 sessions: true,
4106 artifacts: &artifacts,
4107 stem: "chatty",
4108 run: "test-run",
4109 node: "test",
4110 cache_dir: None,
4111 attachments: &[],
4112 writable: &[],
4113 },
4114 )
4115 .await
4116 .unwrap();
4117
4118 assert!(out.timed_out, "{out:?}");
4119 assert!(!out.usable(), "a cut-off answer is still not an answer");
4120 let recorded = std::fs::read_to_string(artifacts.join("chatty.out")).unwrap();
4121 assert!(
4122 recorded.contains("i-said-something"),
4123 "the artifact must keep what arrived before the kill, got {recorded:?}"
4124 );
4125 assert!(
4126 out.text.contains("i-said-something"),
4127 "and the graph must be able to see it too, got {:?}",
4128 out.text
4129 );
4130 }
4131
4132 #[test]
4133 fn missing_programs_reports_command_binaries() {
4134 let mut s = spec(AgentKind::Command, None);
4135 s.command = vec!["definitely-not-a-real-binary-xyz".to_owned()];
4136 assert_eq!(
4137 missing_programs(&[s]),
4138 ["definitely-not-a-real-binary-xyz".to_owned()]
4139 );
4140 }
4141
4142 fn pick_spec(id: &str, kind: AgentKind) -> AgentSpec {
4143 AgentSpec {
4144 id: id.to_owned(),
4145 kind,
4146 model: None,
4147 command: Vec::new(),
4148 extra_args: Vec::new(),
4149 env: BTreeMap::new(),
4150 prompt_delivery: None,
4151 max_turn_secs: None,
4152 }
4153 }
4154
4155 fn without<'a>(missing: &'a [&'a str]) -> impl Fn(&AgentSpec) -> bool + 'a {
4158 move |a: &AgentSpec| !missing.contains(&a.id.as_str())
4159 }
4160
4161 #[test]
4162 fn pick_prefers_the_claude_seat_even_when_it_is_not_first_in_the_roster() {
4163 let agents = [
4164 pick_spec("oc", AgentKind::Opencode),
4165 pick_spec("opus", AgentKind::Claude),
4166 pick_spec("agy", AgentKind::Antigravity),
4167 ];
4168 let got = pick(&agents, None, &without(&[])).expect("a pick");
4169 assert_eq!(got.id, "opus");
4170 }
4171
4172 #[test]
4173 fn pick_falls_back_to_the_first_installed_agent_in_roster_order() {
4174 let agents = [
4175 pick_spec("opus", AgentKind::Claude),
4176 pick_spec("oc", AgentKind::Opencode),
4177 pick_spec("agy", AgentKind::Antigravity),
4178 ];
4179 let got = pick(&agents, None, &without(&["opus", "oc"])).expect("a pick");
4180 assert_eq!(got.id, "agy");
4181 }
4182
4183 #[test]
4184 fn pick_on_an_empty_roster_says_what_to_install() {
4185 let msg = pick(&[], None, &without(&[]))
4186 .expect_err("nobody to ask")
4187 .to_string();
4188 assert!(msg.contains("roster is empty"), "{msg}");
4189 assert!(msg.contains("claude"), "{msg}");
4190 assert!(msg.contains("magi.toml"), "{msg}");
4191 }
4192
4193 #[test]
4194 fn pick_on_a_roster_with_nothing_installed_names_the_programs_that_are_missing() {
4195 let agents = [
4196 pick_spec("opus", AgentKind::Claude),
4197 pick_spec("oc", AgentKind::Opencode),
4198 ];
4199 let err = pick(&agents, None, &without(&["opus", "oc"])).expect_err("nothing runnable");
4200 let msg = format!("{err:#}");
4201 assert!(msg.contains("claude"), "{msg}");
4202 assert!(msg.contains("opencode"), "{msg}");
4203 }
4204
4205 #[test]
4206 fn an_explicitly_named_agent_wins_over_the_claude_preference() {
4207 let agents = [
4208 pick_spec("opus", AgentKind::Claude),
4209 pick_spec("oc", AgentKind::Opencode),
4210 ];
4211 let got = pick(&agents, Some("oc"), &without(&[])).expect("a pick");
4212 assert_eq!(got.id, "oc");
4213 }
4214
4215 #[test]
4216 fn an_unknown_agent_id_lists_the_ids_that_do_exist() {
4217 let agents = [
4218 pick_spec("opus", AgentKind::Claude),
4219 pick_spec("oc", AgentKind::Opencode),
4220 ];
4221 let msg = pick(&agents, Some("gemini"), &without(&[]))
4222 .expect_err("no such agent")
4223 .to_string();
4224 assert!(msg.contains("gemini"), "{msg}");
4225 assert!(msg.contains("opus, oc"), "{msg}");
4226 }
4227
4228 #[test]
4229 fn an_explicitly_named_agent_that_is_not_installed_is_an_error_not_a_fallback() {
4230 let agents = [
4231 pick_spec("opus", AgentKind::Claude),
4232 pick_spec("oc", AgentKind::Opencode),
4233 ];
4234 let msg = pick(&agents, Some("oc"), &without(&["oc"]))
4235 .expect_err("must not silently substitute another model")
4236 .to_string();
4237 assert!(msg.contains("opencode"), "{msg}");
4238 assert!(msg.contains("--agent"), "{msg}");
4239 }
4240
4241 fn named(id: &str) -> AgentSpec {
4242 AgentSpec {
4243 id: id.to_owned(),
4244 ..spec(AgentKind::Command, None)
4245 }
4246 }
4247
4248 fn output(text: &str, exit: i32, quota: bool) -> AgentOutput {
4249 AgentOutput {
4250 text: text.to_owned(),
4251 exit_code: Some(exit),
4252 timed_out: false,
4253 duration_ms: 0,
4254 artifacts: Vec::new(),
4255 quota: quota.then_some(Quota {
4256 reset: None,
4257 cause: QuotaCause::UsageLimit,
4258 agent: String::new(),
4259 }),
4260 dropped: None,
4261 commands: Vec::new(),
4262 context_tokens: None,
4263 }
4264 }
4265
4266 #[test]
4267 fn a_chain_keeps_the_written_order_and_a_string_is_a_chain_of_one() {
4268 let agents = [named("a"), named("b"), named("c")];
4269 let all = |_: &AgentSpec| true;
4270 let chain = AgentChoice::Chain(vec!["c".into(), "a".into()]);
4271 let got = pick_chain(&agents, Some(&chain), &all, "synthesizer").unwrap();
4272 assert_eq!(
4273 got.iter().map(|s| s.id.as_str()).collect::<Vec<_>>(),
4274 ["c", "a"]
4275 );
4276
4277 let one = AgentChoice::from("b");
4278 let got = pick_chain(&agents, Some(&one), &all, "synthesizer").unwrap();
4279 assert_eq!(got.len(), 1);
4280 assert_eq!(got[0].id, "b");
4281
4282 let got = pick_chain(&agents, None, &all, "synthesizer").unwrap();
4283 assert_eq!(got.len(), 1, "unset keeps pick's default");
4284 assert_eq!(got[0].id, "a");
4285 let empty = AgentChoice::Chain(Vec::new());
4286 assert_eq!(
4287 pick_chain(&agents, Some(&empty), &all, "x").unwrap()[0].id,
4288 "a"
4289 );
4290 }
4291
4292 #[test]
4293 fn a_chain_skips_unknown_and_uninstalled_ids_and_tries_each_once() {
4294 let agents = [named("a"), named("b")];
4295 let not_a = |s: &AgentSpec| s.id != "a";
4296 let chain = AgentChoice::Chain(
4297 ["a", "ghost", "b", "b"]
4298 .iter()
4299 .map(|s| (*s).to_owned())
4300 .collect(),
4301 );
4302 let got = pick_chain(&agents, Some(&chain), ¬_a, "chatter").unwrap();
4303 assert_eq!(got.iter().map(|s| s.id.as_str()).collect::<Vec<_>>(), ["b"]);
4304
4305 let dup = AgentChoice::Chain(vec!["b".into(), "a".into(), "b".into()]);
4306 let got = pick_chain(&agents, Some(&dup), &|_| true, "chatter").unwrap();
4307 assert_eq!(
4308 got.iter().map(|s| s.id.as_str()).collect::<Vec<_>>(),
4309 ["b", "a"]
4310 );
4311 }
4312
4313 #[test]
4314 fn a_chain_with_nothing_runnable_names_the_role() {
4315 let agents = [named("a")];
4316 let chain = AgentChoice::Chain(vec!["a".into(), "ghost".into()]);
4317 let err = pick_chain(&agents, Some(&chain), &|_| false, "conductor")
4318 .unwrap_err()
4319 .to_string();
4320 assert!(err.contains("conductor"), "{err}");
4321 }
4322
4323 #[test]
4324 fn a_chain_advances_on_error_quota_or_an_unusable_answer_only() {
4325 assert!(chain_advances(&Err(anyhow::anyhow!("spawn failed"))));
4326 assert!(chain_advances(&Ok(output("limit", 0, true))));
4327 assert!(chain_advances(&Ok(output("", 0, false))));
4328 assert!(chain_advances(&Ok(output("x", 1, false))));
4329 assert!(!chain_advances(&Ok(output("answer", 0, false))));
4330 }
4331
4332 #[test]
4333 fn claude_context_tokens_are_unknown_because_usage_is_aggregated() {
4334 for out in [
4335 r#"{"result":"ok","num_turns":1,"usage":{"input_tokens":10,"cache_read_input_tokens":3000}}"#,
4336 r#"{"result":"ok","num_turns":3,"usage":{"input_tokens":10}}"#,
4337 r#"{"result":"ok"}"#,
4338 "not json",
4339 ] {
4340 assert_eq!(context_tokens(AgentKind::Claude, out), None, "{out}");
4341 }
4342 }
4343
4344 #[test]
4345 fn opencode_context_tokens_take_the_last_step_finish() {
4346 let out = concat!(
4347 r#"{"type":"step_finish","sessionID":"s","part":{"type":"step-finish","tokens":{"input":100,"output":5,"cache":{"read":1000,"write":50}}}}"#,
4348 "\n",
4349 r#"{"type":"text","part":{"type":"text","text":"hi"}}"#,
4350 "\n",
4351 r#"{"type":"step_finish","sessionID":"s","part":{"type":"step-finish","tokens":{"input":120,"output":9,"cache":{"read":1500}}}}"#,
4352 "\n"
4353 );
4354 assert_eq!(context_tokens(AgentKind::Opencode, out), Some(1620));
4355 let none = r#"{"type":"step_finish","part":{"type":"step-finish"}}"#;
4356 assert_eq!(context_tokens(AgentKind::Opencode, none), None);
4357 assert_eq!(context_tokens(AgentKind::Opencode, ""), None);
4358 }
4359
4360 #[test]
4361 fn agy_context_tokens_are_unknown_because_usage_is_aggregated() {
4362 let out = r#"{"conversation_id":"c","status":"OK","response":"x","usage":{"input_tokens":260113,"cache_read_tokens":2200925}}"#;
4363 assert_eq!(context_tokens(AgentKind::Antigravity, out), None);
4364 }
4365
4366 #[test]
4367 fn codex_context_tokens_are_unknown_because_usage_is_cumulative() {
4368 let out = concat!(
4369 r#"{"type":"turn.completed","usage":{"input_tokens":1000,"cached_input_tokens":900}}"#,
4370 "\n"
4371 );
4372 assert_eq!(context_tokens(AgentKind::Codex, out), None);
4373 }
4374
4375 #[test]
4376 fn omp_context_tokens_come_from_messages_without_an_agent_end() {
4377 let out = concat!(
4378 r#"{"type":"session","id":"s"}"#,
4379 "\n",
4380 r#"{"type":"message_end","message":{"role":"assistant","content":[],"usage":{"input":50,"cacheRead":400,"cacheWrite":10}}}"#,
4381 "\n",
4382 r#"{"type":"turn_end","message":{"role":"assistant","content":[],"usage":{"input":70,"cacheRead":500}}}"#,
4383 "\n"
4384 );
4385 assert_eq!(context_tokens(AgentKind::Omp, out), Some(570));
4386 let user_only = r#"{"type":"message_end","message":{"role":"user","usage":{"input":9}}}"#;
4387 assert_eq!(context_tokens(AgentKind::Omp, user_only), None);
4388 let no_usage = r#"{"type":"message_end","message":{"role":"assistant","content":[]}}"#;
4389 assert_eq!(context_tokens(AgentKind::Omp, no_usage), None);
4390 }
4391
4392 #[test]
4393 fn command_agents_report_no_context_tokens() {
4394 let out = r#"{"usage":{"input_tokens":5}}"#;
4395 assert_eq!(context_tokens(AgentKind::Command, out), None);
4396 }
4397}