agengo 0.5.3

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
use crate::{config::Config, contract::string_or_empty, driver, process::run};
use anyhow::{bail, Context, Result};
use serde_json::Value;
use std::{env, ffi::OsStr, path::Path};

/// Check that an agent can be started and say how the run will name it:
/// `None` is Claude Code, a name from `specs/agents.yaml` (`codex`, `agy`) is
/// kept as the name, anything else is the path of a custom adapter.
pub fn executable(agent: Option<&str>) -> Result<Option<String>> {
    let cwd = env::current_dir()?;
    let on_path = |program: &str| crate::process::resolve(OsStr::new(program), &cwd).is_some();
    let Some(name) = agent.filter(|name| *name != driver::CLAUDE) else {
        if on_path(driver::CLAUDE) {
            return Ok(None);
        }
        bail!(
            "Claude Code is not on PATH; install it, or pass --agent {}",
            driver::known_agents().join(", --agent ")
        );
    };
    if let Some(program) = driver::known_program(name) {
        if !on_path(&program) {
            bail!("{name} is not on PATH (agengo runs `{program}`); install it, or pick another --agent");
        }
        if driver::is_experimental(name) {
            eprintln!("agengo: note: support for {name} is experimental; its flags come from its documentation and have not been tried against a signed-in {name}");
        }
        return Ok(Some(name.to_owned()));
    }
    match crate::process::resolve(OsStr::new(name), &cwd) {
        Some(path) => Ok(Some(path.to_string_lossy().into())),
        None => bail!(
            "agent executable not found: {name} (agents known by name: claude, {})",
            driver::known_agents().join(", ")
        ),
    }
}

/// The agent for a command that starts one: `--agent`, then `AGENGO_AGENT`,
/// then `agent:` in `.agengo/config.yaml`, then the only agent installed.
/// With several installed and none chosen it stops and says how to choose.
pub fn select(flag: Option<&str>, root: &Path) -> Result<Option<String>> {
    match driver::selection(flag, root)? {
        driver::Selection::Chosen { name, source } => {
            let agent = executable(Some(&name))?;
            if let Some(line) = crate::config::load(root)?.describe(&name) {
                eprintln!("agengo: models · {line}");
            }
            if source == driver::Source::OnlyOneInstalled && name != driver::CLAUDE {
                eprintln!("agengo: using {name}, the only agent installed (`agengo agent use NAME` or --agent chooses another)");
            }
            Ok(agent)
        }
        driver::Selection::Several(names) => {
            let name = ask_which(&names, root)?;
            let agent = executable(Some(&name))?;
            if let Some(line) = crate::config::load(root)?.describe(&name) {
                eprintln!("agengo: models · {line}");
            }
            Ok(agent)
        }
        driver::Selection::Nothing => bail!(
            "no coding agent found on PATH; install Claude Code (claude), Codex (codex) or Antigravity (agy), or pass --agent EXECUTABLE"
        ),
    }
}

/// Several agents are installed and none is chosen. At a terminal, ask once
/// and keep the answer in `.agengo/config.yaml`; otherwise stop, because
/// nobody can answer, and print the command that settles it.
fn ask_which(names: &[String], root: &Path) -> Result<String> {
    use std::io::{BufRead, IsTerminal, Write};
    let list = names.join(", ");
    let command = format!("agengo agent use {}", names[0]);
    if !(std::io::stdin().is_terminal() && std::io::stderr().is_terminal()) {
        bail!(
            "several agents are installed ({list}) and none is chosen, so agengo will not guess which login to use. Choose one for this repository, for example `{command}`, or pass --agent NAME"
        );
    }
    eprintln!("agengo: several agents are installed and none is chosen. Which one should this repository use?");
    for (number, name) in names.iter().enumerate() {
        eprintln!("  {}) {name}", number + 1);
    }
    eprint!("Number or name: ");
    std::io::stderr().flush().ok();
    let mut answer = String::new();
    std::io::stdin().lock().read_line(&mut answer)?;
    let answer = answer.trim();
    let chosen = answer
        .parse::<usize>()
        .ok()
        .and_then(|number| number.checked_sub(1))
        .and_then(|index| names.get(index))
        .or_else(|| names.iter().find(|name| name.as_str() == answer));
    match chosen {
        Some(name) => {
            crate::config::set_agent(root, Some(name))?;
            eprintln!(
                "agengo: this repository now uses {name} ({})",
                crate::config::PATH
            );
            Ok(name.clone())
        }
        None => bail!("no agent chosen; choose one with `{command}` or pass --agent NAME"),
    }
}

/// How a command names the agent it starts, for the line it prints before
/// calling it. `agent` is what `executable` returned: `None` for Claude Code.
pub fn label(agent: Option<&str>, auth: Auth) -> String {
    let name = agent.map_or_else(
        || "Claude Code".to_owned(),
        |path| {
            Path::new(path)
                .file_name()
                .map_or_else(|| path.to_owned(), |name| name.to_string_lossy().into())
        },
    );
    let login = match auth {
        Auth::Subscription => "subscription login",
        Auth::Api => "API keys",
    };
    format!("agent {name} ({login})")
}

