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
435#[derive(Debug)]
436pub(crate) struct IsolatedSeatWait(pub(crate) crate::run::ResourceBlock);
437
438impl std::fmt::Display for IsolatedSeatWait {
439 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
440 f.write_str(&self.0.description())
441 }
442}
443
444pub async fn invoke(
452 spec: &AgentSpec,
453 seat: &mut SeatState,
454 inv: &Invocation<'_>,
455) -> Result<AgentOutput> {
456 Box::pin(invoke_on_heap(spec, seat, inv, &mut false)).await
457}
458
459pub(crate) async fn invoke_tracking_spawn(
462 spec: &AgentSpec,
463 seat: &mut SeatState,
464 inv: &Invocation<'_>,
465 spawn_attempted: &mut bool,
466) -> Result<AgentOutput> {
467 Box::pin(invoke_on_heap(spec, seat, inv, spawn_attempted)).await
468}
469
470async fn invoke_on_heap(
471 spec: &AgentSpec,
472 seat: &mut SeatState,
473 inv: &Invocation<'_>,
474 spawn_attempted: &mut bool,
475) -> Result<AgentOutput> {
476 let home = crate::run::home();
477 let (min_free, isolated) = if repository_writer(inv) && repository_seat(inv) {
479 match crate::run::RunState::load_under(inv.run, &home) {
480 Ok(state) => (
481 state.config.disk.min_free_bytes,
482 crate::build_target::isolated(&state.config).then(|| Box::new(state.config)),
483 ),
484 Err(error) if crate::run::is_run_id(inv.run) => {
485 return Err(crate::repo_lock::ResourceBlocked(format!(
486 "cannot confirm saved build policy: {error:#}"
487 ))
488 .into());
489 }
490 Err(_) => (0, None),
491 }
492 } else {
493 (0, None)
494 };
495 let isolated = isolated.as_deref();
496 let resource = |error: anyhow::Error| {
497 crate::repo_lock::ResourceBlocked(format!("{}: {error:#}", crate::build_target::KIND))
498 };
499 let mut build_guard = None;
500 let mut target = None;
501 if let Some(config) = isolated {
502 let path = crate::build_target::resolve(&home, inv.cwd).map_err(resource)?;
503 let head = crate::git::rev_parse(inv.cwd, "HEAD")
504 .await
505 .map_err(resource)?;
506 let owner = crate::cache::Owner::here(inv.run, inv.node, &seat.key, inv.cwd, &head);
507 let started = std::time::Instant::now();
508 build_guard = Some(
509 crate::build_target::acquire(&home, &path, &owner, config)
510 .await
511 .map_err(|error| {
512 let detail = format!("{}: {error:#}", path.display());
513 let timeout = error.is::<crate::cache::WaitTimeout>().then(|| {
514 IsolatedSeatWait(crate::run::ResourceBlock {
515 cause: crate::run::ResourceBlockCause::IsolatedCacheTimeout {
516 target: path.clone(),
517 waited_secs: started.elapsed().as_secs(),
518 limit_secs: config.graph.timeout_resource_wait,
519 },
520 node: inv.node.to_owned(),
521 kind: crate::build_target::KIND.into(),
522 detail: detail.clone(),
523 at: jiff::Timestamp::now(),
524 })
525 });
526 let error = anyhow::Error::new(crate::repo_lock::ResourceBlocked(format!(
527 "{}: {detail}",
528 crate::build_target::KIND
529 )));
530 match timeout {
531 Some(timeout) => error.context(timeout),
532 None => error,
533 }
534 })?,
535 );
536 target = Some((path, head));
537 }
538 let inv = &Invocation {
539 cache_dir: target
540 .as_ref()
541 .map(|(path, _)| path.as_path())
542 .or(inv.cache_dir.filter(|_| inv.allow_write)),
543 ..inv.clone()
544 };
545 let lease = if repository_seat(inv) {
550 crate::repo_lock::SeatLease::for_checkout(inv.cwd, inv.allow_write, inv.coordination)
551 .await?
552 } else {
553 None
554 };
555 let inv = &Invocation {
556 timeout: spec.turn_timeout(inv.timeout),
557 ..inv.clone()
558 };
559 let mut outputs = Vec::new();
560 if repository_writer(inv) {
561 let mut paths = vec![inv.cwd.to_owned()];
562 if let Some(cache) = inv.cache_dir {
563 paths.push(cache.to_owned());
564 }
565 let admit = if isolated.is_some() {
566 crate::retention::OutputLease::admit_isolated
567 } else {
568 crate::retention::OutputLease::admit
569 };
570 outputs
571 .extend(admit(&home, &paths, min_free).map_err(|e| {
572 crate::repo_lock::ResourceBlocked(format!("disk admission: {e:#}"))
573 })?);
574 }
575 if repository_seat(inv) {
576 if let Some(guard) = crate::retention::OutputLease::borrow(inv.cwd).map_err(|e| {
577 crate::repo_lock::ResourceBlocked(format!("worktree output ownership: {e:#}"))
578 })? {
579 outputs.push(guard);
580 }
581 if let Some(cache) = inv.cache_dir {
582 outputs.push(crate::retention::OutputLease::cache(
583 &crate::run::home(),
584 cache,
585 false,
586 )?);
587 }
588 }
589 if let (Some(config), Some((path, head))) = (isolated, &target) {
590 crate::build_target::ensure_fresh(&home, path, inv.cwd, head, config)
591 .with_context(|| format!("target {}", path.display()))
592 .map_err(resource)?;
593 crate::cache::invalidate_identity(&home, path);
595 tracing::info!(target = %path.display(), seat = %seat.key, "admitted isolated build cache");
596 }
597
598 let mut prompt = inv.prompt.to_owned();
599 if inv.node == crate::queue::CHAT_NODE {
600 prompt.push_str("\n\n");
601 prompt.push_str(crate::prompt::CHAT_FOLLOW_THROUGH);
602 }
603 if let Some(lease) = lease.as_ref().filter(|lease| lease.delegated) {
604 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()));
605 }
606 let home = repository_writer(inv).then(crate::run::home);
609 let mut writable = inv.writable.to_vec();
610 if let Some(home) = &home {
611 for root in worktree_writable_roots(inv.cwd, home).await? {
612 if !writable.contains(&root) {
613 writable.push(root);
614 }
615 }
616 }
617 if let Some((path, _)) = &target {
618 writable.push(path.clone());
619 prompt.push_str("\n\nUse the launcher-provided Cargo target and Cargo command. Do not set a different target or bypass the managed Cargo launcher.");
620 }
621 if repository_writer(inv) {
622 prompt.push_str("\n\n");
623 prompt.push_str(&editing_access_note(inv.fetched_base));
624 }
625 let inv = &Invocation {
626 writable: &writable,
627 prompt: &prompt,
628 ..inv.clone()
629 };
630 tokio::fs::create_dir_all(inv.artifacts)
631 .await
632 .with_context(|| format!("create {}", inv.artifacts.display()))?;
633 let prompt_path = inv.artifacts.join(format!("{}.prompt.md", inv.stem));
634 tokio::fs::write(&prompt_path, inv.prompt)
635 .await
636 .with_context(|| format!("write {}", prompt_path.display()))?;
637
638 let omp_session = if spec.kind == AgentKind::Omp {
639 Some(OmpSession::prepare(
640 spec,
641 seat,
642 inv.sessions,
643 crate::run::home,
644 )?)
645 } else {
646 None
647 };
648 let plan = build_command(spec, seat, inv, &prompt_path)?;
649 tracing::debug!(seat = %seat.key, agent = %spec.id, argv = ?plan.logged_argv(), "spawning agent");
650 tokio::fs::write(
652 inv.artifacts.join(format!("{}.access.json", inv.stem)),
653 serde_json::to_vec_pretty(&serde_json::json!({
654 "launcher_version": env!("CARGO_PKG_VERSION"),
655 "kind": spec.kind,
656 "allow_write": inv.allow_write,
657 "unsandboxed": repository_writer(inv),
658 "writable_roots": inv.writable,
659 "isolated_build_target": target.as_ref().map(|(path, _)| path),
660 "fetched_base": inv.fetched_base,
661 }))?,
662 )
663 .await
664 .context("write seat access evidence")?;
665
666 let started = Instant::now();
667 let child_path = spec
670 .env
671 .iter()
672 .find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
673 .map(|(_, v)| std::ffi::OsString::from(v))
674 .or_else(|| std::env::var_os("PATH"))
675 .unwrap_or_default();
676 let program = crate::config::find_program_on(&plan.argv[0], &child_path).map_or_else(
677 || plan.argv[0].clone().into(),
678 std::path::PathBuf::into_os_string,
679 );
680 let mut cmd = Command::new(program);
681 cmd.args(plan.args(omp_session.as_ref().and_then(|session| session.dir(seat))))
682 .current_dir(inv.cwd)
683 .envs(&spec.env)
684 .env("MAGI_SEAT", &seat.key)
685 .env("MAGI_TURN", seat.turns.to_string())
686 .env("MAGI_RUN", inv.run)
687 .env("MAGI_NODE", inv.node)
688 .env("MAGI_PROMPT_FILE", &prompt_path)
689 .env("MAGI_ALLOW_WRITE", if inv.allow_write { "1" } else { "0" })
690 .env("GIT_TERMINAL_PROMPT", "0")
691 .stdin(if plan.stdin.is_some() {
692 Stdio::piped()
693 } else {
694 Stdio::null()
695 })
696 .stdout(Stdio::piped())
697 .stderr(Stdio::piped())
698 .kill_on_drop(true)
699 .quiet();
702 if let Some(session) = &omp_session {
703 session.isolate_terminal_history(&mut cmd, seat);
704 }
705 crate::incremental::default_environment(&mut cmd);
706 if repository_writer(inv) {
707 crate::incremental::configure(&mut cmd, inv.cwd)?;
708 }
709 if let Some(home) = home {
710 cmd.env("MAGI_HOME", std::fs::canonicalize(home)?);
713 }
714 if target.is_none() {
715 crate::build_target::command::clear(&mut cmd)?;
716 }
717 if let Some((path, _)) = &target {
718 crate::build_target::command::configure(&mut cmd, path).map_err(resource)?;
719 } else if let Some(cache) = inv.cache_dir {
720 cmd.env("CARGO_TARGET_DIR", cache);
723 } else {
724 cmd.env_remove("CARGO_TARGET_DIR");
732 cmd.env_remove("CARGO_BUILD_TARGET_DIR")
733 .env_remove("CARGO_BUILD_BUILD_DIR");
734 }
735
736 #[cfg(any(unix, windows))]
737 let _chat_controls = {
738 use crate::chat_control::bridge::{self, Bridge};
739 bridge::clear_environment(&mut cmd);
742 if matches!(
743 crate::chat_goal::current_source(),
744 crate::chat_goal::Source::Standing(_)
745 ) {
746 cmd.env(crate::chat_control::standing::ENV, "1");
747 }
748 let bridge = if inv.node == crate::queue::CHAT_NODE {
749 crate::run::try_home().and_then(|home| {
750 match Bridge::start(&home, inv.run, inv.artifacts) {
751 Ok(bridge) => Some(bridge),
752 Err(error) => {
753 tracing::warn!(%error, "chat controls unavailable; continuing conversation");
754 None
755 }
756 }
757 })
758 } else {
759 None
760 };
761 if let Some(bridge) = &bridge {
762 cmd.env("MAGI_HOME", std::fs::canonicalize(crate::run::home())?);
766 bridge.attach(&mut cmd);
767 }
768 bridge
769 };
770
771 let spawn = if build_guard.is_some() {
772 crate::seat_process::Running::spawn_build
773 } else {
774 crate::seat_process::Running::spawn
775 };
776 *spawn_attempted = true;
777 let spawned = spawn(cmd, lease, outputs)
778 .with_context(|| format!("spawn `{}` for seat {}", plan.argv[0], seat.key));
779 let mut running = if isolated.is_some() {
780 spawned.map_err(resource)?
781 } else {
782 spawned?
783 };
784 if let (Some(body), Some(mut sink)) = (plan.stdin.clone(), running.child().stdin.take()) {
788 tokio::spawn(async move {
789 sink.write_all(body.as_bytes()).await.ok();
790 sink.shutdown().await.ok();
791 });
792 }
793
794 let (out_buf, out_reader) = drain(running.child().stdout.take());
811 let (err_buf, err_reader) = drain(running.child().stderr.take());
812
813 #[cfg(all(test, unix))]
814 let min_free = test_watchdog::floor(inv.run, min_free);
815 let mut paths = vec![inv.cwd.to_owned()];
816 if let Some(cache) = inv.cache_dir {
817 paths.push(cache.to_owned());
818 }
819 let mut pressure = None;
820 let waited = tokio::select! {
821 waited = tokio::time::timeout(inv.timeout, running.child().wait()) => Some(waited),
822 reason = crate::retention::emergency(paths, min_free, isolated.is_some()) => {
823 pressure = Some(reason);
824 None
825 }
826 };
827 let (code, timed_out) = match waited {
828 Some(Ok(res)) => {
829 let status = res.with_context(|| format!("wait for seat {}", seat.key))?;
830 (status.code(), false)
831 }
832 Some(Err(_)) | None => {
833 if let Some(reason) = &pressure {
834 tracing::warn!(seat = %seat.key, %reason, "agent execution interrupted");
835 } else {
836 tracing::warn!(seat = %seat.key, secs = inv.timeout.as_secs(), "agent timed out");
837 }
838 if !running.coordinated() {
840 running
841 .child()
842 .kill()
843 .await
844 .context("stop timed-out seat")?;
845 }
846 (None, true)
847 }
848 };
849 running.finish().await;
850
851 let stdout = collect(&out_buf, out_reader, PIPE_GRACE).await;
856 let stderr = collect(&err_buf, err_reader, PIPE_GRACE).await;
857
858 let out_path = inv.artifacts.join(format!("{}.out", inv.stem));
859 let err_path = inv.artifacts.join(format!("{}.err", inv.stem));
860 tokio::fs::write(&out_path, &stdout).await.ok();
861 tokio::fs::write(&err_path, &stderr).await.ok();
862 if let Some(reason) = pressure {
863 return Err(
864 anyhow::Error::new(crate::repo_lock::ResourceBlocked(reason.clone()))
865 .context(ExecutionInterrupted(reason)),
866 );
867 }
868
869 if code != Some(0)
870 && (stdout.contains(crate::incremental::BLOCKED)
871 || stderr.contains(crate::incremental::BLOCKED))
872 {
873 let detail = if stderr.contains(crate::incremental::BLOCKED) {
874 &stderr
875 } else {
876 &stdout
877 };
878 return Err(crate::repo_lock::ResourceBlocked(tail_chars(detail, 2000)).into());
879 }
880
881 let mut extracted = extract(spec.kind, &stdout);
882 if spec.kind == AgentKind::Antigravity && extracted.quota.is_none() {
883 extracted.quota = agy_quota(&stdout, &stderr);
884 }
885 if let Some(quota) = &mut extracted.quota {
886 quota.agent.clone_from(&spec.id);
887 if quota.cause == QuotaCause::Authentication {
888 let _ = crate::notices::Notices::open().raise(crate::notices::Notice::warn(
889 &format!("agent-authentication:{}", spec.id),
890 format!("Agent `{}` cannot authenticate. Re-authenticate this agent, then resume the held task.", spec.id),
891 ));
892 }
893 extracted.dropped = None;
896 tracing::warn!(
897 seat = %seat.key,
898 agent = %spec.id,
899 reset = ?quota.reset,
900 cause = ?quota.cause,
901 "agent needs machine-side recovery"
902 );
903 }
904 if let Some(omp_session) = omp_session {
905 omp_session.record(seat, extracted.session, code == Some(0))?;
906 } else if let Some(session) = extracted.session {
907 match spec.kind {
908 AgentKind::Claude => seat.claude_session = Some(session),
909 AgentKind::Opencode | AgentKind::Antigravity | AgentKind::Codex => {
910 seat.captured_session = Some(session);
911 }
912 AgentKind::Command | AgentKind::Omp => {}
913 }
914 }
915 if let Some(status) = &extracted.status
916 && !status.eq_ignore_ascii_case("success")
917 {
918 tracing::warn!(seat = %seat.key, status = %status, "agent reported a non-success status");
919 }
920 let text = if extracted.text.trim().is_empty() {
921 if stdout.trim().is_empty() {
923 stderr.trim().to_owned()
924 } else {
925 stdout.trim().to_owned()
926 }
927 } else {
928 extracted.text
929 };
930 seat.turns += 1;
931
932 Ok(AgentOutput {
933 text,
934 exit_code: code,
935 timed_out,
936 duration_ms: started.elapsed().as_millis() as u64,
937 artifacts: vec![
938 file_name(&prompt_path),
939 file_name(&out_path),
940 file_name(&err_path),
941 ],
942 quota: extracted.quota,
943 dropped: extracted.dropped,
944 commands: extracted.commands,
945 context_tokens: extracted.context_tokens,
946 })
947}
948
949fn file_name(p: &Path) -> String {
950 p.file_name()
951 .unwrap_or_default()
952 .to_string_lossy()
953 .into_owned()
954}
955
956enum OmpSession {
957 Fresh(PathBuf),
958 Resume,
959}
960
961impl OmpSession {
962 fn prepare(
963 spec: &AgentSpec,
964 seat: &SeatState,
965 sessions: bool,
966 home: impl FnOnce() -> PathBuf,
967 ) -> Result<Self> {
968 let resume = has_session(AgentKind::Omp, seat, sessions);
969 if resume && seat.omp_session_dir.is_none() {
970 return Ok(Self::Resume);
972 }
973 for arg in &spec.extra_args {
974 let flag = arg.split_once('=').map_or(arg.as_str(), |(flag, _)| flag);
975 if matches!(
976 flag,
977 "--session-dir"
978 | "--no-session"
979 | "--resume"
980 | "--session"
981 | "--fork"
982 | "--restore"
983 | "--continue"
984 | "--from-claude"
985 | "--from-codex"
986 | "-r"
987 | "-c"
988 ) {
989 bail!("omp extra_args cannot set {flag} for isolated sessions");
990 }
991 }
992 if resume {
993 let dir = seat.omp_session_dir.as_ref().expect("managed resume");
994 anyhow::ensure!(
995 dir.is_absolute(),
996 "saved omp session directory is not absolute"
997 );
998 std::fs::read_dir(dir)
999 .with_context(|| format!("open saved omp session directory {}", dir.display()))?;
1000 return Ok(Self::Resume);
1001 }
1002
1003 let root = std::path::absolute(home().join("agent-sessions").join("omp"))
1004 .context("resolve absolute omp session store")?;
1005 anyhow::ensure!(
1007 root.to_str().is_some(),
1008 "omp session store is not valid Unicode"
1009 );
1010 std::fs::create_dir_all(&root)
1011 .with_context(|| format!("create omp session store {}", root.display()))?;
1012 let ids =
1013 crate::id_reserve::IdSource::new(|| SplitMix64::new(crate::rng::entropy()).uuid_v4());
1014 let id = ids.reserve(None, "omp session directory", |id| {
1015 crate::id_reserve::create_dir(&root.join(id))
1016 })?;
1017 Ok(Self::Fresh(root.join(id)))
1018 }
1019
1020 fn dir<'a>(&'a self, seat: &'a SeatState) -> Option<&'a Path> {
1021 match self {
1022 Self::Fresh(dir) => Some(dir),
1023 Self::Resume => seat.omp_session_dir.as_deref(),
1024 }
1025 }
1026
1027 fn isolate_terminal_history(&self, cmd: &mut Command, seat: &SeatState) {
1028 if self.dir(seat).is_none() {
1029 return;
1030 }
1031 for key in [
1035 "ZELLIJ_PANE_ID",
1036 "TMUX_PANE",
1037 "CMUX_SURFACE_ID",
1038 "KITTY_WINDOW_ID",
1039 "WEZTERM_PANE",
1040 "TERM_SESSION_ID",
1041 "WT_SESSION",
1042 ] {
1043 cmd.env_remove(key);
1044 }
1045 }
1046
1047 fn record(self, seat: &mut SeatState, reported: Option<String>, success: bool) -> Result<()> {
1048 let reported = reported.filter(|id| !id.is_empty());
1049 match self {
1050 Self::Resume if seat.omp_session_dir.is_none() => {
1051 if let Some(id) = reported {
1053 seat.captured_session = Some(id);
1054 }
1055 }
1056 Self::Resume => {
1057 if let Some(id) = reported {
1058 let previous = seat.captured_session.as_deref().expect("managed resume");
1059 let dir = seat.omp_session_dir.as_deref().expect("managed resume");
1060 if previous != id {
1061 anyhow::ensure!(
1062 omp_continues(dir, previous, &id)?,
1063 "omp resumed a different session than requested"
1064 );
1065 seat.captured_session = Some(id);
1066 }
1067 } else if success {
1068 bail!("omp did not confirm the requested session; see the seat output");
1071 }
1072 }
1073 Self::Fresh(dir) => {
1074 if let Some(id) = reported {
1075 seat.captured_session = Some(id);
1076 seat.omp_session_dir = Some(dir);
1077 } else if success {
1078 bail!("omp did not report a new session id; see the seat output");
1079 }
1080 }
1081 }
1082 Ok(())
1083 }
1084}
1085
1086fn omp_continues(dir: &Path, previous: &str, reported: &str) -> Result<bool> {
1089 use std::io::{BufRead as _, BufReader, Read as _};
1090
1091 let mut parents = BTreeMap::new();
1092 let mut line = Vec::new();
1093 for entry in std::fs::read_dir(dir).context("read omp continuation directory")? {
1094 let entry = entry?;
1095 let path = entry.path();
1096 if path.extension() != Some(OsStr::new("jsonl")) || !entry.file_type()?.is_file() {
1097 continue;
1098 }
1099 line.clear();
1100 BufReader::new(std::fs::File::open(path)?)
1102 .take(64 * 1024)
1103 .read_until(b'\n', &mut line)?;
1104 if !line.ends_with(b"\n") {
1105 continue;
1106 }
1107 let Ok(header) = serde_json::from_slice::<serde_json::Value>(&line) else {
1108 continue;
1109 };
1110 if header["type"].as_str() != Some("session") {
1111 continue;
1112 }
1113 if let Some(id) = header["id"].as_str() {
1114 let parent = header["continuationOf"].as_str().map(str::to_owned);
1115 if parents.insert(id.to_owned(), parent).is_some() {
1116 return Ok(false);
1117 }
1118 }
1119 }
1120
1121 let mut current = reported.to_owned();
1122 while let Some(Some(parent)) = parents.remove(¤t) {
1124 if parent == previous {
1125 return Ok(true);
1126 }
1127 current = parent;
1128 }
1129 Ok(false)
1130}
1131
1132#[derive(Debug)]
1134struct Plan {
1135 argv: Vec<String>,
1136 stdin: Option<String>,
1137}
1138
1139impl Plan {
1140 fn args<'a>(&'a self, omp_dir: Option<&'a Path>) -> impl Iterator<Item = &'a OsStr> {
1142 omp_dir
1143 .into_iter()
1144 .flat_map(|dir| [OsStr::new("--session-dir"), dir.as_os_str()])
1145 .chain(self.argv[1..].iter().map(OsStr::new))
1146 }
1147
1148 fn logged_argv(&self) -> Vec<&str> {
1151 let mut settings_value = false;
1152 self.argv
1153 .iter()
1154 .map(|arg| {
1155 if settings_value {
1156 settings_value = false;
1157 "[redacted]"
1158 } else if arg == "--settings" {
1159 settings_value = true;
1160 arg.as_str()
1161 } else if arg.starts_with("--settings=") {
1162 "--settings=[redacted]"
1163 } else {
1164 arg.as_str()
1165 }
1166 })
1167 .collect()
1168 }
1169}
1170
1171fn pointer(kind: AgentKind, prompt_path: &Path) -> String {
1182 if matches!(kind, AgentKind::Antigravity) {
1183 return format!("@{}", prompt_path.display());
1184 }
1185 format!(
1186 "Read the file at {} and follow every instruction in it exactly. That \
1187 file is your complete task description; this message contains nothing \
1188 else.",
1189 prompt_path.display()
1190 )
1191}
1192
1193fn build_command(
1194 spec: &AgentSpec,
1195 seat: &SeatState,
1196 inv: &Invocation<'_>,
1197 prompt_path: &Path,
1198) -> Result<Plan> {
1199 let mut argv: Vec<String> = Vec::new();
1200 let mut stdin: Option<String> = None;
1201 let delivery = spec.delivery();
1202 let resuming = has_session(spec.kind, seat, inv.sessions);
1203
1204 match spec.kind {
1205 AgentKind::Claude => {
1206 argv.push("claude".to_owned());
1211 argv.push("-p".to_owned());
1212 argv.push("--output-format".to_owned());
1213 argv.push("json".to_owned());
1214 if let Some(m) = &spec.model {
1215 argv.push("--model".to_owned());
1216 argv.push(m.clone());
1217 }
1218 if inv.sessions {
1219 let uuid = seat
1220 .claude_session
1221 .as_deref()
1222 .context("claude seat is missing its session uuid")?;
1223 argv.push(if resuming { "--resume" } else { "--session-id" }.to_owned());
1224 argv.push(uuid.to_owned());
1225 }
1226 argv.push("--permission-mode".to_owned());
1227 argv.push("bypassPermissions".to_owned());
1228 if !inv.allow_write {
1229 argv.push("--disallowed-tools".to_owned());
1230 argv.push("Edit,Write,MultiEdit,NotebookEdit".to_owned());
1231 }
1232 }
1233 AgentKind::Opencode => {
1234 argv.push("opencode".to_owned());
1238 argv.push("run".to_owned());
1239 argv.push("--format".to_owned());
1240 argv.push("json".to_owned());
1241 argv.push("--dir".to_owned());
1242 argv.push(inv.cwd.to_string_lossy().into_owned());
1243 argv.push("--auto".to_owned());
1252 if let Some(m) = &spec.model {
1253 argv.push("-m".to_owned());
1254 argv.push(m.clone());
1255 }
1256 if resuming {
1257 argv.push("-s".to_owned());
1258 argv.push(
1259 seat.captured_session
1260 .clone()
1261 .expect("has_session checked the id is present"),
1262 );
1263 }
1264 }
1265 AgentKind::Antigravity => {
1266 argv.push("agy".to_owned());
1267 argv.push("--output-format".to_owned());
1268 argv.push("json".to_owned());
1269 argv.push("--print-timeout".to_owned());
1272 argv.push(format!("{}s", inv.timeout.as_secs()));
1273 argv.push("--mode".to_owned());
1274 argv.push(
1275 if inv.allow_write {
1276 "accept-edits"
1277 } else {
1278 "plan"
1279 }
1280 .to_owned(),
1281 );
1282 if inv.allow_write {
1283 argv.push("--dangerously-skip-permissions".to_owned());
1284 }
1285 if let Some(m) = &spec.model {
1286 argv.push("--model".to_owned());
1287 argv.push(m.clone());
1288 }
1289 if resuming {
1290 argv.push("--conversation".to_owned());
1291 argv.push(
1292 seat.captured_session
1293 .clone()
1294 .expect("has_session checked the id is present"),
1295 );
1296 }
1297 let mut add_dirs: Vec<String> = Vec::new();
1307 if delivery == Delivery::File || !inv.attachments.is_empty() {
1308 add_dirs.push(inv.artifacts.to_string_lossy().into_owned());
1309 }
1310 for path in inv.attachments {
1311 let Some(parent) = path.parent() else {
1312 continue;
1313 };
1314 if parent.starts_with(inv.artifacts) {
1315 continue;
1316 }
1317 let dir = parent.to_string_lossy().into_owned();
1318 if !add_dirs.contains(&dir) {
1319 add_dirs.push(dir);
1320 }
1321 }
1322 if inv.allow_write {
1323 for path in inv.writable {
1324 let dir = path.to_string_lossy().into_owned();
1325 if !add_dirs.contains(&dir) {
1326 add_dirs.push(dir);
1327 }
1328 }
1329 }
1330 for dir in add_dirs {
1331 argv.push("--add-dir".to_owned());
1332 argv.push(dir);
1333 }
1334 }
1335 AgentKind::Codex => {
1336 argv.push("codex".to_owned());
1342 argv.push("exec".to_owned());
1343 argv.push("--json".to_owned());
1344 argv.push("--skip-git-repo-check".to_owned());
1347 argv.push("-C".to_owned());
1348 argv.push(inv.cwd.to_string_lossy().into_owned());
1349 if repository_writer(inv) {
1359 argv.push("--dangerously-bypass-approvals-and-sandbox".to_owned());
1360 } else {
1361 argv.push("--sandbox".to_owned());
1362 argv.push(
1363 if inv.allow_write {
1364 "workspace-write"
1365 } else {
1366 "read-only"
1367 }
1368 .to_owned(),
1369 );
1370 argv.push("-c".to_owned());
1373 argv.push("approval_policy=\"never\"".to_owned());
1374 if inv.allow_write && !inv.writable.is_empty() {
1375 let roots: Vec<String> = inv
1376 .writable
1377 .iter()
1378 .map(|p| p.to_string_lossy().into_owned())
1379 .collect();
1380 argv.push("-c".to_owned());
1381 argv.push(format!(
1382 "sandbox_workspace_write.writable_roots={}",
1383 serde_json::to_string(&roots).unwrap_or_else(|_| "[]".to_owned())
1384 ));
1385 }
1386 }
1387 if let Some(m) = &spec.model {
1388 argv.push("-m".to_owned());
1389 argv.push(m.clone());
1390 }
1391 if resuming {
1397 argv.push("resume".to_owned());
1398 argv.push(
1399 seat.captured_session
1400 .clone()
1401 .expect("has_session checked the id is present"),
1402 );
1403 }
1404 }
1405 AgentKind::Omp => {
1406 argv.push("omp".to_owned());
1410 argv.push("-p".to_owned());
1411 argv.push("--mode=json".to_owned());
1412 argv.push("--auto-approve".to_owned());
1422 if let Some(m) = &spec.model {
1423 argv.push("--model".to_owned());
1424 argv.push(m.clone());
1425 }
1426 if resuming {
1432 argv.push("--resume".to_owned());
1433 argv.push(
1434 seat.captured_session
1435 .clone()
1436 .expect("has_session checked the id is present"),
1437 );
1438 }
1439 }
1440 AgentKind::Command => {
1441 if spec.command.is_empty() {
1446 bail!("agent `{}` has kind = \"command\" but no command", spec.id);
1447 }
1448 let vars: BTreeMap<&str, String> = BTreeMap::from([
1449 ("{prompt_file}", prompt_path.to_string_lossy().into_owned()),
1450 ("{cwd}", inv.cwd.to_string_lossy().into_owned()),
1451 ("{label}", seat.key.clone()),
1452 ("{session}", seat.claude_session.clone().unwrap_or_default()),
1453 ]);
1454 for raw in &spec.command {
1455 let mut arg = raw.clone();
1456 for (k, v) in &vars {
1457 if arg.contains(k) {
1458 arg = arg.replace(k, v);
1459 }
1460 }
1461 argv.push(arg);
1462 }
1463 }
1464 }
1465
1466 argv.extend(spec.extra_args.iter().cloned());
1467
1468 if spec.kind == AgentKind::Antigravity {
1471 argv.push("-p".to_owned());
1472 }
1473 if spec.kind == AgentKind::Codex && delivery == Delivery::Stdin {
1476 argv.push("-".to_owned());
1477 }
1478 match delivery {
1479 Delivery::Stdin if spec.kind == AgentKind::Antigravity => {
1480 argv.push(pointer(spec.kind, prompt_path));
1482 }
1483 Delivery::Stdin => stdin = Some(inv.prompt.to_owned()),
1484 Delivery::Argv => argv.push(inv.prompt.to_owned()),
1485 Delivery::File => argv.push(pointer(spec.kind, prompt_path)),
1486 }
1487
1488 Ok(Plan { argv, stdin })
1489}
1490
1491#[derive(Debug, Default)]
1493struct Extracted {
1494 text: String,
1495 session: Option<String>,
1496 status: Option<String>,
1497 quota: Option<Quota>,
1498 dropped: Option<Dropped>,
1499 commands: Vec<CommandEvidence>,
1500 context_tokens: Option<u64>,
1501}
1502
1503fn extract(kind: AgentKind, stdout: &str) -> Extracted {
1505 let mut extracted = extract_answer(kind, stdout);
1506 extracted.context_tokens = context_tokens(kind, stdout);
1507 extracted
1508}
1509
1510fn uint(v: &serde_json::Value, key: &str) -> Option<u64> {
1512 v.get(key).and_then(serde_json::Value::as_u64)
1513}
1514
1515fn input_side(usage: &serde_json::Value, input: &[&str], cache: &[&str]) -> Option<u64> {
1520 let first = |keys: &[&str]| keys.iter().find_map(|k| uint(usage, k));
1521 let base = first(input)?;
1522 let cached: u64 = cache.iter().filter_map(|k| uint(usage, k)).sum();
1523 Some(base.saturating_add(cached))
1524}
1525
1526fn context_tokens(kind: AgentKind, stdout: &str) -> Option<u64> {
1547 use serde_json::Value;
1548 let lines = || {
1549 stdout
1550 .lines()
1551 .filter_map(|l| serde_json::from_str::<Value>(l.trim()).ok())
1552 };
1553 match kind {
1554 AgentKind::Claude => None,
1555 AgentKind::Opencode => lines()
1556 .filter(|v| {
1557 v.get("type").and_then(|t| t.as_str()) == Some("step_finish")
1559 || v.get("part")
1560 .and_then(|p| p.get("type"))
1561 .and_then(|t| t.as_str())
1562 == Some("step-finish")
1563 })
1564 .filter_map(|v| {
1565 let tokens = v.get("part")?.get("tokens")?;
1566 let base = uint(tokens, "input")?;
1567 let cache = tokens.get("cache");
1568 let cached = ["read", "write"]
1569 .iter()
1570 .filter_map(|k| cache.and_then(|c| uint(c, k)))
1571 .sum::<u64>();
1572 Some(base.saturating_add(cached))
1573 })
1574 .next_back(),
1575 AgentKind::Antigravity => None,
1576 AgentKind::Codex => None,
1577 AgentKind::Omp => lines()
1578 .flat_map(|v| {
1579 match v.get("type").and_then(|t| t.as_str()) {
1582 Some("agent_end") => v
1583 .get("messages")
1584 .and_then(|m| m.as_array())
1585 .cloned()
1586 .unwrap_or_default(),
1587 Some("turn_end") | Some("message_end") => {
1588 v.get("message").cloned().into_iter().collect()
1589 }
1590 _ => Vec::new(),
1591 }
1592 })
1593 .filter(|m| m.get("role").and_then(|r| r.as_str()) == Some("assistant"))
1594 .filter_map(|m| {
1595 input_side(
1596 m.get("usage")?,
1597 &["input", "input_tokens"],
1598 &[
1599 "cacheRead",
1600 "cacheWrite",
1601 "cache_read_tokens",
1602 "cache_write_tokens",
1603 ],
1604 )
1605 })
1606 .next_back(),
1607 AgentKind::Command => None,
1608 }
1609}
1610
1611pub(crate) fn answer_text(kind: AgentKind, stdout: &str) -> String {
1614 extract_answer(kind, stdout).text
1615}
1616
1617fn extract_answer(kind: AgentKind, stdout: &str) -> Extracted {
1618 match kind {
1619 AgentKind::Claude => {
1620 let Ok(v) = serde_json::from_str::<serde_json::Value>(stdout.trim()) else {
1621 return Extracted {
1622 text: stdout.trim().to_owned(),
1623 ..Extracted::default()
1624 };
1625 };
1626 Extracted {
1627 text: v
1628 .get("result")
1629 .and_then(|r| r.as_str())
1630 .unwrap_or_default()
1631 .to_owned(),
1632 session: v
1633 .get("session_id")
1634 .and_then(|s| s.as_str())
1635 .map(str::to_owned),
1636 status: v.get("is_error").and_then(|e| e.as_bool()).map(|e| {
1637 if e {
1638 "error".to_owned()
1639 } else {
1640 "success".to_owned()
1641 }
1642 }),
1643 quota: claude_quota(&v),
1644 dropped: None,
1647 commands: Vec::new(),
1648 context_tokens: None,
1649 }
1650 }
1651 AgentKind::Opencode => {
1652 let mut text = String::new();
1654 let mut session = None;
1655 for line in stdout.lines() {
1656 let Ok(v) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
1657 continue;
1658 };
1659 if session.is_none() {
1660 session = v
1661 .get("sessionID")
1662 .and_then(|s| s.as_str())
1663 .map(str::to_owned);
1664 }
1665 let part = v.get("part").unwrap_or(&serde_json::Value::Null);
1666 if part.get("type").and_then(|t| t.as_str()) == Some("text")
1667 && let Some(t) = part.get("text").and_then(|t| t.as_str())
1668 {
1669 if !text.is_empty() {
1670 text.push('\n');
1671 }
1672 text.push_str(t);
1673 }
1674 }
1675 Extracted {
1676 text,
1677 session,
1678 status: None,
1679 quota: None,
1680 dropped: None,
1681 commands: Vec::new(),
1682 context_tokens: None,
1683 }
1684 }
1685 AgentKind::Antigravity => {
1686 let obj = stdout
1689 .lines()
1690 .rev()
1691 .find_map(|l| serde_json::from_str::<serde_json::Value>(l.trim()).ok());
1692 let Some(v) = obj else {
1693 return Extracted {
1694 text: stdout.trim().to_owned(),
1695 ..Extracted::default()
1696 };
1697 };
1698 Extracted {
1699 text: v
1700 .get("response")
1701 .and_then(|r| r.as_str())
1702 .unwrap_or_default()
1703 .trim()
1704 .to_owned(),
1705 session: v
1706 .get("conversation_id")
1707 .and_then(|s| s.as_str())
1708 .map(str::to_owned),
1709 status: v.get("status").and_then(|s| s.as_str()).map(str::to_owned),
1710 quota: None,
1711 dropped: dropped_stream(&v),
1712 commands: Vec::new(),
1713 context_tokens: None,
1714 }
1715 }
1716 AgentKind::Codex => {
1717 let mut text = String::new();
1739 let mut session = None;
1740 let mut status = None;
1741 let mut commands = Vec::new();
1742 for line in stdout.lines() {
1743 let Ok(v) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
1744 continue;
1745 };
1746 match v.get("type").and_then(|t| t.as_str()) {
1747 Some("thread.started") => {
1748 session = v
1749 .get("thread_id")
1750 .and_then(|s| s.as_str())
1751 .map(str::to_owned);
1752 }
1753 Some("item.completed") => {
1754 let item = v.get("item").unwrap_or(&serde_json::Value::Null);
1755 match item.get("type").and_then(|t| t.as_str()) {
1756 Some("agent_message") => {
1757 if let Some(t) = item.get("text").and_then(|t| t.as_str()) {
1758 text = t.trim().to_owned();
1759 }
1760 }
1761 Some("command_execution") => {
1762 commands.push(command_evidence(item));
1763 }
1764 _ => {}
1765 }
1766 }
1767 Some("turn.completed") => status = Some("success".to_owned()),
1768 Some("turn.failed") => status = Some("error".to_owned()),
1769 _ => {}
1770 }
1771 }
1772 Extracted {
1773 text,
1774 session,
1775 status,
1776 quota: codex_quota(stdout),
1777 dropped: None,
1778 commands,
1779 context_tokens: None,
1780 }
1781 }
1782 AgentKind::Omp => {
1783 let mut text = String::new();
1804 let mut session = None;
1805 for line in stdout.lines() {
1806 let Ok(v) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
1807 continue;
1808 };
1809 if v.get("type").and_then(|t| t.as_str()) == Some("session") {
1810 session = v.get("id").and_then(|s| s.as_str()).map(str::to_owned);
1811 continue;
1812 }
1813 let messages: Vec<&serde_json::Value> = match v.get("type").and_then(|t| t.as_str())
1817 {
1818 Some("agent_end") => v
1819 .get("messages")
1820 .and_then(|m| m.as_array())
1821 .map(|m| m.iter().collect())
1822 .unwrap_or_default(),
1823 Some("turn_end") | Some("message_end") => {
1824 v.get("message").into_iter().collect()
1825 }
1826 _ => continue,
1827 };
1828 for message in messages {
1829 if message.get("role").and_then(|r| r.as_str()) != Some("assistant") {
1830 continue;
1831 }
1832 let Some(parts) = message.get("content").and_then(|c| c.as_array()) else {
1833 continue;
1834 };
1835 for part in parts {
1836 if part.get("type").and_then(|t| t.as_str()) != Some("text") {
1837 continue;
1838 }
1839 if let Some(t) = part.get("text").and_then(|t| t.as_str())
1840 && !t.trim().is_empty()
1841 {
1842 text = t.trim().to_owned();
1843 }
1844 }
1845 }
1846 }
1847 Extracted {
1848 text,
1849 session,
1850 status: None,
1851 quota: None,
1852 dropped: None,
1853 commands: Vec::new(),
1854 context_tokens: None,
1855 }
1856 }
1857 AgentKind::Command => {
1858 let parsed = serde_json::from_str::<serde_json::Value>(stdout.trim()).ok();
1863 let quota = parsed.as_ref().and_then(claude_quota);
1864 let dropped = parsed.as_ref().and_then(dropped_stream);
1867 Extracted {
1868 text: stdout.trim().to_owned(),
1869 session: None,
1870 status: None,
1871 quota,
1872 dropped,
1873 commands: Vec::new(),
1874 context_tokens: None,
1875 }
1876 }
1877 }
1878}
1879
1880fn command_evidence(item: &serde_json::Value) -> CommandEvidence {
1887 let description = match item.get("command") {
1888 Some(serde_json::Value::String(s)) => s.clone(),
1889 Some(serde_json::Value::Array(parts)) => parts
1890 .iter()
1891 .filter_map(|p| p.as_str())
1892 .collect::<Vec<_>>()
1893 .join(" "),
1894 _ => String::new(),
1895 };
1896 let result_summary = item
1897 .get("aggregated_output")
1898 .and_then(|o| o.as_str())
1899 .map(|s| tail_chars(s.trim(), 400))
1900 .unwrap_or_default();
1901 CommandEvidence {
1902 id: item
1903 .get("id")
1904 .and_then(|s| s.as_str())
1905 .unwrap_or_default()
1906 .to_owned(),
1907 description,
1908 exit_code: item
1909 .get("exit_code")
1910 .and_then(serde_json::Value::as_i64)
1911 .map(|e| e as i32),
1912 result_summary,
1913 source: "codex".to_owned(),
1914 }
1915}
1916
1917fn tail_chars(s: &str, max: usize) -> String {
1919 let count = s.chars().count();
1920 if count <= max {
1921 return s.to_owned();
1922 }
1923 s.chars().skip(count - max).collect()
1924}
1925
1926fn codex_quota(stdout: &str) -> Option<Quota> {
1929 let mut message = None;
1930 let mut failed = false;
1931 for line in stdout.lines() {
1932 let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else {
1933 continue;
1934 };
1935 match v.get("type").and_then(serde_json::Value::as_str) {
1936 Some("error") => {
1937 if let Some(m) = v.get("message").and_then(serde_json::Value::as_str)
1938 && m.starts_with("You've hit your usage limit. Visit https://chatgpt.com/settings/usage to purchase more credits")
1939 {
1940 message = Some(m.to_owned());
1941 }
1942 }
1943 Some("turn.failed") => failed = true,
1944 _ => {}
1945 }
1946 }
1947 if !failed {
1948 return None;
1949 }
1950 let message = message?;
1951 Some(Quota {
1952 reset: message
1953 .split_once("try again at ")
1954 .map(|(_, hint)| hint.trim().trim_end_matches('.').trim().to_owned())
1955 .filter(|hint| !hint.is_empty()),
1956 cause: QuotaCause::UsageLimit,
1957 agent: String::new(),
1958 })
1959}
1960
1961fn claude_quota(v: &serde_json::Value) -> Option<Quota> {
1968 let is_err = v.get("is_error").and_then(|e| e.as_bool()).unwrap_or(false);
1969 if !is_err {
1970 return None;
1971 }
1972 let result = v.get("result").and_then(|r| r.as_str()).unwrap_or("");
1973 if v.get("terminal_reason").and_then(serde_json::Value::as_str) == Some("api_error")
1974 && result.starts_with("Failed to authenticate:")
1975 && result.contains("OAuth session expired and could not be refreshed")
1976 {
1977 return Some(Quota {
1978 reset: None,
1979 cause: QuotaCause::Authentication,
1980 agent: String::new(),
1981 });
1982 }
1983 let status = v.get("api_error_status");
1984 let usage_limit = (status.and_then(serde_json::Value::as_u64) == Some(429)
1985 || status.and_then(serde_json::Value::as_str) == Some("429"))
1986 && v.get("api_error").and_then(serde_json::Value::as_str) == Some("usage_limit_reached");
1987 if !usage_limit && !result.to_lowercase().contains("session limit") {
1988 return None;
1989 }
1990 let reset = result
1993 .split("resets ")
1994 .nth(1)
1995 .map(str::trim)
1996 .filter(|s| !s.is_empty())
1997 .map(str::to_owned);
1998 Some(Quota {
1999 reset,
2000 cause: QuotaCause::UsageLimit,
2001 agent: String::new(),
2002 })
2003}
2004
2005fn agy_quota(stdout: &str, stderr: &str) -> Option<Quota> {
2020 let from_stdout = stdout
2021 .lines()
2022 .rev()
2023 .find_map(|l| serde_json::from_str::<serde_json::Value>(l.trim()).ok())
2024 .and_then(|v| {
2025 let status = v.get("status").and_then(|s| s.as_str()).unwrap_or("");
2026 let error = v.get("error").and_then(|e| e.as_str()).unwrap_or("");
2027 (status.eq_ignore_ascii_case("error") && error.to_lowercase().contains("quota reached"))
2028 .then(|| error.to_owned())
2029 });
2030 let from_stderr = || {
2031 stderr.lines().find_map(|l| {
2032 let v: serde_json::Value =
2033 serde_json::from_str(l.trim().strip_prefix("AGY_ERROR:")?.trim()).ok()?;
2034 let exhausted = v.get("status").and_then(|s| s.as_str()) == Some("RESOURCE_EXHAUSTED");
2035 let code = v.get("error_code").and_then(serde_json::Value::as_u64) == Some(429);
2036 (exhausted && code).then(|| {
2037 v.get("short_error")
2038 .and_then(|e| e.as_str())
2039 .unwrap_or_default()
2040 .to_owned()
2041 })
2042 })
2043 };
2044 let text = from_stdout.or_else(from_stderr)?;
2045 let reset = text
2046 .split_once("Resets ")
2047 .map(|(_, rest)| rest.trim().trim_end_matches('.').trim())
2048 .filter(|s| !s.is_empty())
2049 .map(str::to_owned);
2050 Some(Quota {
2051 reset,
2052 cause: QuotaCause::UsageLimit,
2053 agent: String::new(),
2054 })
2055}
2056
2057fn dropped_stream(v: &serde_json::Value) -> Option<Dropped> {
2088 let status = v.get("status").and_then(|s| s.as_str()).unwrap_or("");
2089 if !status.eq_ignore_ascii_case("error") {
2090 return None;
2091 }
2092 let response = v.get("response").and_then(|r| r.as_str()).unwrap_or("");
2093 if !response.trim().is_empty() {
2094 return None;
2096 }
2097 let produced = v
2098 .get("usage")
2099 .and_then(|u| u.get("output_tokens"))
2100 .and_then(serde_json::Value::as_u64)
2101 .unwrap_or(0);
2102 if produced == 0 {
2103 return None;
2105 }
2106 Some(Dropped {
2107 why: v
2108 .get("error")
2109 .and_then(|e| e.as_str())
2110 .unwrap_or("the CLI ended the stream without delivering its answer")
2111 .trim()
2112 .to_owned(),
2113 output_tokens: produced,
2114 })
2115}
2116
2117pub fn missing_programs(specs: &[AgentSpec]) -> Vec<String> {
2119 let mut missing = Vec::new();
2120 for s in specs {
2121 let program = match s.kind {
2122 AgentKind::Command => s.command.first().map(String::as_str),
2123 other => other.program(),
2124 };
2125 if let Some(p) = program
2126 && !crate::config::which(p)
2127 && !Path::new(p).is_file()
2128 && !missing.iter().any(|m: &String| m == p)
2129 {
2130 missing.push(p.to_owned());
2131 }
2132 }
2133 missing
2134}
2135
2136pub fn artifacts_dir(run_dir: &Path) -> PathBuf {
2138 run_dir.join("artifacts")
2139}
2140
2141pub fn installed(spec: &AgentSpec) -> bool {
2143 spec.kind.program().is_none_or(crate::config::which)
2146}
2147
2148pub fn pick(
2170 agents: &[AgentSpec],
2171 want: Option<&str>,
2172 available: &dyn Fn(&AgentSpec) -> bool,
2173) -> Result<AgentSpec> {
2174 if let Some(id) = want {
2175 let spec = agents
2176 .iter()
2177 .find(|a| a.id == id)
2178 .with_context(|| format!("no agent `{id}` in the roster; it has {}", ids(agents)))?;
2179 if !available(spec) {
2180 bail!(
2181 "agent `{}` needs `{}` on PATH; install it or pass a different \
2182 --agent",
2183 spec.id,
2184 spec.kind.program().unwrap_or("its command")
2185 );
2186 }
2187 return Ok(spec.clone());
2188 }
2189
2190 if agents.is_empty() {
2191 bail!(
2192 "the agent roster is empty, so there is nobody to ask: install one \
2193 of claude, opencode or agy - magi derives a roster from what is on \
2194 PATH - or add an [[agents]] entry to magi.toml."
2195 );
2196 }
2197
2198 if let Some(spec) = agents
2199 .iter()
2200 .find(|a| a.kind == AgentKind::Claude && available(a))
2201 {
2202 return Ok(spec.clone());
2203 }
2204
2205 agents
2206 .iter()
2207 .find(|a| available(a))
2208 .cloned()
2209 .with_context(|| {
2210 let missing = agents
2211 .iter()
2212 .filter_map(|a| a.kind.program())
2213 .collect::<Vec<_>>()
2214 .join(", ");
2215 format!(
2216 "no agent in the roster can be run here: install one of \
2217 {missing}, or add an [[agents]] entry to magi.toml for a CLI \
2218 you do have"
2219 )
2220 })
2221}
2222
2223pub fn for_github_text(spec: &AgentSpec, github_language: &str, cwd: &Path) -> Result<AgentSpec> {
2236 let mut spec = spec.clone();
2237 if spec.kind == AgentKind::Claude {
2238 let mut existing = None;
2241 let mut args = spec.extra_args.iter().enumerate();
2242 while let Some((index, arg)) = args.next() {
2243 if arg == "--settings" {
2244 let (value_index, value) = args.next().context("--settings requires a value")?;
2245 existing = Some((value_index, value.as_str(), false));
2246 } else if let Some(value) = arg.strip_prefix("--settings=") {
2247 existing = Some((index, value, true));
2248 }
2249 }
2250 let mut settings = if let Some((_, value, _)) = existing {
2251 let json = if value.trim_start().starts_with('{') {
2252 value.to_owned()
2253 } else {
2254 std::fs::read_to_string(cwd.join(value))
2255 .context("cannot read existing seat --settings file")?
2256 };
2257 serde_json::from_str::<serde_json::Value>(&json)
2258 .context("cannot parse existing seat --settings JSON")?
2259 } else {
2260 serde_json::json!({})
2261 };
2262 settings
2263 .as_object_mut()
2264 .context("seat --settings must be a JSON object")?
2265 .insert(
2266 "language".to_owned(),
2267 serde_json::json!(crate::lang::name(github_language)),
2268 );
2269 let settings = settings.to_string();
2270 if let Some((index, _, equals)) = existing {
2271 spec.extra_args[index] = if equals {
2272 format!("--settings={settings}")
2273 } else {
2274 settings
2275 };
2276 } else {
2277 spec.extra_args.extend(["--settings".to_owned(), settings]);
2278 }
2279 }
2280 Ok(spec)
2281}
2282
2283pub fn pick_chain(
2291 agents: &[AgentSpec],
2292 choice: Option<&AgentChoice>,
2293 available: &dyn Fn(&AgentSpec) -> bool,
2294 role: &str,
2295) -> Result<Vec<AgentSpec>> {
2296 let wanted = choice.map(AgentChoice::ids).unwrap_or_default();
2297 if wanted.is_empty() {
2298 return pick(agents, None, available)
2299 .map(|s| vec![s])
2300 .with_context(|| format!("choose an agent for the {role} role"));
2301 }
2302 let mut chain: Vec<AgentSpec> = Vec::new();
2303 for id in wanted {
2304 if chain.iter().any(|s| s.id == id) {
2305 continue;
2306 }
2307 match pick(agents, Some(id), available) {
2308 Ok(spec) => chain.push(spec),
2309 Err(e) => tracing::warn!("[roles] {role}: skipping `{id}`: {e:#}"),
2310 }
2311 }
2312 if chain.is_empty() {
2313 bail!(
2314 "[roles] {role} names no agent that can run here; the roster has {}",
2315 ids(agents)
2316 );
2317 }
2318 Ok(chain)
2319}
2320
2321pub fn chain_advances(outcome: &Result<AgentOutput>) -> bool {
2327 match outcome {
2328 Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => false,
2329 Err(_) => true,
2330 Ok(out) => output_advances(out),
2331 }
2332}
2333
2334pub fn output_advances(out: &AgentOutput) -> bool {
2338 out.quota_exhausted() || !out.usable()
2339}
2340
2341fn ids(agents: &[AgentSpec]) -> String {
2342 if agents.is_empty() {
2343 return "no agents at all".to_owned();
2344 }
2345 agents
2346 .iter()
2347 .map(|a| a.id.clone())
2348 .collect::<Vec<_>>()
2349 .join(", ")
2350}
2351
2352#[cfg(all(test, unix))]
2355pub(crate) mod test_watchdog {
2356 use super::*;
2357 static FLOORS: Mutex<BTreeMap<String, u64>> = Mutex::new(BTreeMap::new());
2358
2359 pub(crate) struct Guard(String);
2360
2361 pub(crate) fn set(run: &str, floor: u64) -> Guard {
2362 assert!(
2363 FLOORS
2364 .lock()
2365 .unwrap()
2366 .insert(run.to_owned(), floor)
2367 .is_none()
2368 );
2369 Guard(run.to_owned())
2370 }
2371
2372 pub(super) fn floor(run: &str, configured: u64) -> u64 {
2373 FLOORS
2374 .lock()
2375 .unwrap()
2376 .get(run)
2377 .copied()
2378 .unwrap_or(configured)
2379 }
2380
2381 impl Drop for Guard {
2382 fn drop(&mut self) {
2383 FLOORS.lock().unwrap().remove(&self.0);
2384 }
2385 }
2386}
2387
2388#[cfg(test)]
2389mod tests {
2390 use super::*;
2391
2392 const COMMAND_HELPER_MODE: &str = "MAGI_TEST_COMMAND_HELPER_MODE";
2393
2394 fn command_helper(mode: &str) -> AgentSpec {
2397 crate::run::pin_test_home();
2399 AgentSpec {
2400 id: "helper".to_owned(),
2401 kind: AgentKind::Command,
2402 model: None,
2403 command: vec![
2404 std::env::current_exe()
2405 .expect("locate test helper")
2406 .to_string_lossy()
2407 .into_owned(),
2408 "--exact".to_owned(),
2409 "agent::tests::command_agent_test_helper".to_owned(),
2410 "--nocapture".to_owned(),
2411 ],
2412 extra_args: Vec::new(),
2413 env: BTreeMap::from([(COMMAND_HELPER_MODE.to_owned(), mode.to_owned())]),
2414 prompt_delivery: None,
2415 max_turn_secs: None,
2416 }
2417 }
2418
2419 #[test]
2420 fn command_agent_test_helper() {
2421 match std::env::var(COMMAND_HELPER_MODE).as_deref() {
2422 Ok("reply") => println!("hello {}", std::env::var("MAGI_SEAT").unwrap()),
2423 Ok("cache") => println!("{}", std::env::var("CARGO_TARGET_DIR").unwrap()),
2424 Ok("no-cache") => println!(
2425 "{}",
2426 std::env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| "ABSENT".to_owned())
2427 ),
2428 Ok("ignore-stdin") => println!("done"),
2429 Ok("chatty-sleep") => {
2430 println!("i-said-something");
2431 std::thread::sleep(Duration::from_secs(30));
2432 }
2433 Ok("sleep") => std::thread::sleep(Duration::from_secs(30)),
2434 Ok(other) => panic!("unknown command helper mode {other}"),
2435 Err(_) => {}
2436 }
2437 }
2438
2439 fn spec(kind: AgentKind, model: Option<&str>) -> AgentSpec {
2440 AgentSpec {
2441 id: "a".to_owned(),
2442 kind,
2443 model: model.map(str::to_owned),
2444 command: vec!["echo".to_owned(), "{label}".to_owned()],
2445 extra_args: Vec::new(),
2446 env: BTreeMap::new(),
2447 prompt_delivery: None,
2448 max_turn_secs: None,
2449 }
2450 }
2451
2452 fn inv<'a>(cwd: &'a Path, art: &'a Path, allow_write: bool) -> Invocation<'a> {
2453 Invocation {
2454 coordination: None,
2455 fetched_base: None,
2456 cwd,
2457 prompt: "do the thing",
2458 timeout: Duration::from_secs(900),
2459 allow_write,
2460 sessions: true,
2461 artifacts: art,
2462 stem: "t",
2463 run: "test-run",
2464 node: "test",
2465 cache_dir: None,
2466 attachments: &[],
2467 writable: &[],
2468 }
2469 }
2470
2471 fn plan_for(kind: AgentKind, seat: &SeatState, allow_write: bool) -> Plan {
2472 build_command(
2473 &spec(kind, None),
2474 seat,
2475 &inv(Path::new("."), Path::new("/art"), allow_write),
2476 Path::new("/art/p.md"),
2477 )
2478 .unwrap()
2479 }
2480
2481 #[test]
2482 fn editing_access_requires_fetch_evidence_and_keeps_snapshot() {
2483 let missing = editing_access_note(None);
2484 assert!(missing.contains("No successful launcher fetch evidence"));
2485 let base = crate::run::FetchedBase {
2486 remote: "origin".into(),
2487 branch: "main".into(),
2488 commit: "0123456789abcdef".into(),
2489 fetched_at: "2026-10-18T00:00:00Z".parse().unwrap(),
2490 };
2491 let note = editing_access_note(Some(&base));
2492 for expected in [
2493 "origin/main",
2494 "0123456789abcdef",
2495 "2026-10-18T00:00:00Z",
2496 "Do not fetch again",
2497 ] {
2498 assert!(note.contains(expected), "missing {expected}");
2499 }
2500 for text in [&missing, ¬e] {
2503 assert!(!text.to_lowercase().contains("sandbox"), "{text}");
2504 assert!(!text.contains("Network access is restricted"), "{text}");
2505 }
2506 let roundtrip: crate::run::FetchedBase =
2507 serde_json::from_str(&serde_json::to_string(&base).unwrap()).unwrap();
2508 assert_eq!(editing_access_note(Some(&roundtrip)), note);
2509 }
2510
2511 #[test]
2512 fn codex_editing_seats_bypass_the_sandbox_on_initial_and_resume() {
2513 const BYPASS: &str = "--dangerously-bypass-approvals-and-sandbox";
2514 let roots = [PathBuf::from("/shared/git"), PathBuf::from("/questions")];
2515 for resumed in [false, true] {
2516 let mut seat = SeatState::new("impl-A", "a", 7);
2517 if resumed {
2518 seat.turns = 1;
2519 seat.captured_session = Some("fixture-thread".into());
2520 }
2521 let build = |invocation: &Invocation<'_>| {
2522 build_command(
2523 &spec(AgentKind::Codex, None),
2524 &seat,
2525 invocation,
2526 Path::new("/art/p.md"),
2527 )
2528 .unwrap()
2529 };
2530 for node in [
2531 "implement",
2532 "fix",
2533 "graft",
2534 "gate-fix",
2535 "land",
2536 "rebase",
2537 "base-conflict",
2538 crate::queue::CHAT_NODE,
2539 "external-chat",
2540 ] {
2541 let mut invocation = inv(Path::new("."), Path::new("/art"), true);
2542 invocation.node = node;
2543 invocation.writable = &roots;
2544 let plan = build(&invocation);
2545 let at = plan.argv.iter().position(|s| s == BYPASS);
2546 assert!(at.is_some(), "{node}: {:?}", plan.argv);
2547 if resumed {
2548 let resume = plan.argv.iter().position(|s| s == "resume").unwrap();
2549 assert!(at.unwrap() < resume, "{node}: {:?}", plan.argv);
2550 }
2551 assert!(!plan.argv.iter().any(|s| s == "--sandbox"), "{node}");
2553 assert!(!plan.argv.iter().any(|s| s == "-c"), "{node}");
2554 }
2555 for (node, write) in [
2556 ("review", false),
2557 ("judge", false),
2558 ("advise", false),
2559 ("implement", false),
2560 ("fix", false),
2561 ("dupes", false),
2562 ("conduct", false),
2563 ("waiter", false),
2564 ("talk-title", false),
2565 (crate::queue::CHAT_NODE, false),
2566 ("external-chat", false),
2567 ("deputy", true),
2568 ] {
2569 let mut invocation = inv(Path::new("."), Path::new("/art"), write);
2570 invocation.node = node;
2571 let plan = build(&invocation);
2572 assert!(!plan.argv.iter().any(|s| s == BYPASS), "{node}");
2573 let mode = if write {
2574 "workspace-write"
2575 } else {
2576 "read-only"
2577 };
2578 assert!(
2579 plan.argv.windows(2).any(|w| w == ["--sandbox", mode]),
2580 "{node}: {:?}",
2581 plan.argv
2582 );
2583 assert!(
2584 plan.argv
2585 .windows(2)
2586 .any(|w| w == ["-c", "approval_policy=\"never\""]),
2587 "{node}"
2588 );
2589 }
2590 }
2591 }
2592
2593 #[test]
2594 fn claude_mints_then_resumes_the_same_uuid() {
2595 let mut seat = SeatState::new("judge-1", "a", 7);
2596 let uuid = seat.claude_session.clone().unwrap();
2597 let first = plan_for(AgentKind::Claude, &seat, true);
2598 assert!(first.argv.windows(2).any(|w| w == ["--session-id", &uuid]));
2599 assert!(!first.argv.iter().any(|a| a == "--resume"));
2600
2601 seat.turns = 1;
2602 let second = plan_for(AgentKind::Claude, &seat, true);
2603 assert!(second.argv.windows(2).any(|w| w == ["--resume", &uuid]));
2604 assert!(!second.argv.iter().any(|a| a == "--session-id"));
2605 }
2606
2607 #[test]
2608 fn github_bound_claude_seats_override_the_operators_answer_language() {
2609 let seat = SeatState::new("change-summary", "a", 7);
2610 let art = Path::new("/art");
2611 for (language, name) in [("en", "English"), ("", "English"), ("ja", "Japanese")] {
2612 let claude =
2613 for_github_text(&spec(AgentKind::Claude, None), language, Path::new(".")).unwrap();
2614 let plan = build_command(
2615 &claude,
2616 &seat,
2617 &inv(Path::new("."), art, false),
2618 Path::new("/art/p.md"),
2619 )
2620 .unwrap();
2621 let settings = format!(r#"{{"language":"{name}"}}"#);
2622 assert!(
2623 plan.argv
2624 .windows(2)
2625 .any(|w| w == ["--settings", settings.as_str()]),
2626 "{:?}",
2627 plan.argv
2628 );
2629 assert_eq!(plan.stdin.as_deref(), Some("do the thing"));
2632 }
2633 for kind in [
2634 AgentKind::Codex,
2635 AgentKind::Opencode,
2636 AgentKind::Antigravity,
2637 AgentKind::Omp,
2638 ] {
2639 assert!(
2640 for_github_text(&spec(kind, None), "en", Path::new("."))
2641 .unwrap()
2642 .extra_args
2643 .is_empty()
2644 );
2645 }
2646 }
2647
2648 #[test]
2649 fn github_text_preserves_existing_settings() {
2650 let dir = tempfile::tempdir().unwrap();
2651 let original = serde_json::json!({
2652 "language": "Japanese",
2653 "env": { "SEAT_MODE": "configured" },
2654 "apiKeyHelper": "credential-helper",
2655 "hooks": { "Stop": [] }
2656 });
2657 std::fs::write(dir.path().join("seat-settings.json"), original.to_string()).unwrap();
2658 for value in [original.to_string(), "./seat-settings.json".to_owned()] {
2659 for equals in [false, true] {
2660 let mut spec = spec(AgentKind::Claude, None);
2661 spec.extra_args = vec!["--settings={\"language\":\"French\"}".to_owned()];
2663 if equals {
2664 spec.extra_args.push(format!("--settings={value}"));
2665 } else {
2666 spec.extra_args
2667 .extend(["--settings".to_owned(), value.clone()]);
2668 }
2669 spec.extra_args.push("--verbose".to_owned());
2670 let updated = for_github_text(&spec, "en", dir.path()).unwrap();
2671 assert_eq!(updated.extra_args.len(), spec.extra_args.len());
2672 assert_eq!(updated.extra_args[0], spec.extra_args[0]);
2673 assert_eq!(updated.extra_args.last(), spec.extra_args.last());
2674 let value = &updated.extra_args[updated.extra_args.len() - 2];
2675 let actual: serde_json::Value =
2676 serde_json::from_str(value.strip_prefix("--settings=").unwrap_or(value))
2677 .unwrap();
2678 let mut expected = original.clone();
2679 expected["language"] = serde_json::json!("English");
2680 assert_eq!(actual, expected);
2681 }
2682 }
2683 let on_disk: serde_json::Value = serde_json::from_str(
2684 &std::fs::read_to_string(dir.path().join("seat-settings.json")).unwrap(),
2685 )
2686 .unwrap();
2687 assert_eq!(on_disk, original);
2688 }
2689
2690 #[test]
2691 fn github_text_settings_are_redacted_from_command_logging() {
2692 let dir = tempfile::tempdir().unwrap();
2693 let settings = serde_json::json!({ "env": { "AUTH_TOKEN": "test-only-secret" } });
2694 std::fs::write(dir.path().join("seat-settings.json"), settings.to_string()).unwrap();
2695 for equals in [false, true] {
2696 let mut spec = spec(AgentKind::Claude, None);
2697 spec.extra_args =
2698 vec!["--settings={\"env\":{\"AUTH_TOKEN\":\"earlier-secret\"}}".to_owned()];
2699 if equals {
2700 spec.extra_args
2701 .push("--settings=./seat-settings.json".to_owned());
2702 } else {
2703 spec.extra_args
2704 .extend(["--settings".to_owned(), "./seat-settings.json".to_owned()]);
2705 }
2706 let spec = for_github_text(&spec, "en", dir.path()).unwrap();
2707 let plan = build_command(
2708 &spec,
2709 &SeatState::new("change-summary", "a", 7),
2710 &inv(dir.path(), dir.path(), false),
2711 &dir.path().join("prompt.md"),
2712 )
2713 .unwrap();
2714 let actual = plan.argv.last().unwrap();
2716 let actual: serde_json::Value =
2717 serde_json::from_str(actual.strip_prefix("--settings=").unwrap_or(actual)).unwrap();
2718 assert_eq!(actual["env"]["AUTH_TOKEN"], "test-only-secret");
2719 assert_eq!(actual["language"], "English");
2720 let logged = format!("{:?}", plan.logged_argv());
2721 assert!(!logged.contains("secret"));
2722 assert!(!logged.contains("AUTH_TOKEN"));
2723 assert!(logged.contains("[redacted]"));
2724 assert_eq!(plan.logged_argv()[0], "claude");
2725 assert!(plan.logged_argv().contains(&"--output-format"));
2726 }
2727 }
2728
2729 #[test]
2730 fn github_text_rejects_unreadable_or_invalid_settings() {
2731 let dir = tempfile::tempdir().unwrap();
2732 std::fs::write(dir.path().join("bad.json"), "invalid json").unwrap();
2733 std::fs::write(dir.path().join("array.json"), "[]").unwrap();
2734 for args in [
2735 vec!["--settings"],
2736 vec!["--settings", "missing.json"],
2737 vec!["--settings=bad.json"],
2738 vec!["--settings", "array.json"],
2739 ] {
2740 let mut spec = spec(AgentKind::Claude, None);
2741 spec.extra_args = args.into_iter().map(str::to_owned).collect();
2742 assert!(for_github_text(&spec, "en", dir.path()).is_err());
2743 }
2744 }
2745
2746 #[test]
2747 fn read_only_seats_cannot_edit() {
2748 let seat = SeatState::new("judge-1", "a", 7);
2749 let claude = plan_for(AgentKind::Claude, &seat, false);
2750 assert!(claude.argv.iter().any(|a| a == "--disallowed-tools"));
2751 assert!(
2752 !plan_for(AgentKind::Claude, &seat, true)
2753 .argv
2754 .iter()
2755 .any(|a| a == "--disallowed-tools")
2756 );
2757
2758 let agy = plan_for(AgentKind::Antigravity, &seat, false);
2759 assert!(agy.argv.windows(2).any(|w| w == ["--mode", "plan"]));
2760 assert!(
2761 !agy.argv
2762 .iter()
2763 .any(|a| a == "--dangerously-skip-permissions")
2764 );
2765 let agy_rw = plan_for(AgentKind::Antigravity, &seat, true);
2766 assert!(
2767 agy_rw
2768 .argv
2769 .windows(2)
2770 .any(|w| w == ["--mode", "accept-edits"])
2771 );
2772 assert!(
2773 agy_rw
2774 .argv
2775 .iter()
2776 .any(|a| a == "--dangerously-skip-permissions")
2777 );
2778 let agy_prompt = agy_rw
2783 .argv
2784 .iter()
2785 .position(|a| a == "-p")
2786 .map(|i| agy_rw.argv[i + 1].clone())
2787 .expect("agy takes its prompt with -p");
2788 assert!(
2789 agy_prompt.starts_with('@'),
2790 "agy must get a file reference, got {agy_prompt:?}"
2791 );
2792 assert!(
2793 !agy_prompt.contains("Read the file at"),
2794 "the prose pointer is for CLIs with no file syntax"
2795 );
2796
2797 for allow_write in [false, true] {
2802 assert!(
2803 plan_for(AgentKind::Opencode, &seat, allow_write)
2804 .argv
2805 .iter()
2806 .any(|a| a == "--auto"),
2807 "opencode needs --auto even to read (allow_write = {allow_write})"
2808 );
2809 }
2810 }
2811
2812 #[test]
2815 fn codex_gets_extra_writable_roots_only_when_it_may_write() {
2816 let seat = SeatState::new("deputy-x", "a", 7);
2817 let roots = [PathBuf::from("/data/questions")];
2818 let mk = |allow_write: bool| {
2819 let mut i = inv(Path::new("."), Path::new("/art"), allow_write);
2820 i.writable = &roots;
2821 build_command(
2822 &spec(AgentKind::Codex, None),
2823 &seat,
2824 &i,
2825 Path::new("/art/p.md"),
2826 )
2827 .unwrap()
2828 };
2829 let want = "sandbox_workspace_write.writable_roots=[\"/data/questions\"]";
2830 assert!(mk(true).argv.windows(2).any(|w| w == ["-c", want]));
2831 assert!(!mk(false).argv.iter().any(|a| a.contains("writable_roots")));
2832 }
2833
2834 #[test]
2835 fn repository_write_scope_covers_editing_nodes_without_changing_other_roles() {
2836 let mut i = inv(Path::new("."), Path::new("/art"), true);
2837 for node in [
2838 "implement",
2839 "fix",
2840 "graft",
2841 "gate-fix",
2842 "land",
2843 "rebase",
2844 "base-conflict",
2845 "chat",
2846 "external-chat",
2847 ] {
2848 i.node = node;
2849 assert!(repository_writer(&i), "{node}");
2850 i.allow_write = false;
2851 assert!(!repository_writer(&i), "{node}");
2852 i.allow_write = true;
2853 }
2854 for node in ["deputy", "judge", "review", "bump", "conduct", "talk-title"] {
2855 i.node = node;
2856 assert!(!repository_writer(&i), "{node}");
2857 }
2858 i.node = "chat";
2859 let roots = [PathBuf::from("/questions")];
2860 i.writable = &roots;
2861 assert!(
2862 repository_writer(&i),
2863 "explicit roots do not change the role"
2864 );
2865 assert!(
2866 !repository_seat(&i),
2867 "chat turns bypass repository scheduling"
2868 );
2869 }
2870
2871 #[test]
2872 fn coordination_classification_is_independent_of_write_grants() {
2873 let roots = [PathBuf::from("/questions")];
2874 for node in [
2875 crate::queue::CHAT_NODE,
2876 "external-chat",
2877 "implement",
2878 "fix",
2879 "graft",
2880 "gate-fix",
2881 "land",
2882 "rebase",
2883 "base-conflict",
2884 "review",
2885 "judge",
2886 "advise",
2887 "deputy",
2888 "waiter",
2889 "conduct",
2890 "dupes",
2891 "talk-title",
2892 ] {
2893 for allow_write in [false, true] {
2894 for writable in [&[][..], &roots[..]] {
2895 let mut i = inv(Path::new("."), Path::new("/art"), allow_write);
2896 i.node = node;
2897 i.writable = writable;
2898 assert_eq!(
2899 repository_seat(&i),
2900 !matches!(
2901 node,
2902 crate::queue::CHAT_NODE
2903 | "external-chat"
2904 | "talk-title"
2905 | "deputy"
2906 | "conduct"
2907 | "dupes"
2908 ),
2909 "{node}, allow_write={allow_write}, writable={writable:?}"
2910 );
2911 if matches!(node, crate::queue::CHAT_NODE | "external-chat") {
2912 assert_eq!(repository_writer(&i), allow_write);
2913 }
2914 }
2915 }
2916 }
2917 }
2918
2919 #[test]
2920 fn writable_directories_reach_initial_and_resumed_adapter_commands() {
2921 let roots = [
2922 PathBuf::from("/shared/git"),
2923 PathBuf::from("/state/questions"),
2924 ];
2925 for kind in [AgentKind::Codex, AgentKind::Antigravity] {
2926 for resumed in [false, true] {
2927 let mut seat = SeatState::new("impl-A", "a", 7);
2928 if resumed {
2929 seat.turns = 1;
2930 seat.captured_session = Some("session-id".into());
2931 }
2932 for allow_write in [false, true] {
2933 let mut i = inv(Path::new("."), Path::new("/art"), allow_write);
2934 i.writable = &roots;
2935 let plan = build_command(&spec(kind, None), &seat, &i, Path::new("/art/p.md"))
2936 .unwrap();
2937 for root in &roots {
2938 if kind == AgentKind::Antigravity {
2939 assert_eq!(
2940 plan.argv.windows(2).any(|w| {
2941 w[0] == "--add-dir" && w[1] == root.to_str().unwrap()
2942 }),
2943 allow_write,
2944 "resumed={resumed}: {:?}",
2945 plan.argv
2946 );
2947 }
2948 assert_eq!(
2949 plan.argv
2950 .iter()
2951 .any(|arg| arg.contains(root.to_str().unwrap())),
2952 allow_write,
2953 "{kind:?}, resumed={resumed}: {:?}",
2954 plan.argv
2955 );
2956 }
2957 if kind == AgentKind::Codex && resumed {
2958 let at = plan.argv.iter().position(|s| s == "resume").unwrap();
2959 assert!(!plan.argv[at..].iter().any(|s| s == "-c"));
2960 }
2961 }
2962 }
2963 }
2964 }
2965
2966 #[test]
2967 fn codex_is_sandboxed_reads_stdin_and_puts_resume_last() {
2968 let mut seat = SeatState::new("judge-1", "a", 7);
2969
2970 let ro = plan_for(AgentKind::Codex, &seat, false);
2976 assert!(ro.argv.windows(2).any(|w| w == ["--sandbox", "read-only"]));
2977 let rw = plan_for(AgentKind::Codex, &seat, true);
2978 assert!(
2979 rw.argv
2980 .windows(2)
2981 .any(|w| w == ["--sandbox", "workspace-write"])
2982 );
2983 for p in [&ro, &rw] {
2984 assert!(
2985 !p.argv
2986 .iter()
2987 .any(|a| a == "--dangerously-bypass-approvals-and-sandbox"),
2988 "the bypass defeats the only enforced read-only mode we have"
2989 );
2990 assert!(
2992 p.argv
2993 .windows(2)
2994 .any(|w| w == ["-c", "approval_policy=\"never\""]),
2995 "an unattended seat that asks for approval blocks until timeout"
2996 );
2997 }
2998
2999 assert_eq!(ro.stdin.as_deref(), Some("do the thing"));
3001 assert_eq!(
3002 ro.argv.last().map(String::as_str),
3003 Some("-"),
3004 "without the `-` argument codex waits for a prompt it never gets"
3005 );
3006
3007 seat.turns = 1;
3011 assert!(!has_session(AgentKind::Codex, &seat, true));
3012 assert!(
3013 !plan_for(AgentKind::Codex, &seat, true)
3014 .argv
3015 .iter()
3016 .any(|a| a == "resume")
3017 );
3018 seat.captured_session = Some("01a07440-4545-7492-85c1-024e3259a90a".to_owned());
3019 let resumed = plan_for(AgentKind::Codex, &seat, true);
3020 let at = resumed
3021 .argv
3022 .iter()
3023 .position(|a| a == "resume")
3024 .expect("resumes by subcommand");
3025 assert_eq!(resumed.argv[at + 1], "01a07440-4545-7492-85c1-024e3259a90a");
3026 assert!(
3027 resumed.argv[..at].iter().any(|a| a == "--sandbox"),
3028 "every option precedes the subcommand"
3029 );
3030 assert_eq!(resumed.argv.last().map(String::as_str), Some("-"));
3031 }
3032
3033 #[test]
3036 fn omp_reads_stdin_auto_approves_and_resumes_by_id() {
3037 let mut seat = SeatState::new("review-1", "a", 7);
3038
3039 let first = plan_for(AgentKind::Omp, &seat, false);
3043 assert!(first.argv.iter().any(|a| a == "-p"));
3044 assert!(first.argv.iter().any(|a| a == "--mode=json"));
3045 assert_eq!(first.stdin.as_deref(), Some("do the thing"));
3046 assert!(
3047 !first.argv.iter().any(|a| a == "do the thing"),
3048 "the prompt reached argv, where Windows caps it"
3049 );
3050
3051 for allow_write in [false, true] {
3057 let p = plan_for(AgentKind::Omp, &seat, allow_write);
3058 assert!(
3059 p.argv.iter().any(|a| a == "--auto-approve"),
3060 "omp needs --auto-approve even to read (allow_write = {allow_write})"
3061 );
3062 assert!(
3063 !p.argv
3064 .iter()
3065 .any(|a| a == "--dangerously-bypass-approvals-and-sandbox"),
3066 "nothing ever asks for the bypass"
3067 );
3068 }
3069
3070 seat.turns = 1;
3073 assert!(!has_session(AgentKind::Omp, &seat, true));
3074 assert!(
3075 !plan_for(AgentKind::Omp, &seat, true)
3076 .argv
3077 .iter()
3078 .any(|a| a == "--resume")
3079 );
3080 seat.captured_session = Some("01a09fe9-4e31-7226-85b3-fda6f46689d5".to_owned());
3081 let resumed = plan_for(AgentKind::Omp, &seat, true);
3082 assert!(
3083 resumed
3084 .argv
3085 .windows(2)
3086 .any(|w| w == ["--resume", "01a09fe9-4e31-7226-85b3-fda6f46689d5"]),
3087 "a captured id is what makes the next turn a resume"
3088 );
3089 assert!(!resumed.argv.iter().any(|a| a == "--continue"));
3092 assert_eq!(resumed.stdin.as_deref(), Some("do the thing"));
3094 }
3095
3096 #[test]
3097 fn omp_terminal_breadcrumbs_are_disabled_only_for_managed_sessions() {
3098 let mut seat = SeatState::new("review-1", "a", 7);
3099 let mut cmd = Command::new("omp");
3100 cmd.envs([
3101 ("ZELLIJ_PANE_ID", "1"),
3102 ("TMUX_PANE", "%2"),
3103 ("CMUX_SURFACE_ID", "terminal"),
3104 ("KITTY_WINDOW_ID", "3"),
3105 ("WEZTERM_PANE", "4"),
3106 ("TERM_SESSION_ID", "terminal"),
3107 ("WT_SESSION", "terminal"),
3108 ("OMP_PROFILE", "work"),
3109 ]);
3110 let envs = |cmd: &Command| {
3111 cmd.as_std()
3112 .get_envs()
3113 .filter(|(_, value)| value.is_some())
3114 .count()
3115 };
3116 OmpSession::Resume.isolate_terminal_history(&mut cmd, &seat);
3117 assert_eq!(envs(&cmd), 8);
3118 OmpSession::Fresh(PathBuf::from("managed")).isolate_terminal_history(&mut cmd, &seat);
3119 assert_eq!(envs(&cmd), 1);
3120 assert!(
3121 cmd.as_std()
3122 .get_envs()
3123 .any(|(key, value)| { key == "OMP_PROFILE" && value == Some(OsStr::new("work")) })
3124 );
3125
3126 seat.omp_session_dir = Some(PathBuf::from("managed"));
3127 cmd.env("WT_SESSION", "terminal");
3128 OmpSession::Resume.isolate_terminal_history(&mut cmd, &seat);
3129 assert_eq!(envs(&cmd), 1);
3130 }
3131
3132 #[test]
3133 fn omp_managed_session_persists_native_path_and_reuses_it_after_reload() {
3134 let tmp = tempfile::tempdir().unwrap();
3135 let home = tmp.path().join("magi home 日本語");
3136 let spec = spec(AgentKind::Omp, None);
3137 let mut seat = SeatState::new("review-1", "a", 7);
3138 let art = tmp.path().join("art");
3139 let cwd = tmp.path().join("other checkout");
3140 let mut invocation = inv(&cwd, &art, false);
3141 let prompt = art.join("p.md");
3142
3143 let fresh = OmpSession::prepare(&spec, &seat, true, || home.clone()).unwrap();
3144 let dir = fresh.dir(&seat).unwrap().to_owned();
3145 assert_eq!(dir.parent().unwrap(), home.join("agent-sessions/omp"));
3146 assert!(dir.is_absolute() && dir.is_dir());
3147 assert!(
3148 !dir.file_name()
3149 .unwrap()
3150 .to_str()
3151 .unwrap()
3152 .contains(&seat.key)
3153 );
3154 let plan = build_command(&spec, &seat, &invocation, &prompt).unwrap();
3155 let args: Vec<_> = plan.args(Some(&dir)).collect();
3156 assert_eq!(&args[..2], [OsStr::new("--session-dir"), dir.as_os_str()]);
3157 assert!(!args.contains(&OsStr::new("--resume")));
3158 fresh
3159 .record(&mut seat, Some("first-id".into()), true)
3160 .unwrap();
3161 seat.turns += 1;
3162
3163 let mut seat: SeatState =
3164 serde_json::from_slice(&serde_json::to_vec(&seat).unwrap()).unwrap();
3165 let resumed = OmpSession::prepare(&spec, &seat, true, || {
3166 panic!("resume must not resolve home")
3167 })
3168 .unwrap();
3169 let plan = build_command(&spec, &seat, &invocation, &prompt).unwrap();
3170 let args: Vec<_> = plan.args(resumed.dir(&seat)).collect();
3171 assert_eq!(&args[..2], [OsStr::new("--session-dir"), dir.as_os_str()]);
3172 assert!(args.windows(2).any(|w| w == ["--resume", "first-id"]));
3173 let before = seat.clone();
3174 assert!(
3175 resumed
3176 .record(&mut seat, Some("other-id".into()), true)
3177 .is_err()
3178 );
3179 assert!(OmpSession::Resume.record(&mut seat, None, true).is_err());
3180 assert_eq!(seat, before);
3181 OmpSession::Resume.record(&mut seat, None, false).unwrap();
3183 assert_eq!(seat, before);
3184
3185 let fallback = SeatState::new("review-1", "b", 7);
3186 let next = OmpSession::prepare(&spec, &fallback, true, || home.clone()).unwrap();
3187 assert_ne!(next.dir(&fallback).unwrap(), dir);
3188 invocation.sessions = false;
3190 let fresh = OmpSession::prepare(&spec, &seat, false, || home.clone()).unwrap();
3191 let new_dir = fresh.dir(&seat).unwrap().to_owned();
3192 assert_ne!(new_dir, dir);
3193 assert_ne!(next.dir(&fallback).unwrap(), new_dir);
3194 assert!(
3195 !build_command(&spec, &seat, &invocation, &prompt)
3196 .unwrap()
3197 .args(Some(&new_dir))
3198 .any(|arg| arg == "--resume")
3199 );
3200 fresh
3201 .record(&mut seat, Some("fresh-id".into()), true)
3202 .unwrap();
3203 assert_eq!(seat.omp_session_dir.as_deref(), Some(new_dir.as_path()));
3204 assert_eq!(seat.captured_session.as_deref(), Some("fresh-id"));
3205
3206 std::fs::remove_dir(new_dir).unwrap();
3207 assert!(OmpSession::prepare(&spec, &seat, true, || home.clone()).is_err());
3208 }
3209
3210 #[test]
3211 fn omp_pre_isolation_json_resumes_without_a_session_directory() {
3212 let mut seat: SeatState = serde_json::from_str(
3213 r#"{"key":"review-1","agent":"a","turns":1,"claude_session":null,"captured_session":"legacy-id"}"#,
3214 )
3215 .unwrap();
3216 let resume = OmpSession::prepare(&spec(AgentKind::Omp, None), &seat, true, || {
3217 panic!("legacy resume must not resolve or create a store")
3218 })
3219 .unwrap();
3220 let plan = plan_for(AgentKind::Omp, &seat, false);
3221 let args: Vec<_> = plan.args(resume.dir(&seat)).collect();
3222 assert!(!args.contains(&OsStr::new("--session-dir")));
3223 assert!(args.windows(2).any(|w| w == ["--resume", "legacy-id"]));
3224 resume
3225 .record(&mut seat, Some("continuation-id".into()), true)
3226 .unwrap();
3227 assert!(seat.omp_session_dir.is_none());
3228 assert_eq!(seat.captured_session.as_deref(), Some("continuation-id"));
3229 let plan = plan_for(AgentKind::Omp, &seat, false);
3230 assert!(
3231 plan.args(None)
3232 .zip(plan.args(None).skip(1))
3233 .any(|(flag, id)| flag == "--resume" && id == "continuation-id")
3234 );
3235 }
3236
3237 #[test]
3238 fn omp_managed_resume_tracks_only_local_continuation_lineage() {
3239 let tmp = tempfile::tempdir().unwrap();
3240 let managed = tmp.path().join("managed");
3241 std::fs::create_dir(&managed).unwrap();
3242 let mut seat = SeatState::new("review-1", "a", 7);
3243 seat.turns = 1;
3244 seat.captured_session = Some("original".into());
3245 seat.omp_session_dir = Some(managed.clone());
3246
3247 let write_header = |dir: &Path, id: &str, parent: &str| {
3248 let header = serde_json::json!({
3249 "type": "session", "version": 3, "id": id, "continuationOf": parent,
3250 });
3251 std::fs::write(dir.join(format!("{id}.jsonl")), format!("{header}\n")).unwrap();
3252 };
3253 write_header(tmp.path(), "outside", "original");
3254 write_header(&managed, "unrelated", "other-seat");
3255 write_header(&managed, "middle", "original");
3256 write_header(&managed, "latest", "middle");
3257 for id in ["outside", "unrelated"] {
3258 assert!(
3259 OmpSession::Resume
3260 .record(&mut seat, Some(id.into()), true)
3261 .is_err()
3262 );
3263 assert_eq!(seat.captured_session.as_deref(), Some("original"));
3264 }
3265
3266 OmpSession::Resume
3267 .record(&mut seat, Some("latest".into()), true)
3268 .unwrap();
3269 assert_eq!(seat.omp_session_dir.as_deref(), Some(managed.as_path()));
3270 let plan = plan_for(AgentKind::Omp, &seat, false);
3271 assert!(plan.argv.windows(2).any(|w| w == ["--resume", "latest"]));
3272 }
3273
3274 #[test]
3275 fn omp_managed_session_rejects_extra_args_that_override_history() {
3276 let mut spec = spec(AgentKind::Omp, None);
3277 let mut seat = SeatState::new("review-1", "a", 7);
3278 for arg in [
3279 "--session-dir",
3280 "--session-dir=other",
3281 "--no-session",
3282 "--continue",
3283 "--resume=other",
3284 "--session",
3285 "--session=operator.jsonl",
3286 "--fork",
3287 "--fork=operator.jsonl",
3288 "--restore",
3289 "--from-claude",
3290 "--from-codex",
3291 "-c",
3292 "-r=other",
3293 ] {
3294 spec.extra_args = vec![arg.into()];
3295 for sessions in [false, true] {
3296 let error = OmpSession::prepare(&spec, &seat, sessions, || panic!("invalid arg"))
3297 .err()
3298 .unwrap();
3299 assert!(error.to_string().contains("omp extra_args"));
3300 }
3301 seat.turns = 1;
3302 seat.captured_session = Some("existing-id".into());
3303 seat.omp_session_dir = Some(PathBuf::from("not-opened"));
3304 }
3305 }
3306
3307 #[test]
3312 fn omp_takes_the_answer_without_an_agent_end_line() {
3313 let stream = concat!(
3314 r#"{"type":"session","version":3,"id":"01a09fe9-4e31-7226-85b3-fda6f46689d5","cwd":"C:\\w"}"#,
3315 "\n",
3316 r#"{"type":"agent_start"}"#,
3317 "\n",
3318 r#"{"type":"turn_start"}"#,
3319 "\n",
3320 r#"{"type":"message_update","assistantMessageEvent":{"type":"text_delta","contentIndex":1,"delta":"."}}"#,
3321 "\n",
3322 r#"{"type":"message_end","message":{"role":"assistant","content":[{"type":"thinking","thinking":"checking"},{"type":"text","text":"."}]}}"#,
3323 "\n",
3324 r#"{"type":"turn_end","message":{"role":"assistant","content":[{"type":"thinking","thinking":"done"},{"type":"text","text":"{\"vote\":\"approve\"}"}]}}"#,
3325 "\n",
3326 );
3327 let out = extract(AgentKind::Omp, stream);
3328 assert_eq!(
3329 out.text, "{\"vote\":\"approve\"}",
3330 "the last assistant text block is the answer even with no agent_end"
3331 );
3332 assert_eq!(
3333 out.session.as_deref(),
3334 Some("01a09fe9-4e31-7226-85b3-fda6f46689d5")
3335 );
3336 }
3337
3338 #[test]
3342 fn omp_walks_agent_end_and_ignores_tool_loop_narration() {
3343 let stream = concat!(
3344 r#"{"type":"session","version":3,"id":"s1"}"#,
3345 "\n",
3346 "{\"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問題ありません。\"}]}]}",
3347 "\n",
3348 );
3349 let out = extract(AgentKind::Omp, stream);
3350 assert_eq!(
3351 out.text, "## 判定\n\n問題ありません。",
3352 "the narration is not the answer, and non-ASCII survives intact"
3353 );
3354 assert_eq!(out.session.as_deref(), Some("s1"));
3355 }
3356
3357 #[test]
3360 fn omp_skips_non_json_lines() {
3361 let stream = concat!(
3362 "Warning: some omp notice\n",
3363 r#"{"type":"session","version":3,"id":"s2"}"#,
3364 "\n",
3365 r#"{"type":"message_end","message":{"role":"assistant","content":[{"type":"text","text":"the answer"}]}}"#,
3366 "\n",
3367 "trailing junk",
3368 "\n",
3369 );
3370 let out = extract(AgentKind::Omp, stream);
3371 assert_eq!(out.text, "the answer");
3372 assert_eq!(out.session.as_deref(), Some("s2"));
3373 }
3374
3375 #[test]
3377 fn codex_takes_the_last_agent_message_and_the_thread_id() {
3378 let stream = concat!(
3379 "2026-09-06T01:05:49.394445Z ERROR codex_models_manager: failed to load models cache\n",
3380 r#"{"type":"thread.started","thread_id":"01a07440-4545-7492-85c1-024e3259a90a"}"#,
3381 "\n",
3382 r#"{"type":"turn.started"}"#,
3383 "\n",
3384 r#"{"type":"item.completed","item":{"id":"item_0","type":"agent_message","text":"Looking into it."}}"#,
3385 "\n",
3386 r#"{"type":"item.completed","item":{"id":"item_1","type":"command_execution","text":"cargo test"}}"#,
3387 "\n",
3388 r#"{"type":"item.completed","item":{"id":"item_2","type":"agent_message","text":"{\"verdict\": \"ok\"}"}}"#,
3389 "\n",
3390 r#"{"type":"turn.completed","usage":{"input_tokens":17137}}"#,
3391 "\n",
3392 );
3393 let out = extract(AgentKind::Codex, stream);
3394 assert_eq!(
3395 out.text, "{\"verdict\": \"ok\"}",
3396 "the last agent message is the answer; earlier ones narrate"
3397 );
3398 assert_eq!(
3399 out.session.as_deref(),
3400 Some("01a07440-4545-7492-85c1-024e3259a90a")
3401 );
3402 assert_eq!(out.status.as_deref(), Some("success"));
3403
3404 let failed = concat!(
3405 r#"{"type":"thread.started","thread_id":"t1"}"#,
3406 "\n",
3407 r#"{"type":"turn.failed","error":{"message":"nope"}}"#,
3408 "\n",
3409 );
3410 assert_eq!(
3411 extract(AgentKind::Codex, failed).status.as_deref(),
3412 Some("error")
3413 );
3414 }
3415
3416 #[test]
3417 fn captured_sessions_resume_only_once_reported() {
3418 let mut seat = SeatState::new("impl-A", "a", 7);
3419 seat.turns = 1;
3420 for kind in [AgentKind::Opencode, AgentKind::Antigravity] {
3421 assert!(!has_session(kind, &seat, true));
3422 let p = plan_for(kind, &seat, true);
3423 assert!(!p.argv.iter().any(|a| a == "-s" || a == "--conversation"));
3424 }
3425
3426 seat.captured_session = Some("sid".to_owned());
3427 assert!(has_session(AgentKind::Opencode, &seat, true));
3428 assert!(
3429 plan_for(AgentKind::Opencode, &seat, true)
3430 .argv
3431 .windows(2)
3432 .any(|w| w == ["-s", "sid"])
3433 );
3434 assert!(
3435 plan_for(AgentKind::Antigravity, &seat, true)
3436 .argv
3437 .windows(2)
3438 .any(|w| w == ["--conversation", "sid"])
3439 );
3440 }
3441
3442 #[test]
3443 fn sessions_disabled_never_resumes() {
3444 let mut seat = SeatState::new("impl-A", "a", 7);
3445 seat.turns = 3;
3446 seat.captured_session = Some("sid".to_owned());
3447 for kind in [
3448 AgentKind::Claude,
3449 AgentKind::Opencode,
3450 AgentKind::Antigravity,
3451 ] {
3452 assert!(!has_session(kind, &seat, false));
3453 }
3454 }
3455
3456 #[test]
3457 fn long_prompts_never_reach_argv_for_file_delivery_clis() {
3458 let seat = SeatState::new("judge-1", "a", 7);
3459 for kind in [AgentKind::Opencode, AgentKind::Antigravity] {
3460 let p = plan_for(kind, &seat, false);
3461 assert!(
3462 p.argv.iter().all(|a| a != "do the thing"),
3463 "{kind:?} put the prompt on the command line"
3464 );
3465 assert!(p.argv.iter().any(|a| a.contains("/art/p.md")));
3466 }
3467 let p = plan_for(AgentKind::Antigravity, &seat, false);
3469 let at = p.argv.iter().position(|a| a == "-p").unwrap();
3470 assert!(p.argv.get(at + 1).is_some_and(|v| v.contains("p.md")));
3471 assert!(p.stdin.is_none());
3472 }
3473
3474 #[test]
3475 fn agy_print_timeout_tracks_the_node_budget() {
3476 let seat = SeatState::new("impl-A", "a", 7);
3477 let p = build_command(
3478 &spec(AgentKind::Antigravity, None),
3479 &seat,
3480 &Invocation {
3481 coordination: None,
3482 fetched_base: None,
3483 cwd: Path::new("."),
3484 prompt: "p",
3485 timeout: Duration::from_secs(3600),
3486 allow_write: true,
3487 sessions: true,
3488 artifacts: Path::new("/art"),
3489 stem: "t",
3490 run: "test-run",
3491 node: "test",
3492 cache_dir: None,
3493 attachments: &[],
3494 writable: &[],
3495 },
3496 Path::new("/art/p.md"),
3497 )
3498 .unwrap();
3499 assert!(p.argv.windows(2).any(|w| w == ["--print-timeout", "3600s"]));
3500 }
3501
3502 #[test]
3509 fn attachments_widen_antigravitys_add_dir_even_off_file_delivery() {
3510 let mut s = spec(AgentKind::Antigravity, None);
3511 s.prompt_delivery = Some(Delivery::Argv);
3512 let seat = SeatState::new("talk", "a", 7);
3513 let atts = [PathBuf::from("/art/attachments/abc.png")];
3514
3515 let without = build_command(
3516 &s,
3517 &seat,
3518 &Invocation {
3519 attachments: &[],
3520 writable: &[],
3521 ..inv(Path::new("."), Path::new("/art"), true)
3522 },
3523 Path::new("/art/p.md"),
3524 )
3525 .unwrap();
3526 assert!(
3527 !without.argv.iter().any(|a| a == "--add-dir"),
3528 "no attachment, no reason to widen the sandbox: {without:?}"
3529 );
3530
3531 let with = build_command(
3532 &s,
3533 &seat,
3534 &Invocation {
3535 attachments: &atts,
3536 writable: &[],
3537 ..inv(Path::new("."), Path::new("/art"), true)
3538 },
3539 Path::new("/art/p.md"),
3540 )
3541 .unwrap();
3542 assert!(
3543 with.argv.windows(2).any(|w| w == ["--add-dir", "/art"]),
3544 "an attachment outside cwd must widen the sandbox even off File delivery: {with:?}"
3545 );
3546 }
3547
3548 #[test]
3554 fn an_inherited_attachment_outside_this_conversations_artifacts_dir_gets_its_own_add_dir() {
3555 let seat = SeatState::new("plan", "a", 7);
3556 let atts = [
3557 PathBuf::from("/art/attachments/own.png"),
3558 PathBuf::from("/other-chat/attachments/inherited.png"),
3559 ];
3560
3561 let p = build_command(
3562 &spec(AgentKind::Antigravity, None),
3563 &seat,
3564 &Invocation {
3565 attachments: &atts,
3566 writable: &[],
3567 ..inv(Path::new("."), Path::new("/art"), true)
3568 },
3569 Path::new("/art/p.md"),
3570 )
3571 .unwrap();
3572
3573 assert!(
3574 p.argv.windows(2).any(|w| w == ["--add-dir", "/art"]),
3575 "this conversation's own artifacts dir must still be granted: {p:?}"
3576 );
3577 assert!(
3578 p.argv
3579 .windows(2)
3580 .any(|w| w == ["--add-dir", "/other-chat/attachments"]),
3581 "the inherited attachment's own directory must be granted too: {p:?}"
3582 );
3583 }
3584
3585 #[test]
3586 fn command_agents_get_placeholders_substituted() {
3587 let seat = SeatState::new("impl-A", "a", 7);
3588 let p = plan_for(AgentKind::Command, &seat, true);
3589 assert_eq!(p.argv[0], "echo");
3590 assert_eq!(p.argv[1], "impl-A");
3591 assert_eq!(p.stdin.as_deref(), Some("do the thing"));
3592 }
3593
3594 const EXPIRED_AUTH: &str = r#"{"is_error":true,"terminal_reason":"api_error","result":"Failed to authenticate: OAuth session expired and could not be refreshed"}"#;
3595 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."}
3596{"type":"turn.failed","error":{"message":"You've hit your usage limit."}}"#;
3597
3598 #[test]
3599 fn observed_machine_failures_are_detected_conservatively() {
3600 let auth = extract(AgentKind::Claude, EXPIRED_AUTH).quota.unwrap();
3601 assert_eq!(auth.cause, QuotaCause::Authentication);
3602 assert_eq!(auth.reset, None);
3603 let limit = extract(AgentKind::Codex, CODEX_LIMIT).quota.unwrap();
3604 assert_eq!(limit.cause, QuotaCause::UsageLimit);
3605 assert_eq!(limit.reset.as_deref(), Some("Oct 27th, 2026 6:18 PM"));
3606 assert!(
3608 extract(AgentKind::Codex, &format!("{CODEX_LIMIT}\n{CODEX_LIMIT}"))
3609 .quota
3610 .is_some()
3611 );
3612 let without_reset = CODEX_LIMIT.replace(" or try again at Oct 27th, 2026 6:18 PM", "");
3613 assert!(
3614 extract(AgentKind::Codex, &without_reset)
3615 .quota
3616 .unwrap()
3617 .reset
3618 .is_none()
3619 );
3620 for text in [
3621 EXPIRED_AUTH.replace("true", "false"),
3622 EXPIRED_AUTH.replace("api_error", "unknown"),
3623 EXPIRED_AUTH.replace(
3624 "OAuth session expired and could not be refreshed",
3625 "unknown error",
3626 ),
3627 ] {
3628 assert!(extract(AgentKind::Claude, &text).quota.is_none());
3629 }
3630 assert!(
3631 extract(AgentKind::Codex, CODEX_LIMIT.lines().next().unwrap())
3632 .quota
3633 .is_none()
3634 );
3635 assert!(
3636 extract(
3637 AgentKind::Codex,
3638 &CODEX_LIMIT.replace("You've hit your usage limit.", "Something failed.")
3639 )
3640 .quota
3641 .is_none()
3642 );
3643 let quoted = serde_json::json!({"type":"item.completed","item":{"type":"agent_message","text":CODEX_LIMIT}}).to_string();
3644 assert!(extract(AgentKind::Codex, "ed).quota.is_none());
3645 assert!(extract(AgentKind::Codex, EXPIRED_AUTH).quota.is_none());
3646 assert!(
3647 extract(AgentKind::Antigravity, EXPIRED_AUTH)
3648 .quota
3649 .is_none()
3650 );
3651 let legacy: Quota = serde_json::from_str(r#"{"reset":null}"#).unwrap();
3652 assert_eq!(legacy.cause, QuotaCause::UsageLimit);
3653 }
3654
3655 #[test]
3656 fn claude_rate_limit_is_detected_and_reset_read_when_present() {
3657 let stdout = r#"{"is_error": true, "terminal_reason": "api_error",
3659 "result": "You've hit your session limit · resets 4:50am (Asia/Tokyo)",
3660 "session_id": "b8e928f1-754e-4bd3-86c5-0567763654e3"}"#;
3661 let out = extract(AgentKind::Claude, stdout);
3662 let quota = out.quota.as_ref().expect("rate limit must be detected");
3663 assert_eq!(
3664 quota.reset.as_deref(),
3665 Some("4:50am (Asia/Tokyo)"),
3666 "reset time read from the body"
3667 );
3668 }
3669
3670 #[test]
3671 fn claude_rate_limit_without_a_readable_reset_is_still_detected() {
3672 let out = extract(
3673 AgentKind::Claude,
3674 r#"{"is_error":true,"result":"session limit reached"}"#,
3675 );
3676 let quota = out.quota.expect("rate limit detected without a reset");
3677 assert!(quota.reset.is_none(), "unknown reset is kept as unknown");
3678 }
3679
3680 #[test]
3681 fn claude_structured_usage_limit_requires_the_error_and_exact_pair() {
3682 for kind in [AgentKind::Claude, AgentKind::Command] {
3683 for reply in [
3684 r#"{"is_error":true,"api_error_status":429,"api_error":"usage_limit_reached"}"#,
3685 r#"{"is_error":true,"api_error_status":"429","api_error":"usage_limit_reached"}"#,
3686 ] {
3687 assert!(extract(kind, reply).quota.is_some(), "{reply}");
3688 }
3689 for reply in [
3690 r#"{"is_error":false,"api_error_status":429,"api_error":"usage_limit_reached"}"#,
3691 r#"{"is_error":true,"api_error_status":500,"api_error":"usage_limit_reached"}"#,
3692 r#"{"is_error":true,"api_error_status":429,"api_error":"other_error"}"#,
3693 r#"{"is_error":false,"api_error_status":"429","api_error":"usage_limit_reached"}"#,
3694 r#"{"is_error":true,"api_error_status":"500","api_error":"usage_limit_reached"}"#,
3695 r#"{"is_error":true,"api_error_status":"429","api_error":"other_error"}"#,
3696 r#"{"is_error":true,"api_error":"usage_limit_reached"}"#,
3697 ] {
3698 assert!(extract(kind, reply).quota.is_none(), "{reply}");
3699 }
3700 }
3701 }
3702
3703 #[test]
3704 fn ordinary_failures_are_never_quota() {
3705 let claude_fail = extract(
3707 AgentKind::Claude,
3708 r#"{"is_error":true,"result":"account does not exist"}"#,
3709 );
3710 assert!(claude_fail.quota.is_none());
3711
3712 let cmd_fail = extract(AgentKind::Command, "boom");
3714 assert!(cmd_fail.quota.is_none());
3715
3716 let success = extract(
3718 AgentKind::Command,
3719 r#"{"is_error":false,"result":"session limit is fine"}"#,
3720 );
3721 assert!(success.quota.is_none());
3722 }
3723
3724 #[test]
3732 fn codex_command_execution_events_are_captured_alongside_the_final_message() {
3733 let stream = concat!(
3734 r#"{"type":"thread.started","thread_id":"t1"}"#,
3735 "\n",
3736 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"}}"#,
3737 "\n",
3738 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"}}"#,
3739 "\n",
3740 r#"{"type":"item.completed","item":{"id":"item99","type":"agent_message","text":"Both tests in the target pass."}}"#,
3741 "\n",
3742 r#"{"type":"turn.completed"}"#,
3743 "\n",
3744 );
3745 let out = extract(AgentKind::Codex, stream);
3746 assert_eq!(out.text, "Both tests in the target pass.");
3747 assert_eq!(out.commands.len(), 2, "{:?}", out.commands);
3748
3749 let paired = &out.commands[0];
3750 assert_eq!(paired.id, "item49");
3751 assert_eq!(paired.exit_code, Some(1));
3752 assert!(paired.description.contains("graph_cached_gate"));
3753 assert!(paired.result_summary.contains("1 failed"));
3754
3755 let solo = &out.commands[1];
3756 assert_eq!(solo.exit_code, Some(0));
3757
3758 assert!(
3762 out.commands
3763 .iter()
3764 .any(|c| c.exit_code != Some(0) && c.description.contains("graph_cached_gate")),
3765 "a failed run of the actual target must still be visible: {:?}",
3766 out.commands
3767 );
3768 }
3769
3770 #[test]
3771 fn command_agent_can_carry_the_claude_quota_shape() {
3772 let out = extract(
3773 AgentKind::Command,
3774 r#"{"is_error":true,"result":"You've hit your session limit · resets 1:00am (UTC)"}"#,
3775 );
3776 assert!(
3777 out.quota.is_some(),
3778 "a wrapper emitting the claude shape counts as quota"
3779 );
3780 }
3781
3782 #[test]
3783 fn claude_json_result_is_extracted() {
3784 let out = extract(
3785 AgentKind::Claude,
3786 r#"{"result":"all done","session_id":"abc","is_error":false}"#,
3787 );
3788 assert_eq!(out.text, "all done");
3789 assert_eq!(out.session.as_deref(), Some("abc"));
3790 assert_eq!(out.status.as_deref(), Some("success"));
3791 }
3792
3793 #[test]
3808 fn a_clean_cli_turn_is_not_the_same_fact_as_the_nodes_own_work_being_done() {
3809 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"}"#;
3810 let out = extract(AgentKind::Claude, stdout);
3811 assert_eq!(out.status.as_deref(), Some("success"));
3812 assert!(out.quota.is_none());
3813 assert!(!out.text.trim().is_empty());
3814
3815 let agent_out = AgentOutput {
3816 text: out.text.clone(),
3817 exit_code: Some(0),
3818 timed_out: false,
3819 duration_ms: 500,
3820 artifacts: Vec::new(),
3821 quota: out.quota,
3822 dropped: out.dropped,
3823 commands: out.commands,
3824 context_tokens: None,
3825 };
3826 assert!(
3827 agent_out.usable(),
3828 "the CLI turn itself ended cleanly and must read as usable"
3829 );
3830 assert!(
3831 crate::verdict::extract_json::<crate::verdict::FixReport>(&agent_out.text).is_err(),
3832 "a clean CLI turn is not proof the node's own report ever arrived"
3833 );
3834 }
3835
3836 #[test]
3837 fn opencode_event_stream_is_concatenated() {
3838 let stream = concat!(
3839 r#"{"type":"step_start","sessionID":"ses_1","part":{"type":"step-start"}}"#,
3840 "\n",
3841 r#"{"type":"text","sessionID":"ses_1","part":{"type":"text","text":"first"}}"#,
3842 "\n",
3843 "garbage line\n",
3844 r#"{"type":"text","sessionID":"ses_1","part":{"type":"text","text":"second"}}"#,
3845 "\n"
3846 );
3847 let out = extract(AgentKind::Opencode, stream);
3848 assert_eq!(out.text, "first\nsecond");
3849 assert_eq!(out.session.as_deref(), Some("ses_1"));
3850 }
3851
3852 #[test]
3853 fn agy_json_survives_a_leading_warning_line() {
3854 let stdout = concat!(
3855 "warning: --mode plan has no effect while slash commands are disabled.\n",
3856 r#"{"conversation_id":"eaf2d00a","status":"SUCCESS","response":"persimmon\n"}"#,
3857 "\n"
3858 );
3859 let out = extract(AgentKind::Antigravity, stdout);
3860 assert_eq!(out.text, "persimmon");
3861 assert_eq!(out.session.as_deref(), Some("eaf2d00a"));
3862 assert_eq!(out.status.as_deref(), Some("SUCCESS"));
3863 }
3864
3865 const AGY_DROPPED: &str = concat!(
3872 r#"{"conversation_id":"36743d06-c0b3-4b79-9fa2-23869289d7b6","status":"ERROR","#,
3873 r#""response":"","error":"the connection to the agent was interrupted before "#,
3874 r#"the response finished: subscriber fell behind updates, stalled for 5s","#,
3875 r#""duration_seconds":431.1941803,"num_turns":1,"usage":{"input_tokens":260113,"#,
3876 r#""output_tokens":14267,"thinking_tokens":9695,"cache_read_tokens":2200925,"#,
3877 r#""total_tokens":274380}}"#
3878 );
3879
3880 const AGY_QUOTA_OUT: &str = concat!(
3882 r#"{"conversation_id":"323c3b5b-0000","status":"ERROR","response":"","#,
3883 r#""error":"Individual quota reached. Please upgrade your subscription to "#,
3884 r#"increase your limits. Resets in 1h2m49s.","duration_seconds":265.9,"#,
3885 r#""num_turns":2,"usage":{"input_tokens":1000,"output_tokens":50}}"#
3886 );
3887 const AGY_QUOTA_ERR: &str = concat!(
3888 "error: Individual quota reached. Resets in 1h2m49s.\n",
3889 r#"AGY_ERROR: {"short_error":"RESOURCE_EXHAUSTED (code 429): Individual quota "#,
3890 r#"reached.","status":"RESOURCE_EXHAUSTED","error_code":429,"code_kind":"http","#,
3891 r#""retryable":true}"#,
3892 "\n"
3893 );
3894
3895 #[test]
3896 fn agy_out_of_quota_is_a_quota_with_the_reset_hint() {
3897 let both = agy_quota(AGY_QUOTA_OUT, AGY_QUOTA_ERR).expect("both streams");
3898 assert_eq!(both.reset.as_deref(), Some("in 1h2m49s"));
3899 let stdout_only = agy_quota(AGY_QUOTA_OUT, "").expect("stdout alone");
3900 assert_eq!(stdout_only.reset.as_deref(), Some("in 1h2m49s"));
3901 let stderr_only = agy_quota("not json", AGY_QUOTA_ERR).expect("stderr alone");
3903 assert!(stderr_only.reset.is_none());
3904 }
3905
3906 #[test]
3907 fn ordinary_agy_failures_are_not_a_quota() {
3908 assert!(agy_quota(AGY_DROPPED, "").is_none());
3909 assert!(agy_quota(r#"{"status":"ERROR","error":"boom"}"#, "").is_none());
3910 assert!(
3911 agy_quota(
3912 "",
3913 r#"AGY_ERROR: {"status":"RESOURCE_EXHAUSTED","error_code":500}"#
3914 )
3915 .is_none()
3916 );
3917 assert!(
3918 agy_quota(
3919 "",
3920 r#"AGY_ERROR: {"status":"UNAVAILABLE","error_code":429}"#
3921 )
3922 .is_none()
3923 );
3924 assert!(agy_quota(r#"{"status":"SUCCESS","response":"ok"}"#, "").is_none());
3925 }
3926
3927 #[test]
3928 fn a_cli_that_hangs_up_on_billed_work_is_not_an_agent_that_produced_nothing() {
3929 let out = extract(AgentKind::Antigravity, AGY_DROPPED);
3930 let dropped = out.dropped.expect("recognised as undelivered work");
3931 assert_eq!(dropped.output_tokens, 14267);
3932 assert!(
3933 dropped.why.contains("subscriber fell behind"),
3934 "the CLI's own words are kept for the record: {}",
3935 dropped.why
3936 );
3937 assert_eq!(
3940 out.session.as_deref(),
3941 Some("36743d06-c0b3-4b79-9fa2-23869289d7b6")
3942 );
3943 assert!(out.quota.is_none(), "a dropped stream is not a rate limit");
3944 }
3945
3946 #[test]
3947 fn an_error_with_nothing_produced_stays_an_ordinary_failure() {
3948 let bare = r#"{"conversation_id":"c1","status":"ERROR","response":"","error":"boom"}"#;
3952 assert!(extract(AgentKind::Antigravity, bare).dropped.is_none());
3953
3954 let answered = concat!(
3957 r#"{"conversation_id":"c2","status":"ERROR","response":"here it is","#,
3958 r#""usage":{"output_tokens":10}}"#
3959 );
3960 assert!(extract(AgentKind::Antigravity, answered).dropped.is_none());
3961
3962 let ok = concat!(
3964 r#"{"conversation_id":"c3","status":"SUCCESS","response":"done","#,
3965 r#""usage":{"output_tokens":10}}"#
3966 );
3967 assert!(extract(AgentKind::Antigravity, ok).dropped.is_none());
3968 }
3969
3970 #[test]
3971 fn an_undelivered_output_is_not_usable_but_is_worth_asking_again() {
3972 let out = AgentOutput {
3973 text: String::new(),
3974 exit_code: Some(1),
3975 timed_out: false,
3976 duration_ms: 431_194,
3977 artifacts: Vec::new(),
3978 quota: None,
3979 dropped: Some(Dropped {
3980 why: "subscriber fell behind updates".to_owned(),
3981 output_tokens: 14267,
3982 }),
3983 commands: Vec::new(),
3984 context_tokens: None,
3985 };
3986 assert!(!out.usable());
3987 assert!(out.work_undelivered());
3988 assert!(!out.quota_exhausted());
3991 }
3992
3993 #[test]
3994 fn non_json_stdout_falls_back_to_raw_text() {
3995 let out = extract(AgentKind::Antigravity, "plain answer\n");
3996 assert_eq!(out.text, "plain answer");
3997 assert!(out.session.is_none());
3998 }
3999
4000 #[tokio::test]
4001 async fn command_agent_round_trip_writes_artifacts() {
4002 let dir = tempfile::tempdir().unwrap();
4003 let art = dir.path().join("artifacts");
4004 let mut seat = SeatState::new("impl-A", "a", 7);
4005 let s = command_helper("reply");
4006 let out = invoke(
4007 &s,
4008 &mut seat,
4009 &Invocation {
4010 coordination: None,
4011 fetched_base: None,
4012 cwd: dir.path(),
4013 prompt: "unused",
4014 timeout: Duration::from_secs(30),
4015 allow_write: true,
4016 sessions: true,
4017 artifacts: &art,
4018 stem: "impl-A",
4019 run: "test-run",
4020 node: "test",
4021 cache_dir: None,
4022 attachments: &[],
4023 writable: &[],
4024 },
4025 )
4026 .await
4027 .unwrap();
4028 assert!(out.usable(), "{out:?}");
4029 assert!(out.text.contains("hello impl-A"), "{}", out.text);
4030 assert_eq!(seat.turns, 1);
4031 assert!(art.join("impl-A.prompt.md").is_file());
4032 assert!(art.join("impl-A.out").is_file());
4033 }
4034
4035 #[tokio::test]
4036 async fn the_invocation_cache_dir_reaches_the_seat_as_cargo_target_dir() {
4037 crate::run::pin_test_home();
4038 let dir = tempfile::tempdir().unwrap();
4042 let cache = dir.path().join("magi-cache");
4043 let mut seat = SeatState::new("impl-A", "a", 7);
4044 let s = command_helper("cache");
4045 let out = invoke(
4046 &s,
4047 &mut seat,
4048 &Invocation {
4049 coordination: None,
4050 fetched_base: None,
4051 cwd: dir.path(),
4052 prompt: "unused",
4053 timeout: Duration::from_secs(30),
4054 allow_write: true,
4055 sessions: true,
4056 artifacts: &dir.path().join("artifacts"),
4057 stem: "cache",
4058 run: "test-run",
4059 node: "test",
4060 cache_dir: Some(&cache),
4061 attachments: &[],
4062 writable: &[],
4063 },
4064 )
4065 .await
4066 .unwrap();
4067 assert!(out.usable(), "{out:?}");
4068 assert!(
4069 out.text.contains(cache.to_string_lossy().as_ref()),
4070 "the seat must see CARGO_TARGET_DIR = the shared cache"
4071 );
4072 }
4073
4074 #[tokio::test]
4075 async fn cache_dir_none_strips_a_cargo_target_dir_inherited_from_this_process() {
4076 let previous = std::env::var("CARGO_TARGET_DIR").ok();
4084 unsafe {
4089 std::env::set_var("CARGO_TARGET_DIR", "/should/never/reach/a/read-only/seat");
4090 }
4091 let dir = tempfile::tempdir().unwrap();
4092 let mut seat = SeatState::new("review-1", "a", 7);
4093 let s = command_helper("no-cache");
4094 let result = invoke(
4095 &s,
4096 &mut seat,
4097 &Invocation {
4098 coordination: None,
4099 fetched_base: None,
4100 cwd: dir.path(),
4101 prompt: "unused",
4102 timeout: Duration::from_secs(30),
4103 allow_write: false,
4104 sessions: true,
4105 artifacts: &dir.path().join("artifacts"),
4106 stem: "no-cache",
4107 run: "test-run",
4108 node: "test",
4109 cache_dir: None,
4110 attachments: &[],
4111 writable: &[],
4112 },
4113 )
4114 .await;
4115 unsafe {
4120 match &previous {
4121 Some(v) => std::env::set_var("CARGO_TARGET_DIR", v),
4122 None => std::env::remove_var("CARGO_TARGET_DIR"),
4123 }
4124 }
4125 let out = result.unwrap();
4126 assert!(out.usable(), "{out:?}");
4127 assert!(
4128 out.text.contains("ABSENT"),
4129 "a read-only seat must never inherit the process's own CARGO_TARGET_DIR: {}",
4130 out.text
4131 );
4132 }
4133
4134 #[tokio::test]
4135 async fn a_prompt_larger_than_the_pipe_buffer_does_not_deadlock() {
4136 let dir = tempfile::tempdir().unwrap();
4137 let mut seat = SeatState::new("impl-A", "a", 7);
4138 let s = command_helper("ignore-stdin");
4141 let big = "x".repeat(1_000_000);
4142 let out = invoke(
4143 &s,
4144 &mut seat,
4145 &Invocation {
4146 coordination: None,
4147 fetched_base: None,
4148 cwd: dir.path(),
4149 prompt: &big,
4150 timeout: Duration::from_secs(60),
4151 allow_write: true,
4152 sessions: true,
4153 artifacts: &dir.path().join("artifacts"),
4154 stem: "big",
4155 run: "test-run",
4156 node: "test",
4157 cache_dir: None,
4158 attachments: &[],
4159 writable: &[],
4160 },
4161 )
4162 .await
4163 .unwrap();
4164 assert!(out.usable(), "{out:?}");
4165 assert!(out.text.contains("done"), "{}", out.text);
4166 }
4167
4168 #[tokio::test]
4169 async fn agent_turn_cap_limits_a_direct_invocation() {
4170 let dir = tempfile::tempdir().unwrap();
4171 let artifacts = dir.path().join("artifacts");
4172 let mut seat = SeatState::new("impl-A", "helper", 7);
4173 let mut s = command_helper("sleep");
4174 s.max_turn_secs = Some(2);
4175 let out = invoke(&s, &mut seat, &inv(dir.path(), &artifacts, false))
4176 .await
4177 .unwrap();
4178 assert!(out.timed_out, "{out:?}");
4179 assert!(out.duration_ms < 20_000, "{out:?}");
4182 }
4183
4184 #[tokio::test]
4185 async fn timeout_is_reported_not_hung() {
4186 let dir = tempfile::tempdir().unwrap();
4187 let mut seat = SeatState::new("impl-A", "a", 7);
4188 let s = command_helper("sleep");
4189 let out = invoke(
4190 &s,
4191 &mut seat,
4192 &Invocation {
4193 coordination: None,
4194 fetched_base: None,
4195 cwd: dir.path(),
4196 prompt: "unused",
4197 timeout: Duration::from_millis(300),
4198 allow_write: true,
4199 sessions: true,
4200 artifacts: &dir.path().join("artifacts"),
4201 stem: "slow",
4202 run: "test-run",
4203 node: "test",
4204 cache_dir: None,
4205 attachments: &[],
4206 writable: &[],
4207 },
4208 )
4209 .await
4210 .unwrap();
4211 assert!(out.timed_out);
4212 assert!(!out.usable());
4213 }
4214
4215 #[tokio::test]
4216 async fn a_timeout_keeps_what_the_agent_had_already_printed() {
4217 let dir = tempfile::tempdir().unwrap();
4223 let artifacts = dir.path().join("artifacts");
4224 let mut seat = SeatState::new("impl-A", "a", 7);
4225 let s = command_helper("chatty-sleep");
4226 let out = invoke(
4227 &s,
4228 &mut seat,
4229 &Invocation {
4230 coordination: None,
4231 fetched_base: None,
4232 cwd: dir.path(),
4233 prompt: "unused",
4234 timeout: Duration::from_secs(10),
4239 allow_write: true,
4240 sessions: true,
4241 artifacts: &artifacts,
4242 stem: "chatty",
4243 run: "test-run",
4244 node: "test",
4245 cache_dir: None,
4246 attachments: &[],
4247 writable: &[],
4248 },
4249 )
4250 .await
4251 .unwrap();
4252
4253 assert!(out.timed_out, "{out:?}");
4254 assert!(!out.usable(), "a cut-off answer is still not an answer");
4255 let recorded = std::fs::read_to_string(artifacts.join("chatty.out")).unwrap();
4256 assert!(
4257 recorded.contains("i-said-something"),
4258 "the artifact must keep what arrived before the kill, got {recorded:?}"
4259 );
4260 assert!(
4261 out.text.contains("i-said-something"),
4262 "and the graph must be able to see it too, got {:?}",
4263 out.text
4264 );
4265 }
4266
4267 #[test]
4268 fn missing_programs_reports_command_binaries() {
4269 let mut s = spec(AgentKind::Command, None);
4270 s.command = vec!["definitely-not-a-real-binary-xyz".to_owned()];
4271 assert_eq!(
4272 missing_programs(&[s]),
4273 ["definitely-not-a-real-binary-xyz".to_owned()]
4274 );
4275 }
4276
4277 fn pick_spec(id: &str, kind: AgentKind) -> AgentSpec {
4278 AgentSpec {
4279 id: id.to_owned(),
4280 kind,
4281 model: None,
4282 command: Vec::new(),
4283 extra_args: Vec::new(),
4284 env: BTreeMap::new(),
4285 prompt_delivery: None,
4286 max_turn_secs: None,
4287 }
4288 }
4289
4290 fn without<'a>(missing: &'a [&'a str]) -> impl Fn(&AgentSpec) -> bool + 'a {
4293 move |a: &AgentSpec| !missing.contains(&a.id.as_str())
4294 }
4295
4296 #[test]
4297 fn pick_prefers_the_claude_seat_even_when_it_is_not_first_in_the_roster() {
4298 let agents = [
4299 pick_spec("oc", AgentKind::Opencode),
4300 pick_spec("opus", AgentKind::Claude),
4301 pick_spec("agy", AgentKind::Antigravity),
4302 ];
4303 let got = pick(&agents, None, &without(&[])).expect("a pick");
4304 assert_eq!(got.id, "opus");
4305 }
4306
4307 #[test]
4308 fn pick_falls_back_to_the_first_installed_agent_in_roster_order() {
4309 let agents = [
4310 pick_spec("opus", AgentKind::Claude),
4311 pick_spec("oc", AgentKind::Opencode),
4312 pick_spec("agy", AgentKind::Antigravity),
4313 ];
4314 let got = pick(&agents, None, &without(&["opus", "oc"])).expect("a pick");
4315 assert_eq!(got.id, "agy");
4316 }
4317
4318 #[test]
4319 fn pick_on_an_empty_roster_says_what_to_install() {
4320 let msg = pick(&[], None, &without(&[]))
4321 .expect_err("nobody to ask")
4322 .to_string();
4323 assert!(msg.contains("roster is empty"), "{msg}");
4324 assert!(msg.contains("claude"), "{msg}");
4325 assert!(msg.contains("magi.toml"), "{msg}");
4326 }
4327
4328 #[test]
4329 fn pick_on_a_roster_with_nothing_installed_names_the_programs_that_are_missing() {
4330 let agents = [
4331 pick_spec("opus", AgentKind::Claude),
4332 pick_spec("oc", AgentKind::Opencode),
4333 ];
4334 let err = pick(&agents, None, &without(&["opus", "oc"])).expect_err("nothing runnable");
4335 let msg = format!("{err:#}");
4336 assert!(msg.contains("claude"), "{msg}");
4337 assert!(msg.contains("opencode"), "{msg}");
4338 }
4339
4340 #[test]
4341 fn an_explicitly_named_agent_wins_over_the_claude_preference() {
4342 let agents = [
4343 pick_spec("opus", AgentKind::Claude),
4344 pick_spec("oc", AgentKind::Opencode),
4345 ];
4346 let got = pick(&agents, Some("oc"), &without(&[])).expect("a pick");
4347 assert_eq!(got.id, "oc");
4348 }
4349
4350 #[test]
4351 fn an_unknown_agent_id_lists_the_ids_that_do_exist() {
4352 let agents = [
4353 pick_spec("opus", AgentKind::Claude),
4354 pick_spec("oc", AgentKind::Opencode),
4355 ];
4356 let msg = pick(&agents, Some("gemini"), &without(&[]))
4357 .expect_err("no such agent")
4358 .to_string();
4359 assert!(msg.contains("gemini"), "{msg}");
4360 assert!(msg.contains("opus, oc"), "{msg}");
4361 }
4362
4363 #[test]
4364 fn an_explicitly_named_agent_that_is_not_installed_is_an_error_not_a_fallback() {
4365 let agents = [
4366 pick_spec("opus", AgentKind::Claude),
4367 pick_spec("oc", AgentKind::Opencode),
4368 ];
4369 let msg = pick(&agents, Some("oc"), &without(&["oc"]))
4370 .expect_err("must not silently substitute another model")
4371 .to_string();
4372 assert!(msg.contains("opencode"), "{msg}");
4373 assert!(msg.contains("--agent"), "{msg}");
4374 }
4375
4376 fn named(id: &str) -> AgentSpec {
4377 AgentSpec {
4378 id: id.to_owned(),
4379 ..spec(AgentKind::Command, None)
4380 }
4381 }
4382
4383 fn output(text: &str, exit: i32, quota: bool) -> AgentOutput {
4384 AgentOutput {
4385 text: text.to_owned(),
4386 exit_code: Some(exit),
4387 timed_out: false,
4388 duration_ms: 0,
4389 artifacts: Vec::new(),
4390 quota: quota.then_some(Quota {
4391 reset: None,
4392 cause: QuotaCause::UsageLimit,
4393 agent: String::new(),
4394 }),
4395 dropped: None,
4396 commands: Vec::new(),
4397 context_tokens: None,
4398 }
4399 }
4400
4401 #[test]
4402 fn a_chain_keeps_the_written_order_and_a_string_is_a_chain_of_one() {
4403 let agents = [named("a"), named("b"), named("c")];
4404 let all = |_: &AgentSpec| true;
4405 let chain = AgentChoice::Chain(vec!["c".into(), "a".into()]);
4406 let got = pick_chain(&agents, Some(&chain), &all, "synthesizer").unwrap();
4407 assert_eq!(
4408 got.iter().map(|s| s.id.as_str()).collect::<Vec<_>>(),
4409 ["c", "a"]
4410 );
4411
4412 let one = AgentChoice::from("b");
4413 let got = pick_chain(&agents, Some(&one), &all, "synthesizer").unwrap();
4414 assert_eq!(got.len(), 1);
4415 assert_eq!(got[0].id, "b");
4416
4417 let got = pick_chain(&agents, None, &all, "synthesizer").unwrap();
4418 assert_eq!(got.len(), 1, "unset keeps pick's default");
4419 assert_eq!(got[0].id, "a");
4420 let empty = AgentChoice::Chain(Vec::new());
4421 assert_eq!(
4422 pick_chain(&agents, Some(&empty), &all, "x").unwrap()[0].id,
4423 "a"
4424 );
4425 }
4426
4427 #[test]
4428 fn a_chain_skips_unknown_and_uninstalled_ids_and_tries_each_once() {
4429 let agents = [named("a"), named("b")];
4430 let not_a = |s: &AgentSpec| s.id != "a";
4431 let chain = AgentChoice::Chain(
4432 ["a", "ghost", "b", "b"]
4433 .iter()
4434 .map(|s| (*s).to_owned())
4435 .collect(),
4436 );
4437 let got = pick_chain(&agents, Some(&chain), ¬_a, "chatter").unwrap();
4438 assert_eq!(got.iter().map(|s| s.id.as_str()).collect::<Vec<_>>(), ["b"]);
4439
4440 let dup = AgentChoice::Chain(vec!["b".into(), "a".into(), "b".into()]);
4441 let got = pick_chain(&agents, Some(&dup), &|_| true, "chatter").unwrap();
4442 assert_eq!(
4443 got.iter().map(|s| s.id.as_str()).collect::<Vec<_>>(),
4444 ["b", "a"]
4445 );
4446 }
4447
4448 #[test]
4449 fn a_chain_with_nothing_runnable_names_the_role() {
4450 let agents = [named("a")];
4451 let chain = AgentChoice::Chain(vec!["a".into(), "ghost".into()]);
4452 let err = pick_chain(&agents, Some(&chain), &|_| false, "conductor")
4453 .unwrap_err()
4454 .to_string();
4455 assert!(err.contains("conductor"), "{err}");
4456 }
4457
4458 #[test]
4459 fn a_chain_advances_on_error_quota_or_an_unusable_answer_only() {
4460 assert!(chain_advances(&Err(anyhow::anyhow!("spawn failed"))));
4461 assert!(chain_advances(&Ok(output("limit", 0, true))));
4462 assert!(chain_advances(&Ok(output("", 0, false))));
4463 assert!(chain_advances(&Ok(output("x", 1, false))));
4464 assert!(!chain_advances(&Ok(output("answer", 0, false))));
4465 }
4466
4467 #[test]
4468 fn claude_context_tokens_are_unknown_because_usage_is_aggregated() {
4469 for out in [
4470 r#"{"result":"ok","num_turns":1,"usage":{"input_tokens":10,"cache_read_input_tokens":3000}}"#,
4471 r#"{"result":"ok","num_turns":3,"usage":{"input_tokens":10}}"#,
4472 r#"{"result":"ok"}"#,
4473 "not json",
4474 ] {
4475 assert_eq!(context_tokens(AgentKind::Claude, out), None, "{out}");
4476 }
4477 }
4478
4479 #[test]
4480 fn opencode_context_tokens_take_the_last_step_finish() {
4481 let out = concat!(
4482 r#"{"type":"step_finish","sessionID":"s","part":{"type":"step-finish","tokens":{"input":100,"output":5,"cache":{"read":1000,"write":50}}}}"#,
4483 "\n",
4484 r#"{"type":"text","part":{"type":"text","text":"hi"}}"#,
4485 "\n",
4486 r#"{"type":"step_finish","sessionID":"s","part":{"type":"step-finish","tokens":{"input":120,"output":9,"cache":{"read":1500}}}}"#,
4487 "\n"
4488 );
4489 assert_eq!(context_tokens(AgentKind::Opencode, out), Some(1620));
4490 let none = r#"{"type":"step_finish","part":{"type":"step-finish"}}"#;
4491 assert_eq!(context_tokens(AgentKind::Opencode, none), None);
4492 assert_eq!(context_tokens(AgentKind::Opencode, ""), None);
4493 }
4494
4495 #[test]
4496 fn agy_context_tokens_are_unknown_because_usage_is_aggregated() {
4497 let out = r#"{"conversation_id":"c","status":"OK","response":"x","usage":{"input_tokens":260113,"cache_read_tokens":2200925}}"#;
4498 assert_eq!(context_tokens(AgentKind::Antigravity, out), None);
4499 }
4500
4501 #[test]
4502 fn codex_context_tokens_are_unknown_because_usage_is_cumulative() {
4503 let out = concat!(
4504 r#"{"type":"turn.completed","usage":{"input_tokens":1000,"cached_input_tokens":900}}"#,
4505 "\n"
4506 );
4507 assert_eq!(context_tokens(AgentKind::Codex, out), None);
4508 }
4509
4510 #[test]
4511 fn omp_context_tokens_come_from_messages_without_an_agent_end() {
4512 let out = concat!(
4513 r#"{"type":"session","id":"s"}"#,
4514 "\n",
4515 r#"{"type":"message_end","message":{"role":"assistant","content":[],"usage":{"input":50,"cacheRead":400,"cacheWrite":10}}}"#,
4516 "\n",
4517 r#"{"type":"turn_end","message":{"role":"assistant","content":[],"usage":{"input":70,"cacheRead":500}}}"#,
4518 "\n"
4519 );
4520 assert_eq!(context_tokens(AgentKind::Omp, out), Some(570));
4521 let user_only = r#"{"type":"message_end","message":{"role":"user","usage":{"input":9}}}"#;
4522 assert_eq!(context_tokens(AgentKind::Omp, user_only), None);
4523 let no_usage = r#"{"type":"message_end","message":{"role":"assistant","content":[]}}"#;
4524 assert_eq!(context_tokens(AgentKind::Omp, no_usage), None);
4525 }
4526
4527 #[test]
4528 fn command_agents_report_no_context_tokens() {
4529 let out = r#"{"usage":{"input_tokens":5}}"#;
4530 assert_eq!(context_tokens(AgentKind::Command, out), None);
4531 }
4532}