Skip to main content

agentmux_srv_core/backend/blockcontroller/subprocess/
container_spawn.rs

1// Copyright 2025, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Container-exec turn spawn (`spawn_container_turn`) for [`SubprocessController`].
5//!
6//! Docker-exec analog of `host_spawn::spawn_turn`, used for container agents.
7//! Drives the exec via `bollard`'s Docker socket API instead of a host
8//! `std::process` child (P1a: no secrets in argv — env vars travel through
9//! `CreateExecOptions.env`, never process argv / `/proc/<pid>/cmdline`).
10//!
11//! `spawn_container_turn` refuses, queues or accepts a request here and hands the
12//! accepted turn to the steps in `container_spawn_steps.rs`.
13//! `publish_line` is its private output-line helper (used only here).
14
15use std::sync::Arc;
16
17use crate::backend::blockcontroller::{core, session_stats, shell};
18
19use super::{argv::build_turn_argv, SubprocessController, SubprocessControllerInner, SubprocessSpawnConfig, SUBPROCESS_OUTPUT_SUBJECT};
20
21#[path = "container_spawn_steps.rs"]
22pub mod steps;
23
24#[cfg(test)]
25#[path = "container_turn_tests.rs"]
26mod container_turn_tests;
27
28/// Wrap the CLI argv so it reads the turn prompt from `prompt_path`, a file
29/// already written into the container by
30/// [`ContainerManager::upload_turn_prompt`].
31///
32/// Redirecting from a file is the only transport that satisfies all three
33/// constraints at once (see `upload_turn_prompt`'s doc for the measurements):
34/// the CLI gets a real stdin that really reaches EOF, the message never touches
35/// argv or env — so `docker top` / host `ps` / `/proc/<pid>/cmdline` can't see a
36/// secret pasted into a chat message — and there is no `MAX_ARG_STRLEN` ceiling.
37///
38/// The CLI argv is passed through as `"$@"` rather than interpolated into the
39/// script, so there is no shell quoting to get wrong, and it is passed
40/// UNCHANGED — including a trailing `-` (codex) or a `-p ""` placeholder
41/// (gemini/qwen/kimi), both of which mean "read the prompt from
42/// stdin" and are correct again now that stdin genuinely works (codex P1,
43/// PR #2883).
44///
45/// The prompt file is removed after the CLI exits, and the CLI's own exit
46/// status is preserved for `inspect_exec` to classify the turn.
47///
48/// The directory the provider CLI is installed into on first start is appended
49/// to `PATH`, after the image's own, so a CLI baked into an older image still
50/// wins over the installed one.
51fn container_turn_exec(prompt_path: &str, cmd: Vec<String>) -> Vec<String> {
52    // bash, not sh: the image's sh is dash, which drops the exported `git` and `gh` functions
53    // (`BASH_FUNC_*` environment entries) before the provider starts.
54    let mut out = vec![
55        "bash".to_string(),
56        "-c".to_string(),
57        // $1 = prompt path, "$@" (after shift) = the CLI and its args.
58        format!(
59            r#"PATH="$PATH:{}"; export PATH; F="$1"; shift; "$@" < "$F"; rc=$?; rm -f "$F"; exit $rc"#,
60            crate::backend::container::cli::cli_path_dirs()
61        ),
62        // $0 for the script -- a label only.
63        "agentmux-turn".to_string(),
64        prompt_path.to_string(),
65    ];
66    out.extend(cmd);
67    out
68}
69
70#[cfg(test)]
71mod turn_exec_tests {
72    use super::container_turn_exec;
73
74    fn v(xs: &[&str]) -> Vec<String> {
75        xs.iter().map(|s| s.to_string()).collect()
76    }
77
78    /// The security property this shape exists for (reagent P1, PR #2883): the
79    /// message must never reach argv, where `docker top` / `ps` /
80    /// `/proc/<pid>/cmdline` would expose a pasted secret. It can't — the argv
81    /// is built from the prompt's PATH and never sees the message at all.
82    #[test]
83    fn the_argv_carries_only_a_path_never_the_message() {
84        let argv = container_turn_exec("/tmp/agentmux-turn-abc", v(&["claude", "-p"]));
85        assert!(argv.iter().any(|a| a == "/tmp/agentmux-turn-abc"), "the path is there");
86        assert!(
87            argv.iter().all(|a| !a.contains("ghp_") && !a.contains("secret")),
88            "nothing message-shaped is: {argv:?}",
89        );
90    }
91
92    /// The CLI must actually read the file — this redirect IS the fix.
93    #[test]
94    fn redirects_the_clis_stdin_from_the_prompt_file() {
95        let argv = container_turn_exec("/tmp/p", v(&["claude", "-p"]));
96        assert!(argv[2].contains(r#""$@" < "$F""#), "must redirect: {}", argv[2]);
97    }
98
99    /// The prompt file is transient state; leaving it behind would accumulate
100    /// one file per turn for the life of the container.
101    #[test]
102    fn removes_the_prompt_file_afterwards() {
103        let argv = container_turn_exec("/tmp/p", v(&["claude", "-p"]));
104        assert!(argv[2].contains(r#"rm -f "$F""#), "must clean up: {}", argv[2]);
105    }
106
107    /// `inspect_exec` classifies the turn from the exit code, so the CLI's own
108    /// status must survive the cleanup that runs after it.
109    #[test]
110    fn preserves_the_clis_exit_status_across_cleanup() {
111        let argv = container_turn_exec("/tmp/p", v(&["claude", "-p"]));
112        assert!(argv[2].contains("rc=$?"), "captures status before rm");
113        assert!(argv[2].contains("exit $rc"), "and re-raises it: {}", argv[2]);
114    }
115
116    /// The installed CLI is found after the image's own `PATH`, not before it.
117    #[test]
118    fn appends_the_install_dir_to_path_after_the_images_own() {
119        let argv = container_turn_exec("/tmp/p", v(&["claude", "-p"]));
120        assert!(
121            argv[2].starts_with(
122                r#"PATH="$PATH:/home/agent/.agentmux/cli/node_modules/.bin:/home/agent/.agentmux/cli/bin:/home/agent/.agentmux/cli/venv/bin"; export PATH;"#
123            ),
124            "{}",
125            argv[2]
126        );
127    }
128
129    /// An exported function (`BASH_FUNC_*`) reaches the provider through the launcher: the container
130    /// agent's `git` and `gh` are such functions, and the image's `sh` would drop them.
131    #[cfg(unix)]
132    #[test]
133    fn an_exported_function_reaches_the_provider() {
134        let prompt = std::env::temp_dir().join(format!("amx-turn-fn-{}", std::process::id()));
135        std::fs::write(&prompt, "").unwrap();
136        let argv = container_turn_exec(prompt.to_str().unwrap(), v(&["bash", "-c", "type -t gh"]));
137        let out = std::process::Command::new(&argv[0])
138            .args(&argv[1..])
139            .env("BASH_FUNC_gh%%", "() {  echo from-function
140}")
141            .output()
142            .unwrap();
143        assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "function");
144        let _ = std::fs::remove_file(&prompt);
145    }
146
147    /// Passed as "$@", so the CLI argv survives verbatim and in order.
148    #[test]
149    fn passes_the_cli_argv_through_unchanged() {
150        let argv = container_turn_exec("/tmp/p", v(&["claude", "-p", "--model", "opus"]));
151        assert_eq!(&argv[0], "bash");
152        assert_eq!(&argv[1], "-c");
153        // argv[3] is $0, argv[4] is the prompt path; the CLI argv follows.
154        assert_eq!(&argv[5..], &v(&["claude", "-p", "--model", "opus"])[..]);
155    }
156
157    /// codex's trailing `-` means "read the prompt from stdin" and must NOT be
158    /// stripped: stdin is a real, EOF-terminating file now. An earlier cut of
159    /// this fix removed it, which was only necessary while the message was
160    /// being smuggled through argv.
161    #[test]
162    fn keeps_codexs_trailing_stdin_positional() {
163        let argv = container_turn_exec("/tmp/p", v(&["codex", "exec", "--json", "-"]));
164        assert_eq!(argv.last().unwrap(), "-");
165    }
166
167    /// Same for the `-p ""` placeholder gemini/qwen/kimi use to
168    /// mean "prompt comes from stdin" (codex P1, PR #2883).
169    #[test]
170    fn keeps_an_empty_prompt_placeholder() {
171        let argv = container_turn_exec("/tmp/p", v(&["gemini", "-p", "", "--json"]));
172        assert_eq!(&argv[5..], &v(&["gemini", "-p", "", "--json"])[..]);
173    }
174}
175
176impl SubprocessController {
177    /// Record what a container turn does before its exec (start the container,
178    /// install the CLI). Call before [`spawn_container_turn`](Self::spawn_container_turn):
179    /// the step runs at the start of that turn's own task, and again for each
180    /// message queued behind it, so a failed start-up is retried by the next one.
181    pub fn set_container_startup(&self, step: super::StartupStep) {
182        *self.container_startup.lock().unwrap() = Some(step);
183    }
184
185    /// Spawn a container agent turn via Docker socket (P1a: no secrets in argv).
186    ///
187    /// This is the secure alternative to `spawn_turn` for container agents. Instead
188    /// of running `docker exec -e KEY=VALUE ...` as a CLI subprocess (which exposes
189    /// secrets in process argv / `/proc/<pid>/cmdline`, CWE-214), this method calls
190    /// `ContainerManager::exec` directly, passing env vars through
191    /// `CreateExecOptions.env` (Docker socket). The exec I/O (file-backed prompt
192    /// + stdout NDJSON stream) drives the same state machine as `spawn_turn`:
193    ///   • appends `--resume <sid>` if a prior session_id is known
194    ///   • uploads the turn message into the container as a file and redirects
195    ///     the CLI's stdin from it — see `container_turn_exec` for why the
196    ///     exec's own stdin, argv, and env are all unusable for this
197    ///   • reads NDJSON from the output stream, publishing MPS blockfile events
198    ///   • captures session_id from the provider's init event
199    ///   • transitions status running → done
200    ///   • drains the pending-message queue when the exec exits
201    ///
202    /// `base_cmd` is `[cli_command] + cli_args` WITHOUT resume — this method appends
203    /// `--resume <sid>` internally before starting the exec.
204    /// The exec env is derived from THIS message's `config.env_vars` (denylist
205    /// applied here, per-turn) — not carried across queue drains — so a queued
206    /// message runs with its own freshly-resolved auth/env, matching `spawn_turn`.
207    ///
208    /// Takes `cm` and `container_name` by value (not reference) so the returned
209    /// future is `'static` — required for `tokio::spawn` in the queue-drain path.
210    pub fn spawn_container_turn(
211        &self,
212        cm: crate::backend::container::ContainerManager,
213        container_name: String,
214        base_cmd: Vec<String>,
215        config: SubprocessSpawnConfig,
216    ) -> Result<(), String> {
217        // The container path keeps the prompt out of argv on purpose (module
218        // doc: a pasted secret must not show in `ps`), so a provider that
219        // can only take its prompt as an argument doesn't run here.
220        if !config.prompt_arg_flag.is_empty() {
221            return Err(
222                "This agent's CLI takes its message on the command line, which the container runtime doesn't do. Run it on the host."
223                    .to_string(),
224            );
225        }
226        // A host Codex pane compacts through a short-lived App Server
227        // (codex_compact.rs); inside a container that isn't built yet, and
228        // `exec` would take "/compact" as a prompt.
229        if super::codex_compact::is_compact_request(&config) {
230            return Err("Compacting a Codex agent that runs in a container isn't supported yet.".to_string());
231        }
232        // What a queued message runs with (its own args were taken into `base_cmd`), kept for a replacement
233        // controller to run the queue with (replace.rs).
234        self.remember_container_context(&cm, &container_name, &base_cmd);
235        // A fresh agent's first turn starts with its Session Context block (first_turn_hold.rs).
236        let Some(config) = self.hold_for_session_context(config) else { return Ok(()) };
237        if !self.take_run_lock_for_turn() {
238            self.queue_behind_running_process(config, "container exec busy");
239            return Ok(());
240        }
241
242        // Shared for the whole turn: an update of this container waits for none, and refuses
243        // while one holds it.
244        let Ok(update_guard) = crate::backend::container::drift::update_gate(&container_name).try_read_owned() else {
245            self.unlock_run();
246            return Err("This agent's container is being updated. Send the message again in a moment.".to_string());
247        };
248
249        self.hydrate_session_id_from_config(config.session_id.as_deref());
250
251        let session_id_hint = self.inner.lock().unwrap().session_id.clone();
252        let cmd = match build_turn_argv(
253            &base_cmd,
254            &config.resume_strategy,
255            &config.resume_flag,
256            session_id_hint.as_deref(),
257        ) {
258            Ok(cmd) => cmd,
259            Err(error) => {
260                self.unlock_run();
261                return Err(error);
262            }
263        };
264
265        self.emit_message_accepted(&config);
266
267        let turn = self.begin_container_turn(cm, container_name, base_cmd, cmd, &config);
268
269        // Spawn all async work (exec + I/O) into a background task so this
270        // function returns synchronously. This is required so the queue-drain
271        // path inside the reader task can call `spawn_container_turn` without
272        // needing the returned future to be `'static`.
273        tokio::spawn(steps::run_turn(turn, update_guard));
274
275        Ok(())
276    }
277
278    /// A queued message has already been removed from `pending_messages` when
279    /// its next spawn is attempted. If provider argv validation rejects that
280    /// spawn, persist a transcript error so the message does not disappear
281    /// with only a server log. Mirrors the host queue-drain failure path.
282    pub(super) fn publish_queued_spawn_error(
283        block_id: &str,
284        error: &str,
285        broker: &Option<Arc<crate::backend::mps::Broker>>,
286        filestore: &Option<Arc<crate::backend::storage::filestore::FileStore>>,
287        mstore: &Option<Arc<crate::backend::storage::store::Store>>,
288    ) {
289        let Some(broker) = broker else {
290            return;
291        };
292        let error_frame = serde_json::json!({
293            "type": "result",
294            "is_error": true,
295            "subtype": "error_during_execution",
296            "error": {"message": format!("[AgentMux] queued message could not be sent: {error}")}
297        }).to_string();
298        // Into the agent's global zone too: that is what the pane reads on
299        // reload (Phase 5a-3c).
300        let global_zone = crate::backend::transcript::append::resolve_global_output_zone(mstore, block_id);
301        shell::handle_append_block_file(
302            broker,
303            block_id,
304            SUBPROCESS_OUTPUT_SUBJECT,
305            format!("{error_frame}\n").as_bytes(),
306            filestore.as_ref(),
307            global_zone.as_deref(),
308        );
309    }
310
311    /// Publish a single NDJSON line from container exec output: session-id
312    /// capture, MPS blockfile event, and FileStore write-through. Used by
313    /// `spawn_container_turn`'s output reader task.
314    fn publish_line(
315        line: &str,
316        block_id: &str,
317        session_id_field: &str,
318        inner: &std::sync::Mutex<SubprocessControllerInner>,
319        mstore: &Option<Arc<crate::backend::storage::store::Store>>,
320        event_bus: &Option<Arc<crate::backend::eventbus::EventBus>>,
321        broker: &Option<Arc<crate::backend::mps::Broker>>,
322        filestore: &Option<Arc<crate::backend::storage::filestore::FileStore>>,
323        stats: &mut session_stats::SessionStatsAccumulator,
324        global_output_zone: Option<&str>,
325        last_result_frame: &mut Option<serde_json::Value>,
326        last_inband_error: &mut Option<serde_json::Value>,
327        parked_notices_due: &mut bool,
328    ) {
329        let trimmed = line.trim();
330        if trimmed.is_empty() {
331            return;
332        }
333        stats.record_line(trimmed.len(), mstore);
334
335        if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(trimmed) {
336            // Capture session_id from provider init event.
337            if let Some(sid) = parsed.get(session_id_field).and_then(|v| v.as_str()) {
338                let changed = SubprocessController::record_captured_session_id_inner(inner, sid);
339                if changed {
340                    tracing::info!(block_id = %block_id, session_id = %sid, "container exec: captured session id");
341                    core::persist_session_id(block_id, sid, &mstore, &event_bus);
342                }
343            }
344
345            // Retain the terminal `result` frame for completion-time failure
346            // classification (mirrors host_spawn.rs's stdout_reader).
347            if parsed.get("type").and_then(|v| v.as_str()) == Some("result") {
348                *last_result_frame = Some(parsed);
349            } else if parsed.get("type").and_then(|v| v.as_str()) == Some("assistant")
350                && (parsed.get("isApiErrorMessage").and_then(|v| v.as_bool()).unwrap_or(false)
351                    || parsed.get("error").is_some())
352            {
353                // In-band API error: 401 / auth failures arrive as a synthetic
354                // assistant message (exit 0, is_error:false on result frame) —
355                // capture it so the completion-time classifier below can trip
356                // the failure gate.
357                *last_inband_error = Some(parsed);
358            } else if crate::agents::limit_reset::codex_failure_text(&parsed).is_some() {
359                // Codex reports a failed turn as `error` / `turn.failed` frames.
360                *last_inband_error = Some(parsed);
361            } else if parsed.get("type").and_then(|v| v.as_str()) == Some("turn.completed") {
362                *last_inband_error = None;
363            }
364        }
365
366        // The host's stdout reader does the same with each frame: the context reading, the
367        // compaction boundary that lets this pane's memory reinjection go out, and the memory
368        // card parked for that boundary written after the summary that follows it. Without them a
369        // container's compaction never leaves "compacting", and the card is written 30 s late
370        // with a "no compaction boundary came" warning.
371        let mut release_parked_notices = false;
372        if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(trimmed) {
373            crate::backend::context_reading::observe_claude_frame(block_id, &parsed);
374            // The model a reply came from is told to the pane's chip as the reply arrives: the exec may stay alive for a
375            // background command long after the answer, and the turn's end (`record_outcome`) would be that late.
376            if trimmed.contains("\"model\"") {
377                if let Some(b) = broker.as_deref() {
378                    crate::backend::agent_runtime_container::publish_container_reply(b, block_id);
379                }
380            }
381            if parsed.get("subtype").and_then(|v| v.as_str()) == Some("compact_boundary") {
382                if let Some(uuid) = parsed.get("uuid").and_then(|v| v.as_str()) {
383                    crate::backend::memory::delivery_state::record_compaction_boundary(block_id, uuid);
384                }
385                *parked_notices_due = true;
386            } else if *parked_notices_due && !matches!(parsed.get("type").and_then(|v| v.as_str()), Some("user") | Some("system")) {
387                release_parked_notices = true;
388                *parked_notices_due = false;
389            }
390        }
391
392        if let Some(ref broker) = broker {
393            if release_parked_notices {
394                for notice in crate::backend::memory::delivery_state::take_parked_notices(block_id) {
395                    crate::backend::transcript::append::append_output_line(broker, block_id, &notice, filestore.as_ref(), global_output_zone);
396                }
397            }
398            crate::backend::transcript::append::append_agent_output_line(
399                broker,
400                block_id,
401                trimmed,
402                filestore.as_ref(),
403                global_output_zone,
404                crate::backend::transcript::origin_sig::WriterRuntime::Container,
405            );
406        }
407    }
408}