#[derive(Debug)]
pub struct Action {
    pub message: String,
    pub recommendation: String,
    pub reason: String,
}
impl std::fmt::Display for Action {
    fn fmt(&self, display: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        display.write_str(&self.message)
    }
}
impl std::error::Error for Action {}

/// An agent reply together with the token and cost usage it reported.
pub struct Invocation {
    pub reply: Result<Value>,
    /// Normalized usage (see `crate::usage`); `None` when not reported or
    /// when the process never produced output, for example on a timeout.
    pub usage: Option<Value>,
}

/// How agent processes authenticate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Auth {
    /// Use the agent CLI's own login (a Claude or ChatGPT subscription):
    /// API key variables are removed from the agent's environment, because
    /// Claude Code and Codex prefer a key over the login when both exist.
    Subscription,
    /// Pass the environment through unchanged, API keys included.
    Api,
}

/// Variables that make agent CLIs bill an API key instead of the logged-in
/// subscription. `CLAUDE_CODE_OAUTH_TOKEN` is a subscription token and stays.
pub const API_KEY_VARIABLES: [&str; 6] = [
    "ANTHROPIC_API_KEY",
    "ANTHROPIC_AUTH_TOKEN",
    "OPENAI_API_KEY",
    "CODEX_API_KEY",
    "GEMINI_API_KEY",
    "GOOGLE_API_KEY",
];

impl Auth {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Subscription => "subscription",
            Self::Api => "api",
        }
    }

    /// Runs recorded before this setting existed passed the environment
    /// through, so a missing value keeps that behavior on resume.
    pub fn from_stored(value: Option<&str>) -> Result<Self> {
        match value {
            Some("subscription") => Ok(Self::Subscription),
            Some("api") | None => Ok(Self::Api),
            Some(other) => bail!("unknown auth mode: {other}"),
        }
    }
}

pub fn invoke_measured(
    agent: Option<&str>,
    auth: Auth,
    request: &Value,
    cwd: &Path,
    timeout: u64,
    profile: &Value,
    config: &Config,
) -> Invocation {
    let mut usage = None;
    let reply = call(
        agent, auth, request, cwd, timeout, profile, config, &mut usage,
    );
    Invocation { reply, usage }
}

/// Whether an agent's error text is an authentication failure, from Claude
/// Code, Codex or an API behind a custom adapter.
fn authentication_failure(text: &str) -> bool {
    let text = text.to_lowercase();
    [
        "not logged in",
        "please run /login",
        "invalid api key",
        "invalid_api_key",
        "incorrect api key",
        "authentication_error",
        "authentication failed",
        "401 unauthorized",
        "missing bearer",
        "oauth token has expired",
        "credit balance is too low",
        "codex login",
        "please set an auth method",
        "authentication required",
    ]
    .iter()
    .any(|pattern| text.contains(pattern))
}

fn authentication_action(agent: Option<&str>, auth: Auth, message: &str) -> Action {
    let name = agent
        .and_then(|path| Path::new(path).file_name())
        .map_or("claude".into(), |name| name.to_string_lossy().into_owned());
    let (recommendation, reason) = match auth {
        Auth::Subscription => (
            "Log in to the agent CLI on this machine with your subscription (for Claude Code: run claude, then /login; for Codex: codex login), then run agengo resume. To pay with an API key instead, start a new run with --auth api.".to_owned(),
            format!(
                "agengo removed API key variables ({}) from the {name} environment so the subscription login is used, and that login is missing or was refused.",
                API_KEY_VARIABLES.join(", ")
            ),
        ),
        Auth::Api => (
            "Check the API key the agent reads from the environment, or log in with a subscription and start a new run with --auth subscription.".to_owned(),
            format!("This run passes API keys through to {name}, and the key was refused."),
        ),
    };
    Action {
        message: message.into(),
        recommendation,
        reason,
    }
}

#[allow(clippy::too_many_arguments)]
fn call(
    agent: Option<&str>,
    auth: Auth,
    request: &Value,
    cwd: &Path,
    timeout: u64,
    profile: &Value,
    config: &Config,
    usage: &mut Option<Value>,
) -> Result<Value> {
    drive(
        &*driver::for_agent(agent),
        agent,
        auth,
        request,
        cwd,
        timeout,
        profile,
        config,
        usage,
    )
}

