Skip to main content

agentmux_srv_core/backend/container/
argv.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A container turn's CLI arguments: the one-shot shape a `docker exec` turn runs with.
5
6/// Heal a container agent's argv IN PLACE when — and only when — it still
7/// carries the persistent controller's flags.
8///
9/// A container agent runs one `docker exec` per turn: `container_spawn.rs`
10/// writes the raw message, closes stdin, and reads until EOF. There is no
11/// long-lived stdin and no control channel. The PERSISTENT argv is wrong for
12/// that in three separate ways, and it is what stale blocks carry:
13///
14///   * `--input-format stream-json` — makes the CLI parse every stdin line as
15///     a JSON envelope, so it meets the startup markdown and dies with
16///     `JSON Parse error: Unrecognized token '#'`. This is the crash that kept
17///     container agents from EVER starting (verified live, 2026-08-31).
18///   * missing `-p` — the one-shot print flag. Without it the CLI is not in
19///     the mode this path drives at all.
20///   * `--permission-prompt-tool stdio` (+ a non-bypass `--permission-mode`) —
21///     routes tool permissions through the control protocol, which only the
22///     persistent controller speaks. A container turn has nothing to answer
23///     `can_use_tool`, so it rejects or hangs on the first permission check.
24///
25/// An earlier cut of this deleted only `--input-format` and left the other two
26/// (codex P1 on PR #2867) — that unblocks the immediate crash while leaving the
27/// pane in the wrong CLI mode, which is a worse failure because it looks like
28/// it works.
29///
30/// The cut after THAT rebuilt the argv wholesale from `launch_args`, which was
31/// worse again (reagent P1 on the same PR): this runs on EVERY container turn,
32/// not once per stale block, so a rebuild also threw away everything
33/// `agent-model.ts` legitimately appends after the base args —
34/// `agent.provider_flags` (user-configurable) and `--fork-session` (gated on
35/// `providerId === "claude"`, not on `agentMode`, so container agents reach it).
36/// It would have permanently broken both for container agents, on blocks whose
37/// argv this fix had already assembled correctly.
38///
39/// So: subtract, don't rebuild. Remove the flags the PERSISTENT argv carries
40/// that the one-shot argv does not, restore any one-shot flag that's missing,
41/// and leave every other token — the user's `--model`/`--effort`, their
42/// `provider_flags`, `--fork-session` — exactly where it was. Which flags are
43/// "persistent-only" is derived from the provider catalog rather than hardcoded,
44/// so a future flag moving between the two lists doesn't silently strand this.
45///
46/// An argv carrying NO persistent-only flag is returned untouched: it was built
47/// by the fixed `selectLaunchArgs` path and there is nothing to heal.
48///
49/// The root cause is fixed at the source in `launch-args.ts`; this is the
50/// self-heal for blocks ALREADY persisted with the bad argv, since `cmd:args`
51/// lives in block meta and would otherwise stay wrong forever. Applied at the
52/// point of use so a block that never re-runs `resync_controller` can't bypass
53/// it.
54pub fn container_argv(argv: Vec<String>, provider_id: &str) -> Vec<String> {
55    let Some(provider) = crate::backend::providers::get_provider(provider_id) else {
56        // Unknown provider — no catalog to diff against, so remove the one flag
57        // that is outright fatal rather than guessing at the rest.
58        return strip_flag_with_value(argv, "--input-format");
59    };
60    let Some(persistent) = provider.persistent_launch_args else {
61        // Subprocess-shaped provider: its only argv IS the one-shot argv, so a
62        // container block could never have been given persistent flags.
63        return argv;
64    };
65
66    let one_shot = flags_with_arity(provider.launch_args);
67    let persistent_only: Vec<(&str, bool)> = flags_with_arity(persistent)
68        .into_iter()
69        .filter(|(flag, _)| !one_shot.iter().any(|(f, _)| f == flag))
70        .collect();
71
72    // Already one-shot-shaped — the frontend assembled this argv, hands off.
73    if !argv
74        .iter()
75        .any(|a| persistent_only.iter().any(|(f, _)| f == a))
76    {
77        return argv;
78    }
79
80    let mut out = argv;
81    for (flag, takes_value) in &persistent_only {
82        out = if *takes_value {
83            strip_flag_with_value(out, flag)
84        } else {
85            out.into_iter().filter(|a| a != flag).collect()
86        };
87    }
88
89    // Restore the one-shot flags the persistent argv never had (`-p` above all).
90    // Prepended so the provider's own baseline keeps its leading position.
91    let mut restored: Vec<String> = Vec::new();
92    for (flag, takes_value) in &one_shot {
93        if out.iter().any(|a| a == flag) {
94            continue;
95        }
96        restored.push(flag.to_string());
97        if *takes_value {
98            if let Some(pos) = provider.launch_args.iter().position(|a| a == flag) {
99                if let Some(v) = provider.launch_args.get(pos + 1) {
100                    restored.push(v.to_string());
101                }
102            }
103        }
104    }
105    restored.extend(out);
106    restored
107}
108
109/// Split an args list into `(flag, takes_a_value)` pairs.
110///
111/// Arity is read off the list itself — a flag whose next token is not another
112/// flag takes a value. That's what lets `container_argv` strip
113/// `--permission-prompt-tool stdio` (two tokens) and `--verbose` (one)
114/// correctly without a hardcoded table of every provider's flag shapes.
115fn flags_with_arity(args: &'static [&'static str]) -> Vec<(&'static str, bool)> {
116    let mut out = Vec::new();
117    for (i, tok) in args.iter().enumerate() {
118        if !tok.starts_with('-') {
119            continue;
120        }
121        let takes_value = args.get(i + 1).is_some_and(|next| !next.starts_with('-'));
122        out.push((*tok, takes_value));
123    }
124    out
125}
126
127/// Remove `flag` and the value token following it, everywhere it appears.
128/// Tolerates a trailing `flag` with no value rather than panicking.
129fn strip_flag_with_value(args: Vec<String>, flag: &str) -> Vec<String> {
130    let mut out = Vec::with_capacity(args.len());
131    let mut it = args.into_iter();
132    while let Some(a) = it.next() {
133        if a == flag {
134            let _ = it.next();
135            continue;
136        }
137        out.push(a);
138    }
139    out
140}
141
142#[cfg(test)]
143mod tests {
144    use super::{container_argv, flags_with_arity, strip_flag_with_value};
145
146    fn v(xs: &[&str]) -> Vec<String> {
147        xs.iter().map(|s| s.to_string()).collect()
148    }
149
150    /// The exact argv a container agent carried before the fix — the persistent
151    /// controller's args, copied verbatim from the live broken block (Moras,
152    /// 2026-08-31).
153    fn stale_persistent_argv() -> Vec<String> {
154        v(&[
155            "--input-format",
156            "stream-json",
157            "--output-format",
158            "stream-json",
159            "--verbose",
160            "--include-partial-messages",
161            "--permission-prompt-tool",
162            "stdio",
163            "--permission-mode",
164            "default",
165            "--model",
166            "sonnet",
167            "--effort",
168            "high",
169        ])
170    }
171
172    /// All three persistent-only defects must go, not just the fatal one
173    /// (codex P1 on PR #2867): the parse crash, the missing one-shot `-p`, and
174    /// the control-protocol permission flags a container turn cannot answer.
175    #[test]
176    fn rebuilds_a_stale_persistent_argv_into_the_one_shot_form() {
177        let got = container_argv(stale_persistent_argv(), "claude");
178
179        assert!(
180            !got.iter().any(|a| a == "--input-format"),
181            "the fatal parse flag must go"
182        );
183        assert!(
184            got.iter().any(|a| a == "-p"),
185            "one-shot print mode must be present"
186        );
187        assert!(
188            !got.iter().any(|a| a == "--permission-prompt-tool"),
189            "the container turn has no control channel to answer can_use_tool",
190        );
191        assert!(
192            !got.iter().any(|a| a == "stdio"),
193            "its value token must go with it"
194        );
195        assert!(
196            !got.iter().any(|a| a == "--permission-mode"),
197            "non-bypass permission mode needs the control protocol",
198        );
199        assert!(
200            got.iter().any(|a| a == "--output-format"),
201            "output-format stream-json is how the pane parses the turn at all",
202        );
203    }
204
205    /// A user's model/effort selections must survive the heal — silently
206    /// resetting someone's model on every stale pane would be its own bug.
207    #[test]
208    fn preserves_the_users_model_and_effort_choices() {
209        let got = container_argv(stale_persistent_argv(), "claude");
210        let pos = |f: &str| got.iter().position(|a| a == f);
211        assert_eq!(got[pos("--model").expect("--model kept") + 1], "sonnet");
212        assert_eq!(got[pos("--effort").expect("--effort kept") + 1], "high");
213    }
214
215    /// reagent P1 on PR #2867. This runs on EVERY container turn, not once per
216    /// stale block, so it must not touch an argv the frontend already built
217    /// correctly — a rebuild-from-baseline silently deleted `provider_flags`
218    /// and `--fork-session` on every single turn, forever.
219    #[test]
220    fn leaves_an_already_correct_one_shot_argv_completely_untouched() {
221        let correct = v(&[
222            "-p",
223            "--output-format",
224            "stream-json",
225            "--verbose",
226            "--include-partial-messages",
227            "--dangerously-skip-permissions",
228            "--exclude-dynamic-system-prompt-sections",
229            "--model",
230            "opus",
231            "--my-custom-provider-flag",
232            "42",             // agent.provider_flags
233            "--fork-session", // resolveForkSessionArgs
234        ]);
235        assert_eq!(container_argv(correct.clone(), "claude"), correct);
236    }
237
238    /// …and when it DOES heal a stale argv, those same user-owned tokens still
239    /// have to come through. Healing is subtraction, not reconstruction.
240    #[test]
241    fn a_heal_preserves_provider_flags_and_fork_session_too() {
242        let mut stale = stale_persistent_argv();
243        stale.extend(v(&["--my-custom-provider-flag", "42", "--fork-session"]));
244
245        let got = container_argv(stale, "claude");
246
247        assert!(
248            got.iter().any(|a| a == "--my-custom-provider-flag"),
249            "provider_flags survive"
250        );
251        assert_eq!(
252            got[got
253                .iter()
254                .position(|a| a == "--my-custom-provider-flag")
255                .unwrap()
256                + 1],
257            "42",
258            "…with its value",
259        );
260        assert!(
261            got.iter().any(|a| a == "--fork-session"),
262            "fork-session survives"
263        );
264        assert!(
265            !got.iter().any(|a| a == "--input-format"),
266            "while still being healed"
267        );
268        assert!(got.iter().any(|a| a == "-p"));
269    }
270
271    /// An unknown provider has no baseline to diff against, so fall back to
272    /// removing only the outright-fatal flag rather than guessing.
273    #[test]
274    fn an_unknown_provider_falls_back_to_removing_only_the_fatal_flag() {
275        let got = container_argv(
276            v(&["--input-format", "stream-json", "--custom"]),
277            "no-such-provider",
278        );
279        assert_eq!(got, v(&["--custom"]));
280    }
281
282    /// A subprocess-shaped provider has no persistent argv, so nothing it was
283    /// ever launched with could need healing.
284    #[test]
285    fn a_provider_with_no_persistent_variant_is_passed_through() {
286        let argv = v(&["--json", "--whatever"]);
287        assert_eq!(container_argv(argv.clone(), "codex"), argv);
288    }
289
290    /// Arity comes off the catalog, not a hardcoded table — this is what lets
291    /// a valued flag drop its value and a bare flag not eat the next one.
292    #[test]
293    fn flags_with_arity_reads_valued_and_bare_flags_off_the_list() {
294        static ARGS: &[&str] = &["-p", "--output-format", "stream-json", "--verbose"];
295        assert_eq!(
296            flags_with_arity(ARGS),
297            vec![
298                ("-p", false),
299                ("--output-format", true),
300                ("--verbose", false)
301            ],
302        );
303    }
304
305    #[test]
306    fn strip_flag_with_value_removes_every_occurrence_and_tolerates_a_missing_value() {
307        assert_eq!(
308            strip_flag_with_value(v(&["--x", "1", "--keep", "--x", "2"]), "--x"),
309            v(&["--keep"]),
310        );
311        assert_eq!(
312            strip_flag_with_value(v(&["--keep", "--x"]), "--x"),
313            v(&["--keep"])
314        );
315        assert_eq!(strip_flag_with_value(vec![], "--x"), Vec::<String>::new());
316    }
317}