#[allow(clippy::too_many_arguments)]
fn drive(
    driver: &dyn driver::Driver,
    agent: Option<&str>,
    auth: Auth,
    request: &Value,
    cwd: &Path,
    timeout: u64,
    profile: &Value,
    config: &Config,
    usage: &mut Option<Value>,
) -> Result<Value> {
    let pick = config.pick(
        string_or_empty(&request["role"]),
        agent.unwrap_or(driver::CLAUDE),
    );
    crate::sandbox::check(config.sandbox, &driver.name(), &driver.sandbox_support())?;
    let mut prepared = driver.prepare(request, profile, &pick)?;
    let mut asked_again = false;
    loop {
        prepared.command.current_dir(cwd);
        if config.sandbox != crate::config::Sandbox::Off {
            crate::sandbox::filter_env(&mut prepared.command, &config.sandbox_env);
        }
        if auth == Auth::Subscription {
            for variable in API_KEY_VARIABLES {
                prepared.command.env_remove(variable);
            }
        }
        let output = run(
            &mut prepared.command,
            Some(prepared.stdin.as_bytes()),
            Some(timeout),
        )?;
        let mut result = driver.parse(&output.stdout);
        // Read usage before any error check: failed attempts are billed too.
        *usage = crate::usage::combine(usage.take(), driver.usage(&mut result));
        if let Some(message) = driver.reported_error(&result) {
            if authentication_failure(&message) {
                return Err(authentication_action(agent, auth, &message).into());
            }
            bail!("{message}");
        }
        if !output.status.success() {
            let error = String::from_utf8_lossy(if output.stderr.is_empty() && result.is_null() {
                &output.stdout
            } else {
                &output.stderr
            });
            let mut tail: Vec<_> = error.trim().chars().rev().take(2400).collect();
            tail.reverse();
            let message = format!(
                "{} exited with code {}\n{}",
                driver.name(),
                output.status.code().unwrap_or(-1),
                tail.into_iter().collect::<String>()
            );
            if authentication_failure(&message) {
                return Err(authentication_action(agent, auth, &message).into());
            }
            bail!("{message}");
        }
        let reply = driver.reply(result);
        if !reply.is_object() && !asked_again {
            if let Some(next) = driver.retry(request, profile, &pick) {
                prepared = next?;
                asked_again = true;
                continue;
            }
        }
        if !reply.is_object() {
            bail!(
                "agent did not return a structured result{}",
                what_it_printed(&output)
            );
        }
        return Ok(reply);
    }
}

/// The end of what the agent printed, so a reply that holds no JSON object
/// can be told from an empty one (an agent that prints nothing when its output
/// is a pipe) and from a refusal.
fn what_it_printed(output: &std::process::Output) -> String {
    let tail = |bytes: &[u8]| {
        let text = String::from_utf8_lossy(bytes);
        let mut chars: Vec<_> = text.trim().chars().rev().take(800).collect();
        chars.reverse();
        chars.into_iter().collect::<String>()
    };
    let (out, err) = (tail(&output.stdout), tail(&output.stderr));
    let mut message = String::new();
    if out.is_empty() {
        message.push_str("\nthe agent printed nothing on stdout");
    } else {
        message.push_str(&format!("\nstdout (end): {out}"));
    }
    if !err.is_empty() {
        message.push_str(&format!("\nstderr (end): {err}"));
    }
    message
}

pub fn existing_source(path: &Path) -> Result<String> {
    std::fs::read_to_string(path).with_context(|| format!("cannot read {}", path.display()))
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(unix)]
    use crate::config::Sandbox;
    use serde_json::json;

    #[test]
    fn label_names_the_agent_and_how_it_logs_in() {
        assert_eq!(
            label(None, Auth::Subscription),
            "agent Claude Code (subscription login)"
        );
        let path = Path::new("tools").join("codex-adapter.cmd");
        assert_eq!(
            label(path.to_str(), Auth::Api),
            "agent codex-adapter.cmd (API keys)"
        );
    }

    /// An adapter that reports which API key variables it can see, or fails
    /// the way Codex does without a login.
    fn adapter(directory: &Path, unix: &str, windows: &str) -> Result<String> {
        if cfg!(windows) {
            let path = directory.join("adapter.cmd");
            std::fs::write(&path, format!("@echo off\r\n{windows}\r\n"))?;
            return Ok(path.to_string_lossy().into_owned());
        }
        let path = directory.join("adapter");
        std::fs::write(&path, format!("#!/bin/sh\ncat >/dev/null\n{unix}\n"))?;
        #[cfg(unix)]
        std::fs::set_permissions(&path, std::os::unix::fs::PermissionsExt::from_mode(0o755))?;
        Ok(path.to_string_lossy().into_owned())
    }

    /// Calls a test adapter. On Linux, a script just written can fail to
    /// start with "Text file busy" (os error 26) while a process another
    /// test forks at that moment still holds the write handle until its own
    /// exec, so that error alone is retried.
    fn call(agent: &str, auth: Auth, directory: &Path) -> Result<Value> {
        for _ in 0..20 {
            let reply = invoke_measured(
                Some(agent),
                auth,
                &json!({}),
                directory,
                30,
                &Value::Null,
                &Config::default(),
            )
            .reply;
            match &reply {
                Err(error) if format!("{error:#}").contains("os error 26") => {
                    std::thread::sleep(std::time::Duration::from_millis(50));
                }
                _ => return reply,
            }
        }
        invoke_measured(
            Some(agent),
            auth,
            &json!({}),
            directory,
            30,
            &Value::Null,
            &Config::default(),
        )
        .reply
    }

    #[test]
    fn subscription_mode_hides_api_keys_from_the_agent() -> Result<()> {
        let directory = tempfile::tempdir()?;
        let agent = adapter(
            directory.path(),
            r#"printf '{"anthropic":"%s","openai":"%s","oauth":"%s"}' "${ANTHROPIC_API_KEY:-}" "${OPENAI_API_KEY:-}" "${CLAUDE_CODE_OAUTH_TOKEN:-}""#,
            r#"echo {"anthropic":"%ANTHROPIC_API_KEY%","openai":"%OPENAI_API_KEY%","oauth":"%CLAUDE_CODE_OAUTH_TOKEN%"}"#,
        )?;
        // Only this test sets these variables.
        env::set_var("ANTHROPIC_API_KEY", "sk-ant-test");
        env::set_var("OPENAI_API_KEY", "sk-openai-test");
        env::set_var("CLAUDE_CODE_OAUTH_TOKEN", "oauth-test");
        let seen = |auth| call(&agent, auth, directory.path());
        let subscription = seen(Auth::Subscription)?;
        let api = seen(Auth::Api)?;
        env::remove_var("ANTHROPIC_API_KEY");
        env::remove_var("OPENAI_API_KEY");
        env::remove_var("CLAUDE_CODE_OAUTH_TOKEN");
        assert_eq!(
            subscription,
            json!({"anthropic":"","openai":"","oauth":"oauth-test"})
        );
        assert_eq!(
            api,
            json!({"anthropic":"sk-ant-test","openai":"sk-openai-test","oauth":"oauth-test"})
        );
        Ok(())
    }

    #[test]
    fn authentication_failures_ask_for_a_login() -> Result<()> {
        let directory = tempfile::tempdir()?;
        let agent = adapter(
            directory.path(),
            "echo 'Error: 401 Unauthorized: Missing bearer authentication in header' >&2\nexit 1",
            "echo Error: 401 Unauthorized: Missing bearer authentication in header 1>&2\r\nexit /b 1",
        )?;
        let error = call(&agent, Auth::Subscription, directory.path()).unwrap_err();
        let action = error.downcast_ref::<Action>().expect("an action request");
        assert!(action.recommendation.contains("codex login"));
        assert!(action.reason.contains("OPENAI_API_KEY"));

        let crash = adapter(
            directory.path(),
            "echo 'segfault' >&2\nexit 1",
            "echo segfault 1>&2\r\nexit /b 1",
        )?;
        let error = call(&crash, Auth::Subscription, directory.path()).unwrap_err();
        assert!(error.downcast_ref::<Action>().is_none());
        Ok(())
    }

    /// Claude Code is started with exactly these arguments and this prompt for
    /// each role. A fake `claude` script records what it is given, so a change
    /// to how agents are started shows up here before it reaches a real run.
    #[cfg(unix)]
    #[test]
    fn claude_is_started_with_the_documented_arguments_for_each_role() -> Result<()> {
        let directory = tempfile::tempdir()?;
        let record = directory.path().join("record");
        std::fs::create_dir(&record)?;
        let script = directory.path().join("claude");
        std::fs::write(
            &script,
            format!(
                "#!/bin/sh\nfor a in \"$@\"; do printf '%s\\n' \"$a\"; done > '{0}/args'\ncat > '{0}/stdin'\n\
                 printf '%s' '{{\"structured_output\":{{\"status\":\"pass\",\"summary\":\"ok\"}},\"usage\":{{\"input_tokens\":3,\"output_tokens\":4}},\"total_cost_usd\":0.5,\"modelUsage\":{{\"m\":{{}}}}}}'\n",
                record.display()
            ),
        )?;
        std::fs::set_permissions(&script, std::os::unix::fs::PermissionsExt::from_mode(0o755))?;
        let claude = driver::Claude {
            program: Some(script.clone().into_os_string()),
        };
        let run = |request: &Value, profile: &Value| {
            let mut usage = None;
            let reply = drive(
                &claude,
                None,
                Auth::Subscription,
                request,
                directory.path(),
                30,
                profile,
                // `auto` adds Claude Code's sandbox where it can start (macOS),
                // which these documented arguments do not include.
                &Config {
                    sandbox: Sandbox::Off,
                    ..Config::default()
                },
                &mut usage,
            );
            Invocation { reply, usage }
        };

        let profile = crate::contract::profile(None)?;
        let cases = [
            ("plan", json!({}), "Read,Grep,Glob", "default", false),
            ("specify", json!({}), "Read,Grep,Glob", "default", false),
            (
                "build",
                json!({"builder_handoff": "commit"}),
                "Read,Grep,Glob,Edit,Write,Bash",
                "acceptEdits",
                true,
            ),
            (
                "build",
                json!({"builder_handoff": "worktree"}),
                "Read,Grep,Glob,Edit,Write,Bash",
                "acceptEdits",
                true,
            ),
            ("review", json!({}), "Read,Grep,Glob,Bash", "default", true),
            (
                "review",
                json!({"review_scope": "integrated"}),
                "Read,Grep,Glob,Bash",
                "default",
                true,
            ),
            ("verify", json!({}), "Read,Grep,Glob,Bash", "default", true),
        ];
        let mut failures = Vec::new();
        for (role, extra, tools, mode, bash) in cases {
            let mut request = json!({"role": role});
            for (key, value) in extra.as_object().unwrap() {
                request[key] = value.clone();
            }
            let config = &profile["roles"][role];
            let schema: Value = serde_json::from_str(config["schema"].as_str().unwrap())?;
            let mut expected = vec![
                "-p".to_owned(),
                "--output-format".into(),
                "json".into(),
                "--json-schema".into(),
                schema.to_string(),
                "--tools".into(),
                tools.into(),
                "--permission-mode".into(),
                mode.into(),
                "--strict-mcp-config".into(),
            ];
            if bash {
                expected.extend([
                    "--allowedTools".to_owned(),
                    "Bash".into(),
                    "--settings".into(),
                    driver::guard_settings(),
                ]);
            }
            let mut prompt = config["instructions"].as_str().unwrap().to_owned();
            if role == "build" {
                prompt.push('\n');
                prompt.push_str(
                    config["handoff_prompts"][request["builder_handoff"].as_str().unwrap()]
                        .as_str()
                        .unwrap(),
                );
            }
            if request["review_scope"] == "integrated" {
                prompt.push('\n');
                prompt.push_str(config["integrated_prompt"].as_str().unwrap());
            }
            let invocation = run(&request, &profile);
            let reply = invocation.reply?;
            let args = std::fs::read_to_string(record.join("args"))?;
            let stdin = std::fs::read_to_string(record.join("stdin"))?;
            let label = format!("{role} {extra}");
            if args.lines().collect::<Vec<_>>() != expected {
                failures.push(format!("{label}: arguments differ: {args}"));
            }
            if stdin != format!("{prompt}\n\n{request}") {
                failures.push(format!("{label}: prompt differs"));
            }
            assert_eq!(reply, json!({"status": "pass", "summary": "ok"}), "{label}");
            assert_eq!(
                invocation.usage,
                Some(json!({"input_tokens": 3, "output_tokens": 4, "cost_usd": 0.5, "model": "m"})),
                "{label}"
            );
        }
        assert!(failures.is_empty(), "{failures:#?}");

        // Errors Claude Code reports in its own output: usage is still read,
        // a login problem asks for an action, anything else is a plain error.
        let report = |body: &str| -> Result<()> {
            std::fs::write(
                &script,
                format!("#!/bin/sh\ncat >/dev/null\nprintf '%s' '{body}'\n"),
            )?;
            Ok(())
        };
        let request = json!({"role": "review"});
        report(
            r#"{"is_error":true,"result":"Not logged in - Please run /login","usage":{"input_tokens":1}}"#,
        )?;
        let invocation = run(&request, &profile);
        assert_eq!(invocation.usage, Some(json!({"input_tokens": 1})));
        let error = invocation.reply.unwrap_err();
        let action = error.downcast_ref::<Action>().expect("an action request");
        assert!(action.recommendation.contains("run claude, then /login"));
        report(r#"{"is_error":true,"result":"model overloaded"}"#)?;
        let error = run(&request, &profile).reply.unwrap_err();
        assert!(error.downcast_ref::<Action>().is_none());
        assert_eq!(error.to_string(), "model overloaded");
        report(r#"{"result":"no structured output"}"#)?;
        let error = run(&request, &profile).reply.unwrap_err();
        assert!(
            error
                .to_string()
                .starts_with("agent did not return a structured result\n"),
            "{error}"
        );
        Ok(())
    }

    /// A script that records its arguments and stdin, then prints `output`.
    #[cfg(unix)]
    fn recording_agent(directory: &Path, output: &str) -> Result<std::path::PathBuf> {
        let script = directory.join("agent");
        std::fs::write(
            &script,
            format!(
                "#!/bin/sh\nn=$(cat '{0}/count' 2>/dev/null || echo 0)\nn=$((n+1))\necho $n > '{0}/count'\n\
                 for a in \"$@\"; do printf '%s\\n' \"$a\"; done > \"{0}/args$n\"\ncat > \"{0}/stdin$n\"\n\
                 cat <<'AGENT_OUTPUT'\n{1}\nAGENT_OUTPUT\n",
                directory.display(),
                output
            ),
        )?;
        std::fs::set_permissions(&script, std::os::unix::fs::PermissionsExt::from_mode(0o755))?;
        Ok(script)
    }

    #[cfg(unix)]
    fn drive_text(name: &str, script: &Path, role: &str, directory: &Path) -> Result<Value> {
        let agent = driver::Text::with_program(name, script.into());
        let profile = crate::contract::profile(None)?;
        drive(
            &agent,
            Some(name),
            Auth::Subscription,
            &json!({"role": role, "builder_handoff": "commit"}),
            directory,
            30,
            &profile,
            &Config {
                sandbox: Sandbox::Off,
                ..Config::default()
            },
            &mut None,
        )
    }

    #[cfg(unix)]
    #[test]
    fn sandbox_modes_limit_the_environment_and_strict_refuses_unchecked_agents() -> Result<()> {
        let directory = tempfile::tempdir()?;
        let script = directory.path().join("agent");
        std::fs::write(
            &script,
            format!(
                "#!/bin/sh\nenv > '{}/env'\ncat >/dev/null\necho '{{\"status\":\"pass\",\"summary\":\"ok\"}}'\n",
                directory.path().display()
            ),
        )?;
        std::fs::set_permissions(&script, std::os::unix::fs::PermissionsExt::from_mode(0o755))?;
        let agent = driver::Text::with_program("codex", script.into());
        let profile = crate::contract::profile(None)?;
        let request = json!({"role": "review", "builder_handoff": "commit"});
        let run = |sandbox| {
            let config = Config {
                sandbox,
                ..Config::default()
            };
            drive(
                &agent,
                Some("codex"),
                Auth::Subscription,
                &request,
                directory.path(),
                30,
                &profile,
                &config,
                &mut None,
            )
        };
        // Off keeps the whole environment, which Cargo has filled with its own.
        run(crate::config::Sandbox::Off)?;
        let env = std::fs::read_to_string(directory.path().join("env"))?;
        assert!(env.contains("CARGO_MANIFEST_DIR="), "off passes everything");
        // Auto passes the short list: PATH yes, Cargo's variables no.
        run(crate::config::Sandbox::Auto)?;
        let env = std::fs::read_to_string(directory.path().join("env"))?;
        assert!(env.contains("PATH="));
        assert!(!env.contains("CARGO_MANIFEST_DIR="), "auto filters {env}");
        // Strict refuses an agent whose sandbox agengo cannot check. Codex
        // passes where its sandbox can start, so ask for agy, which never does.
        let unchecked = driver::Text::with_program("agy", directory.path().join("agent").into());
        let error = drive(
            &unchecked,
            Some("agy"),
            Auth::Subscription,
            &request,
            directory.path(),
            30,
            &profile,
            &Config {
                sandbox: crate::config::Sandbox::Strict,
                ..Config::default()
            },
            &mut None,
        )
        .unwrap_err()
        .to_string();
        assert!(error.contains("--sandbox strict"), "{error}");
        Ok(())
    }

    #[cfg(unix)]
    #[test]
    fn codex_is_started_per_role_and_its_final_message_is_read() -> Result<()> {
        let directory = tempfile::tempdir()?;
        let script = recording_agent(
            directory.path(),
            "I looked at it.\n```json\n{\"status\":\"pass\",\"summary\":\"ok\"}\n```",
        )?;
        let reply = drive_text("codex", &script, "review", directory.path())?;
        assert_eq!(reply, json!({"status": "pass", "summary": "ok"}));
        let args = std::fs::read_to_string(directory.path().join("args1"))?;
        assert_eq!(
            args.lines().collect::<Vec<_>>(),
            [
                "exec",
                "--sandbox",
                "read-only",
                "--skip-git-repo-check",
                "-"
            ]
        );
        let stdin = std::fs::read_to_string(directory.path().join("stdin1"))?;
        let profile = crate::contract::profile(None)?;
        let instructions = profile["roles"]["review"]["instructions"].as_str().unwrap();
        assert!(stdin.starts_with(instructions));
        assert!(stdin.contains(r#"{"builder_handoff":"commit","role":"review"}"#));
        assert!(stdin.contains("reply with exactly one JSON object"));
        assert!(
            stdin.contains("\"changes_requested\""),
            "the schema is in the prompt"
        );

        drive_text("codex", &script, "build", directory.path())?;
        let args = std::fs::read_to_string(directory.path().join("args2"))?;
        assert!(
            args.contains("workspace-write") && !args.contains("read-only"),
            "{args}"
        );
        Ok(())
    }

    /// The model and effort the user set for a tier reach each kind of agent
    /// in that agent's own terms.
    #[cfg(unix)]
    #[test]
    fn tiers_reach_each_agent_as_its_own_flags() -> Result<()> {
        let directory = tempfile::tempdir()?;
        let profile = crate::contract::profile(None)?;
        let config: Config = serde_yaml_ng::from_str(
            "sandbox: off\nthink: {model: big, effort: max, models: {codex: gpt-big}}\nbuild: {model: small, effort: low}\n",
        )?;
        let args_of = |name: &str, role: &str, count: &str| -> Result<Vec<String>> {
            let script = recording_agent(
                directory.path(),
                r#"{"status":"pass","summary":"ok","response":"{\"status\":\"pass\",\"summary\":\"ok\"}"}"#,
            )?;
            let _ = std::fs::remove_file(directory.path().join("count"));
            let agent = driver::Text::with_program(name, script.into());
            drive(
                &agent,
                Some(name),
                Auth::Subscription,
                &json!({"role": role}),
                directory.path(),
                30,
                &profile,
                &config,
                &mut None,
            )?;
            Ok(std::fs::read_to_string(directory.path().join(count))?
                .lines()
                .map(str::to_owned)
                .collect())
        };
        // Codex: -m for the model, a config override for effort, `max` is
        // spelled xhigh, and the models map wins for its own agent.
        let args = args_of("codex", "review", "args1")?;
        assert_eq!(
            args[..8],
            [
                "exec",
                "--sandbox",
                "read-only",
                "--skip-git-repo-check",
                "-m",
                "gpt-big",
                "-c",
                "model_reasoning_effort=\"xhigh\""
            ]
        );
        assert_eq!(args[8], "-");
        let args = args_of("codex", "build", "args1")?;
        assert!(
            args.windows(2).any(|pair| pair == ["-m", "small"]),
            "{args:?}"
        );
        assert!(
            args.contains(&"model_reasoning_effort=\"low\"".to_owned()),
            "{args:?}"
        );
        // Antigravity: --model and --effort before the prompt.
        let args = args_of("agy", "plan", "args1")?;
        assert_eq!(
            args[..6],
            [
                "--output-format",
                "json",
                "--model",
                "big",
                "--effort",
                "max"
            ]
        );
        assert_eq!(args[6], "-p");

        // Claude Code.
        let script = directory.path().join("claude");
        std::fs::write(
            &script,
            format!(
                "#!/bin/sh\nfor a in \"$@\"; do printf '%s\\n' \"$a\"; done > '{0}/claude-args'\ncat >/dev/null\n\
                 printf '%s' '{{\"structured_output\":{{\"status\":\"pass\",\"summary\":\"ok\"}}}}'\n",
                directory.path().display()
            ),
        )?;
        std::fs::set_permissions(&script, std::os::unix::fs::PermissionsExt::from_mode(0o755))?;
        let claude = driver::Claude {
            program: Some(script.into_os_string()),
        };
        let run = |role: &str, config: &Config| -> Result<String> {
            drive(
                &claude,
                None,
                Auth::Subscription,
                &json!({"role": role}),
                directory.path(),
                30,
                &profile,
                config,
                &mut None,
            )?;
            Ok(std::fs::read_to_string(
                directory.path().join("claude-args"),
            )?)
        };
        let args = run("review", &config)?;
        assert!(args.contains("--model\nbig\n--effort\nmax\n"), "{args}");
        let args = run("build", &config)?;
        assert!(args.contains("--model\nsmall\n--effort\nlow\n"), "{args}");
        let args = run("build", &Config::default())?;
        assert!(
            !args.contains("--model") && !args.contains("--effort"),
            "{args}"
        );

        // A custom adapter is told the tier, model and effort in the request.
        let adapter = recording_agent(directory.path(), r#"{"status":"pass","summary":"ok"}"#)?;
        let _ = std::fs::remove_file(directory.path().join("count"));
        let agent = adapter.to_str().unwrap();
        invoke_measured(
            Some(agent),
            Auth::Subscription,
            &json!({"role": "build"}),
            directory.path(),
            30,
            &profile,
            &config,
        )
        .reply?;
        let sent: Value =
            serde_json::from_str(&std::fs::read_to_string(directory.path().join("stdin1"))?)?;
        assert_eq!(
            (
                sent["tier"].as_str(),
                sent["model"].as_str(),
                sent["effort"].as_str()
            ),
            (Some("build"), Some("small"), Some("low"))
        );
        let _ = std::fs::remove_file(directory.path().join("count"));
        invoke_measured(
            Some(agent),
            Auth::Subscription,
            &json!({"role": "plan"}),
            directory.path(),
            30,
            &profile,
            &Config::default(),
        )
        .reply?;
        let sent: Value =
            serde_json::from_str(&std::fs::read_to_string(directory.path().join("stdin1"))?)?;
        assert_eq!(sent["tier"], "think");
        assert!(sent.get("model").is_none() && sent.get("effort").is_none());
        Ok(())
    }

    #[cfg(unix)]
    #[test]
    fn a_reply_without_json_is_asked_for_once_more() -> Result<()> {
        let directory = tempfile::tempdir()?;
        let script = directory.path().join("agent");
        std::fs::write(
            &script,
            format!(
                "#!/bin/sh\ncat > '{0}/stdin'\nif [ -e '{0}/asked' ]; then echo '{{\"status\":\"pass\",\"summary\":\"ok\"}}'; \
                 else touch '{0}/asked'; echo 'All good, nothing to report.'; fi\n",
                directory.path().display()
            ),
        )?;
        std::fs::set_permissions(&script, std::os::unix::fs::PermissionsExt::from_mode(0o755))?;
        let reply = drive_text("codex", &script, "review", directory.path())?;
        assert_eq!(reply, json!({"status": "pass", "summary": "ok"}));
        let stdin = std::fs::read_to_string(directory.path().join("stdin"))?;
        assert!(stdin.contains("did not contain the JSON object"), "{stdin}");

        let silent = recording_agent(directory.path(), "no json at all")?;
        let error = drive_text("codex", &silent, "review", directory.path()).unwrap_err();
        assert!(
            error
                .to_string()
                .starts_with("agent did not return a structured result\n"),
            "{error}"
        );
        assert_eq!(
            std::fs::read_to_string(directory.path().join("count"))?.trim(),
            "2",
            "it asks once, not forever"
        );
        Ok(())
    }

    #[cfg(unix)]
    #[test]
    fn antigravity_envelopes_are_read_by_status_and_structured_output() {
        use driver::Driver;
        let agent = driver::Text::new("agy");
        let parse = |text: &str| agent.reported_error(&agent.parse(text.as_bytes()));
        assert!(parse(r#"{"status":"WAITING","response":""}"#)
            .unwrap()
            .contains("status WAITING"));
        assert_eq!(
            agent.parse(
                br#"{"status":"SUCCESS","response":"","structured_output":{"status":"pass"}}"#
            ),
            json!({"status": "pass"})
        );
        assert_eq!(agent.parse(b""), serde_json::Value::Null);
    }

    #[cfg(unix)]
    #[test]
    fn antigravity_denied_tools_are_named() {
        use driver::Driver;
        let agent = driver::Text::new("agy");
        let output = agent.parse(
            br#"{"status":"SUCCESS","response":"","denied_actions":[{"action":"command","display_name":"Bash"}]}"#,
        );
        let error = agent.reported_error(&output).unwrap();
        assert!(error.contains("not allowed to use command"), "{error}");
        assert!(error.contains("\"command(*)\""), "{error}");
    }

    #[cfg(unix)]
    #[test]
    fn antigravity_is_asked_for_its_sandbox_only_when_the_mode_is_not_off() -> Result<()> {
        let directory = tempfile::tempdir()?;
        let envelope =
            r#"{"status":"SUCCESS","response":"{\"status\":\"pass\",\"summary\":\"ok\"}"}"#;
        let script = recording_agent(directory.path(), envelope)?;
        let agent = driver::Text::with_program("agy", script.into());
        let profile = crate::contract::profile(None)?;
        let request = json!({"role": "review", "builder_handoff": "commit"});
        let run = |sandbox, n: &str| -> Result<Vec<String>> {
            let config = Config {
                sandbox,
                ..Config::default()
            };
            drive(
                &agent,
                Some("agy"),
                Auth::Subscription,
                &request,
                directory.path(),
                30,
                &profile,
                &config,
                &mut None,
            )?;
            Ok(std::fs::read_to_string(directory.path().join(n))?
                .lines()
                .map(str::to_owned)
                .collect())
        };
        assert!(!run(crate::config::Sandbox::Off, "args1")?.contains(&"--sandbox".to_owned()));
        assert!(run(crate::config::Sandbox::Auto, "args2")?.contains(&"--sandbox".to_owned()));
        // agy may ignore the flag without saying so, so strict refuses it.
        let error = drive(
            &agent,
            Some("agy"),
            Auth::Subscription,
            &request,
            directory.path(),
            30,
            &profile,
            &Config {
                sandbox: crate::config::Sandbox::Strict,
                ..Config::default()
            },
            &mut None,
        )
        .unwrap_err()
        .to_string();
        assert!(
            error.contains("cannot tell whether it is in force"),
            "{error}"
        );
        Ok(())
    }

    #[test]
    fn named_agents_choose_their_default_handoff() {
        // Codex's sandbox keeps `.git` read-only, so agengo commits for it.
        assert_eq!(driver::default_handoff("codex"), "worktree");
        assert_eq!(driver::default_handoff("agy"), "commit");
        assert_eq!(driver::default_handoff("./my-adapter"), "commit");
    }

    #[cfg(unix)]
    #[test]
    fn antigravity_gets_the_prompt_as_an_argument_and_returns_json_in_response() -> Result<()> {
        let directory = tempfile::tempdir()?;
        let envelope = r#"{"status":"SUCCESS","response":"Done: {\"status\":\"pass\",\"summary\":\"ok\"}","usage":{"input_tokens":5}}"#;
        let script = recording_agent(directory.path(), envelope)?;
        let reply = drive_text("agy", &script, "review", directory.path())?;
        assert_eq!(reply, json!({"status": "pass", "summary": "ok"}));
        let args = std::fs::read_to_string(directory.path().join("args1"))?;
        let args: Vec<&str> = args.splitn(4, '\n').collect();
        assert_eq!(&args[..3], ["--output-format", "json", "-p"]);
        assert!(args[3].contains(r#"{"builder_handoff":"commit","role":"review"}"#));
        assert_eq!(
            std::fs::read_to_string(directory.path().join("stdin1"))?,
            ""
        );

        // Errors the agent reports in its envelope, and a missing login.
        let failed = recording_agent(
            directory.path(),
            r#"{"status":"ERROR","error":"unknown model: nope"}"#,
        )?;
        let error = drive_text("agy", &failed, "review", directory.path()).unwrap_err();
        assert_eq!(error.to_string(), "unknown model: nope");
        let login = recording_agent(
            directory.path(),
            r#"{"status":"ERROR","error":"authentication required"}"#,
        )?;
        let error = drive_text("agy", &login, "review", directory.path()).unwrap_err();
        assert!(error.downcast_ref::<Action>().is_some());
        Ok(())
    }

    #[test]
    fn agents_known_by_name_are_resolved_by_name() {
        assert_eq!(driver::known_program("codex").as_deref(), Some("codex"));
        assert_eq!(driver::known_program("agy").as_deref(), Some("agy"));
        assert_eq!(driver::known_program("claude"), None);
        assert_eq!(driver::known_program("./codex"), None);
        assert!(label(Some("codex"), Auth::Subscription).contains("agent codex "));
    }

    #[test]
    fn runs_without_a_stored_mode_keep_passing_keys_through() -> Result<()> {
        assert_eq!(Auth::from_stored(None)?, Auth::Api);
        assert_eq!(Auth::from_stored(Some("subscription"))?, Auth::Subscription);
        assert!(Auth::from_stored(Some("other")).is_err());
        Ok(())
    }
}