agentmux_srv_core/backend/blockcontroller/subprocess/host_spawn.rs
1// Copyright 2025, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Host-subprocess turn spawn (`spawn_turn`) for [`SubprocessController`].
5//!
6//! Runs the agent CLI as a `std::process` child (via `tokio::process`) and
7//! writes the turn message to its stdin. `spawn_turn` reads in order: queue
8//! the message if a turn is running, build the argv, claim the session lease
9//! (`claim_turn_lease`), start the process, write the prompt
10//! (`write_prompt_and_close_stdin`), then hand the running turn to its
11//! background tasks: `spawn_stdout_reader`, `spawn_stderr_reader`,
12//! `spawn_lease_renewal` and `spawn_process_waiter`, which closes the turn
13//! (`TurnEnd`: wait for exit or kill, classify a failure, report the end,
14//! release the lease and run lock, drain the queued-message backlog). See
15//! `container_spawn` for the Docker-exec analog used by container agents.
16
17#[cfg(windows)]
18use agentmux_common::win32::NoWindow;
19use std::sync::atomic::{AtomicBool, Ordering};
20use std::sync::{Arc, Mutex};
21
22use tokio::io::{AsyncBufReadExt, BufReader};
23
24#[cfg(unix)]
25use crate::backend::blockcontroller::DEFAULT_GRACEFUL_KILL_WAIT_MS;
26use crate::backend::blockcontroller::{
27 core, publish_controller_status,
28 session_stats, shell, STATUS_DONE, STATUS_RUNNING,
29};
30
31use super::{
32 codex_mcp,
33 argv::{append_prompt_arg, args_for_log, build_turn_argv},
34 SubprocessController, SubprocessSpawnConfig, SUBPROCESS_OUTPUT_SUBJECT,
35};
36
37impl SubprocessController {
38 /// The argv of one turn, the same without anything not to be logged (the
39 /// Codex MCP overrides, codex_mcp.rs, are in the first only), and the
40 /// variables those overrides forward, which the process is launched with, and
41 /// the one that points a Gemini turn at its MCP settings file (gemini_mcp.rs).
42 /// The prompt, when it goes on the command line, is cut from the log by the
43 /// caller (`args_for_log`).
44 fn turn_argv(&self, config: &SubprocessSpawnConfig, session_id: Option<&str>) -> Result<TurnArgv, String> {
45 let build = |base: &[String]| {
46 build_turn_argv(base, &config.resume_strategy, &config.resume_flag, session_id).and_then(|mut args| {
47 if !config.prompt_arg_flag.is_empty() {
48 append_prompt_arg(&mut args, &config.prompt_arg_flag, &config.message)?;
49 }
50 Ok(args)
51 })
52 };
53 let mcp = self.codex_mcp(config);
54 let args = build(&codex_mcp::with_overrides(&config.cli_args, &mcp.overrides))?;
55 let logged = if mcp.overrides.is_empty() { args.clone() } else { build(&config.cli_args)? };
56 let mut env = mcp.env;
57 env.extend(self.gemini_mcp(config));
58 Ok(TurnArgv { args, logged, env })
59 }
60}
61
62/// [`SubprocessController::turn_argv`]'s answer.
63struct TurnArgv {
64 args: Vec<String>,
65 logged: Vec<String>,
66 env: Vec<(String, String)>,
67}
68
69impl SubprocessController {
70 /// Spawn a single turn of the agent CLI.
71 ///
72 /// This is the core method — it spawns `claude -p`, writes the user message to stdin,
73 /// reads NDJSON from stdout (publishing MPS events), and waits for exit.
74 ///
75 /// If a session_id exists from a previous turn, `--resume <sid>` is appended to args.
76 pub fn spawn_turn(&self, config: SubprocessSpawnConfig) -> Result<(), String> {
77 if !self.take_run_lock_for_turn() {
78 // Turn in progress — queue the message for after it exits.
79 self.queue_behind_running_process(config, "subprocess busy");
80 return Ok(());
81 }
82
83 // Hydrate inner.session_id from the config-supplied id if the
84 // controller hasn't captured one yet — MUST run before the
85 // session_id_hint read just below. See
86 // `hydrate_session_id_from_config` for the full rationale
87 // (picker reattach: a fresh controller's inner.session_id is
88 // None, but config.session_id carries the persisted id).
89 // Reordering this after the read (reagent P0 on #2359, an
90 // earlier revision of this same PR) silently dropped --resume
91 // on every reattach's first turn — hydration ran too late for
92 // the read below to see it.
93 self.hydrate_session_id_from_config(config.session_id.as_deref());
94
95 // Read the (now-hydrated) session id once, up front — used
96 // both by the lease claim below and by the resume-flag args
97 // built after it.
98 let session_id_hint = self.inner.lock().unwrap().session_id.clone();
99
100 // A Codex `/compact` compacts the thread through a short-lived App
101 // Server instead of running as an `exec` turn (codex_compact.rs).
102 if super::codex_compact::is_compact_request(&config) {
103 return self.compact_codex_thread(config, session_id_hint);
104 }
105
106 // Build continuation argv before claiming the lease or acknowledging
107 // the message. A malformed provider configuration must fail as an
108 // unstarted turn, not strand the pane in an accepted/running state.
109 let prompt_in_argv = !config.prompt_arg_flag.is_empty();
110 let TurnArgv { args, logged: logged_args, env: mcp_env } = match self.turn_argv(&config, session_id_hint.as_deref()) {
111 Ok(turn) => turn,
112 Err(error) => {
113 self.unlock_run();
114 return Err(error);
115 }
116 };
117
118 // Claim the cross-process session-ownership lease BEFORE `emit_message_accepted` / flipping status
119 // to running: a refusal must look like the turn never started at all (#2359).
120 let claimed_lease = match self.claim_turn_lease(&config, session_id_hint.as_deref()) {
121 Ok(lease) => lease,
122 Err(error) => {
123 self.unlock_run();
124 return Err(error);
125 }
126 };
127
128 // Direct-spawn path (queue was empty): emit the accepted event
129 // now so the frontend can promote its pending entry. The
130 // drain-from-queue path (in process_waiter) emits the same
131 // event just before calling spawn_turn recursively. Only
132 // reached once the lease claim above has succeeded (or was a
133 // no-op) — see that block's comment.
134 self.emit_message_accepted(&config);
135
136 // Update status to running
137 {
138 let mut inner = self.inner.lock().unwrap();
139 Self::set_status(&mut inner, STATUS_RUNNING);
140 }
141 // Mark the turn active BEFORE publishing, so this "running" status
142 // carries turn_active=true: it is the start edge the notification
143 // Router pairs with the process_waiter's turn_active=false to detect
144 // "finished" (subprocess agents otherwise never showed a true→false).
145 self.health_monitor.set_active_turn(true);
146 // Each turn runs its own process: the watchdog's runtime counts from here.
147 self.health_monitor.note_spawned();
148 self.publish_status();
149
150 // Build command — on Windows, .cmd batch wrappers can't be reliably spawned
151 // via cmd.exe /C with piped stdio. Resolve to node <script> instead.
152 let mut cmd = crate::backend::pane_env::make_cli_cmd(&config.cli_command);
153 cmd.args(&args);
154
155 // On Windows: suppress console-window allocation. Without CREATE_NO_WINDOW,
156 // node.exe spawned from a windowless sidecar may try to create/attach to a
157 // console, causing stdout to go to that console rather than the pipe.
158 #[cfg(windows)]
159 {
160 cmd.no_window();
161 }
162 core::apply_working_dir(&mut cmd, &self.block_id, &config.working_dir, &config.env_vars);
163 codex_mcp::apply_env(&mut cmd, &mcp_env);
164 // Identity M4a: record what this process is actually given.
165 crate::backend::identity_spawn::record_process_spawn(
166 &self.block_id,
167 crate::backend::identity_spawn::SpawnPath::Subprocess,
168 &config.env_vars,
169 );
170 // Which model API address this turn's CLI is given, for the connectivity status.
171 core::attach_model_api(&self.block_id, &config.env_vars, &self.mstore, &self.event_bus);
172 cmd.stdin(std::process::Stdio::piped());
173 cmd.stdout(std::process::Stdio::piped());
174 cmd.stderr(std::process::Stdio::piped());
175
176 // Spawn
177 // In the block's tracker before it runs (`spawn_tracked`), so every
178 // descendant it spawns (bg bash, dev servers, watchers) is caught.
179 let spawned = crate::backend::process_tracker::registry::spawn_tracked(&self.block_id, &mut cmd, crate::backend::process_tracker::registry::Join::Agent);
180 if spawned.is_err() {
181 // The turn was marked active (and published) above; a spawn that
182 // never started must not leave it "active" forever — roll back and
183 // publish the terminal state (Codex P2 on #3705). Done before the
184 // map_err below takes the inner lock that publish_status needs.
185 self.health_monitor.set_active_turn(false);
186 }
187 let child = spawned.map_err(|e| {
188 let mut inner = self.inner.lock().unwrap();
189 Self::set_status(&mut inner, STATUS_DONE);
190 inner.proc_exit_code = -1;
191 if let (Some(store), Some(lease)) = (&self.lease_store, &claimed_lease) {
192 if let Err(release_err) = store.release(lease) {
193 tracing::warn!(
194 block_id = %self.block_id,
195 error = %release_err,
196 "lease release failed after spawn failure (self-heals via TTL expiry)"
197 );
198 }
199 }
200 self.unlock_run();
201 format!("failed to spawn subprocess: {e}")
202 });
203 if child.is_err() {
204 // Inner lock released by now: publish DONE with turn_active=false.
205 self.publish_status();
206 }
207 let mut child = child?;
208
209 let pid = child.id().unwrap_or(0);
210 tracing::info!(
211 block_id = %self.block_id,
212 pid = pid,
213 cmd = %config.cli_command,
214 args = ?args_for_log(&logged_args, prompt_in_argv),
215 "subprocess spawned"
216 );
217
218 // Store PID
219 let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<bool>();
220 {
221 let mut inner = self.inner.lock().unwrap();
222 inner.current_pid = Some(pid);
223 inner.kill_tx = Some(kill_tx);
224 }
225
226 // Take ownership of stdin/stdout (piped via Stdio::piped() in spawn config).
227 let stdin = child.stdin.take()
228 .ok_or_else(|| format!("[subprocess] stdin not captured for block {}", self.block_id))?;
229 let stdout = child.stdout.take()
230 .ok_or_else(|| format!("[subprocess] stdout not captured for block {}", self.block_id))?;
231 let stderr = child.stderr.take()
232 .ok_or_else(|| format!("[subprocess] stderr not captured for block {}", self.block_id))?;
233
234 let message = config.message;
235 let user_record = self.user_record_sink(config.message_id.is_some(), config.record.clone());
236 self.write_prompt_and_close_stdin(stdin, message, prompt_in_argv, user_record);
237
238 // Retain the terminal `result` frame so a failure reported on STDOUT
239 // (auth / rate-limit / usage — the common case; claude may even exit 0)
240 // can be classified, not just stderr-reported ones. Shared with the
241 // process_waiter below.
242 let last_result_frame: Arc<Mutex<Option<serde_json::Value>>> = Arc::new(Mutex::new(None));
243 // Track in-band API errors delivered as `assistant` frames (e.g. a
244 // 401 auth failure that claude wraps in a synthetic assistant message
245 // with `"error":"authentication_failed"` and exit 0 — bypasses the
246 // `is_error` flag on the `result` frame entirely).
247 let last_inband_error: Arc<Mutex<Option<serde_json::Value>>> = Arc::new(Mutex::new(None));
248 let stdout_reader_handle = self.spawn_stdout_reader(
249 stdout,
250 config.session_id_field.clone(),
251 Arc::clone(&last_result_frame),
252 Arc::clone(&last_inband_error),
253 );
254
255 // Capture a bounded tail of stderr so a non-zero exit can be classified
256 // into a real cause (SPEC_AGENT_FAILURE_DIAGNOSTICS Phase 2) instead of a
257 // bare "exit N". Shared with the process_waiter below.
258 let stderr_tail: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
259 let stderr_reader_handle = self.spawn_stderr_reader(stderr, Arc::clone(&stderr_tail));
260
261 let turn_done = self.spawn_lease_renewal(&claimed_lease);
262
263 let codex_home = CodexTurn::of(&config.resume_strategy, &config.env_vars);
264 self.spawn_process_waiter(TurnWait {
265 child,
266 kill_rx,
267 stdout_reader_handle,
268 stderr_reader_handle,
269 turn_done,
270 stderr_tail,
271 last_result_frame,
272 last_inband_error,
273 claimed_lease,
274 codex_home,
275 });
276
277 Ok(())
278 }
279}
280
281impl SubprocessController {
282 /// Claim the cross-process session-ownership lease for a turn (see `registry::LeaseStore` and
283 /// `docs/retro/RETRO_DEV_BUILD_SHARED_AGENT_SESSION_COLLISION_2026_07_29.md`). An empty `instance_id` or
284 /// no `lease_store` (registry unavailable) means leasing is a no-op: `Ok(None)`. `Err` carries the
285 /// refusal for a session another AgentMux process owns; the caller releases the run lock.
286 fn claim_turn_lease(
287 &self,
288 config: &SubprocessSpawnConfig,
289 session_id_hint: Option<&str>,
290 ) -> Result<Option<crate::registry::Lease>, String> {
291 if config.instance_id.is_empty() {
292 return Ok(None);
293 }
294 let Some(store) = &self.lease_store else { return Ok(None) };
295 match store.claim(&config.instance_id, &self.boot_id, &self.block_id, session_id_hint) {
296 Ok(lease) => Ok(Some(lease)),
297 Err(crate::registry::LeaseError::HeldByOther { owner_boot_id, age_ms, .. }) => Err(format!(
298 "session '{}' is already owned by another AgentMux process \
299 (boot {owner_boot_id}, renewed {age_ms}ms ago) — refusing to \
300 start a turn against the same session from two processes at once",
301 config.instance_id
302 )),
303 Err(crate::registry::LeaseError::Io(e)) => {
304 tracing::warn!(
305 block_id = %self.block_id,
306 instance_id = %config.instance_id,
307 error = %e,
308 "lease claim failed (io) — proceeding without a lease for this turn"
309 );
310 Ok(None)
311 }
312 }
313 }
314
315 /// Write the user message to the child's stdin, then close it.
316 /// CRITICAL: this must complete BEFORE the child's stdin timeout (Claude CLI: 3s). It uses a real OS
317 /// thread and a synchronous write to bypass the Tokio task scheduler: a `tokio::spawn`'d task may not
318 /// run for seconds on a busy runtime, and the child would time out with "no stdin data received in 3s".
319 fn write_prompt_and_close_stdin(
320 &self,
321 stdin: tokio::process::ChildStdin,
322 message: String,
323 prompt_in_argv: bool,
324 user_record: super::UserRecordSink,
325 ) {
326 let block_id_stdin = self.block_id.clone();
327 {
328 // Convert Tokio's async ChildStdin to a raw OS handle, then
329 // wrap in a std::fs::File for synchronous write. The pipe
330 // buffer (4-64KB on Windows) easily fits our message, so
331 // write_all returns instantly without blocking.
332 #[cfg(unix)]
333 let raw_handle = {
334 use std::os::unix::io::{AsRawFd, FromRawFd};
335 let fd = stdin.as_raw_fd();
336 unsafe { std::fs::File::from_raw_fd(fd) }
337 };
338 #[cfg(windows)]
339 let raw_handle = {
340 use std::os::windows::io::{AsRawHandle, FromRawHandle};
341 let handle = stdin.as_raw_handle();
342 unsafe { std::fs::File::from_raw_handle(handle) }
343 };
344
345 // Spawn a real OS thread (not a Tokio task) for the write.
346 // This ensures it runs immediately regardless of runtime load.
347 // The raw handle is valid as long as `stdin` lives — we move
348 // `stdin` into the thread via a guard to keep it alive.
349 std::thread::spawn(move || {
350 use std::io::Write;
351 let _keep_alive = stdin; // prevent Tokio ChildStdin drop
352 let mut pipe = raw_handle;
353 if prompt_in_argv {
354 // The prompt went on the command line; stdin just closes.
355 std::mem::forget(pipe);
356 user_record.write(&message);
357 return;
358 }
359 let payload = format!("{}\n", message);
360 if let Err(e) = pipe.write_all(payload.as_bytes()) {
361 tracing::warn!(block_id = %block_id_stdin, "subprocess stdin write error: {}", e);
362 std::mem::forget(pipe); // don't close the handle — _keep_alive owns it
363 return;
364 }
365 if let Err(e) = pipe.flush() {
366 tracing::warn!(block_id = %block_id_stdin, "subprocess stdin flush error: {}", e);
367 std::mem::forget(pipe);
368 return;
369 }
370 std::mem::forget(pipe); // don't double-close — _keep_alive owns the handle
371 // Delivered: now the transcript may say so (Codex review).
372 user_record.write(&message);
373 // _keep_alive (Tokio ChildStdin) drops here → EOF to the subprocess
374 });
375 }
376 }
377
378 /// Reads the turn's stdout: counts each line, retains the `result` frame and any in-band API error for
379 /// failure classification, captures the provider's session id from its init event, and publishes every
380 /// line as a blockfile event and a transcript line.
381 fn spawn_stdout_reader(
382 &self,
383 stdout: tokio::process::ChildStdout,
384 session_id_field: String,
385 last_result_frame_read: FrameSlot,
386 last_inband_error_read: FrameSlot,
387 ) -> tokio::task::JoinHandle<()> {
388 let block_id_read = self.block_id.clone();
389 let broker_read = self.broker.clone();
390 let inner_read = Arc::clone(&self.inner);
391 let mstore_read = self.mstore.clone();
392 let event_bus_read = self.event_bus.clone();
393 let filestore_read = self.filestore.clone();
394 let health_read = Arc::clone(&self.health_monitor);
395 // Resolve the agent's GLOBAL transcript zone once (see persistent/spawn.rs).
396 let global_output_zone =
397 crate::backend::transcript::append::resolve_global_output_zone(&self.mstore, &self.block_id);
398 tokio::spawn(async move {
399 let reader = BufReader::new(stdout);
400 let mut lines = reader.lines();
401 let mut stats = session_stats::SessionStatsAccumulator::new(block_id_read.clone());
402
403 tracing::info!(block_id = %block_id_read, "stdout_reader started");
404
405 loop {
406 match lines.next_line().await {
407 Err(e) => {
408 tracing::warn!(block_id = %block_id_read, error = %e, "subprocess stdout read error");
409 break;
410 }
411 Ok(None) => {
412 tracing::info!(block_id = %block_id_read, "subprocess stdout EOF");
413 break;
414 }
415 Ok(Some(line)) => {
416 let trimmed = line.trim();
417 if trimmed.is_empty() {
418 continue;
419 }
420
421 // Track session metadata (debounced 1 s).
422 // Use `line.len()` (not `trimmed.len()`) to match persistent/stdout_reader.rs
423 // so token_estimate stays consistent across controller types.
424 stats.record_line(line.len(), &mstore_read);
425 health_read.note_output();
426
427 if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(trimmed) {
428 // Try to capture session/thread ID from the provider's init event.
429 // Claude: {"type":"system","subtype":"init","session_id":"..."}
430 // Gemini: {"type":"init","session_id":"..."}
431 // Codex: {"type":"thread.started","thread_id":"..."}
432 // Read before the frame may move into a slot below.
433 let sid = parsed
434 .get(&session_id_field)
435 .and_then(|v| v.as_str())
436 .map(str::to_string);
437
438 retain_failure_frame(parsed, &last_result_frame_read, &last_inband_error_read);
439
440 if let Some(sid_string) = sid {
441 capture_session_id(&inner_read, &block_id_read, &session_id_field, &sid_string, &mstore_read, &event_bus_read);
442 }
443 }
444
445 // Publish the NDJSON line as a MPS blockfile event on the "output" subject
446 // and write-through to FileStore for persistent history (Phase 1.3).
447 if let Some(ref broker) = broker_read {
448 crate::backend::transcript::append::append_agent_output_line(
449 broker,
450 &block_id_read,
451 trimmed,
452 filestore_read.as_ref(),
453 global_output_zone.as_deref(),
454 crate::backend::transcript::origin_sig::WriterRuntime::Host,
455 );
456 }
457 }
458 }
459 }
460
461 tracing::info!(block_id = %block_id_read, "stdout_reader exiting");
462 })
463 }
464
465 /// Logs the turn's stderr and retains its last ~40 non-empty lines for failure classification.
466 fn spawn_stderr_reader(
467 &self,
468 stderr: tokio::process::ChildStderr,
469 stderr_tail_reader: Arc<Mutex<Vec<String>>>,
470 ) -> tokio::task::JoinHandle<()> {
471 let block_id_err = self.block_id.clone();
472 tokio::spawn(async move {
473 let reader = BufReader::new(stderr);
474 let mut lines = reader.lines();
475 loop {
476 match lines.next_line().await {
477 Err(e) => {
478 tracing::warn!(block_id = %block_id_err, error = %e, "subprocess stderr read error");
479 break;
480 }
481 Ok(None) => break,
482 Ok(Some(line)) => {
483 if !line.trim().is_empty() {
484 crate::backend::blockcontroller::stderr_log::log_stderr_line(&block_id_err, "subprocess", &line, false);
485 // Retain the last ~40 non-empty lines for classification.
486 let mut buf = stderr_tail_reader.lock().unwrap();
487 buf.push(line);
488 let overflow = buf.len().saturating_sub(40);
489 if overflow > 0 {
490 buf.drain(0..overflow);
491 }
492 }
493 }
494 }
495 }
496 })
497 }
498
499 /// Renews the lease (if any) on its own interval, for as long as THIS turn is active; returns the
500 /// per-turn flag the turn's process waiter sets to stop it. Only host turns claim a lease.
501 ///
502 /// The exit condition is a fresh per-turn flag, NOT `health_monitor.is_active_turn()`, which is shared
503 /// by the whole controller: queued messages drain synchronously in the process waiter, so the next
504 /// turn's `set_active_turn(true)` can land in the same tick this turn releases its lease. A renewal
505 /// task watching the shared flag would see it flip back before its next tick and never end, leaking
506 /// one task per turn in a busy conversation (#2359).
507 fn spawn_lease_renewal(&self, claimed_lease: &Option<crate::registry::Lease>) -> Arc<AtomicBool> {
508 let turn_done = Arc::new(AtomicBool::new(false));
509 if let (Some(store), Some(lease)) = (self.lease_store.clone(), claimed_lease.clone()) {
510 let turn_done_renew = Arc::clone(&turn_done);
511 let block_id_renew = self.block_id.clone();
512 tokio::spawn(async move {
513 let mut interval =
514 tokio::time::interval(std::time::Duration::from_millis(
515 crate::registry::RENEW_INTERVAL_MS,
516 ));
517 loop {
518 interval.tick().await;
519 if turn_done_renew.load(Ordering::SeqCst) {
520 break;
521 }
522 // Blocking OS file lock + fsync'd write: off the async
523 // worker (see `backend::blocking`).
524 let (s, l) = (Arc::clone(&store), lease.clone());
525 let renewed = tokio::task::spawn_blocking(move || s.renew(&l).map_err(|e| e.to_string()))
526 .await
527 .unwrap_or_else(|e| Err(format!("renew task failed: {e}")));
528 if let Err(e) = renewed {
529 // Lost the lease to a TTL reclaim mid-turn — log and
530 // let the turn finish naturally rather than killing
531 // it. Force-killing on lost renewal is deliberately
532 // deferred (see the analysis doc's follow-ups); this
533 // is a real residual gap, not an oversight.
534 tracing::warn!(
535 block_id = %block_id_renew,
536 instance_id = %lease.instance_id(),
537 error = %e,
538 "lease renew failed — lease may have been reclaimed by another process"
539 );
540 break;
541 }
542 }
543 });
544 }
545 turn_done
546 }
547
548 /// Waits for the turn's process to exit or be killed, then closes the turn: joins the readers and
549 /// classifies a failure, reports the end, releases the lease and the run lock, and drains the next
550 /// queued message.
551 fn spawn_process_waiter(&self, wait: TurnWait) {
552 let TurnWait {
553 mut child,
554 kill_rx,
555 stdout_reader_handle,
556 stderr_reader_handle,
557 turn_done,
558 stderr_tail,
559 last_result_frame,
560 last_inband_error,
561 claimed_lease,
562 codex_home,
563 } = wait;
564 let end = TurnEnd {
565 inner: Arc::clone(&self.inner),
566 block_id: self.block_id.clone(),
567 broker: self.broker.clone(),
568 mstore: self.mstore.clone(),
569 event_bus: self.event_bus.clone(),
570 filestore: self.filestore.clone(),
571 health: Arc::clone(&self.health_monitor),
572 run_lock: Arc::clone(&self.run_lock),
573 lease_store: self.lease_store.clone(),
574 self_ref: self.self_ref.lock().unwrap().clone().unwrap_or_default(),
575 };
576 tokio::spawn(async move {
577 let clean_exit = end.wait_for_exit(&mut child, kill_rx).await;
578 let run_failure = match clean_exit {
579 Some((exit_code, exit_signal)) => {
580 end.classify_clean_exit(
581 exit_code,
582 exit_signal,
583 (stdout_reader_handle, stderr_reader_handle),
584 &TurnFrames { stderr_tail, last_result_frame, last_inband_error },
585 codex_home,
586 )
587 .await
588 }
589 None => None,
590 };
591 end.report_end(clean_exit.is_some(), run_failure.as_ref());
592 end.release_turn(&turn_done, &claimed_lease);
593 end.drain_next_queued();
594 });
595 }
596}
597
598/// What a turn's stdout and stderr readers retained for classifying its failure.
599struct TurnFrames {
600 stderr_tail: Arc<Mutex<Vec<String>>>,
601 last_result_frame: FrameSlot,
602 last_inband_error: FrameSlot,
603}
604
605/// The handles a turn's process waiter closes the turn with (clones of the controller's own).
606struct TurnEnd {
607 inner: Arc<Mutex<super::SubprocessControllerInner>>,
608 block_id: String,
609 broker: Option<Arc<crate::backend::mps::Broker>>,
610 mstore: Option<Arc<crate::backend::storage::store::Store>>,
611 event_bus: Option<Arc<crate::backend::eventbus::EventBus>>,
612 filestore: Option<Arc<crate::backend::storage::filestore::FileStore>>,
613 health: Arc<crate::backend::blockcontroller::health::TurnActivityTracker>,
614 run_lock: Arc<AtomicBool>,
615 lease_store: Option<Arc<crate::registry::LeaseStore>>,
616 self_ref: std::sync::Weak<SubprocessController>,
617}
618
619impl TurnEnd {
620 /// Wait for either process exit or a kill signal and record the exit. `Some((code, signal))` is a
621 /// process that exited on its own; a stop returns `None` and stays unclassified.
622 async fn wait_for_exit(
623 &self,
624 child: &mut tokio::process::Child,
625 kill_rx: tokio::sync::oneshot::Receiver<bool>,
626 ) -> Option<(i32, Option<i32>)> {
627 let mut clean_exit: Option<(i32, Option<i32>)> = None;
628 // Wait for either process exit or kill signal
629 tokio::select! {
630 exit_result = child.wait() => {
631 let (exit_code, exit_signal) = match exit_result {
632 Ok(status) => {
633 let code = status.code().unwrap_or(-1);
634 #[cfg(unix)]
635 let sig = std::os::unix::process::ExitStatusExt::signal(&status);
636 #[cfg(not(unix))]
637 let sig: Option<i32> = None;
638 (code, sig)
639 }
640 Err(e) => {
641 tracing::warn!(
642 block_id = %self.block_id,
643 error = %e,
644 "subprocess wait error"
645 );
646 (-1, None)
647 }
648 };
649
650 tracing::info!(
651 block_id = %self.block_id,
652 exit_code = exit_code,
653 "subprocess exited"
654 );
655
656 // Update inner state
657 {
658 let mut inner = self.inner.lock().unwrap();
659 inner.proc_exit_code = exit_code;
660 SubprocessController::set_status(&mut inner, STATUS_DONE);
661 inner.current_pid = None;
662 inner.kill_tx = None;
663 }
664
665 // Defer classification until after the readers are joined
666 // (below); a user-initiated stop (kill arm) stays unclassified.
667 clean_exit = Some((exit_code, exit_signal));
668 }
669 force = kill_rx => {
670 let force = force.unwrap_or(false);
671 tracing::info!(
672 block_id = %self.block_id,
673 force = force,
674 "subprocess kill requested"
675 );
676
677 // The final kill takes the CLI's process group (its MCP
678 // servers) with it; the SIGTERM stays the CLI's own.
679 if force {
680 let _ = agentmux_common::process::kill_child_and_group(child).await;
681 } else {
682 // On Unix, send SIGTERM. On Windows, kill() is the only option.
683 #[cfg(unix)]
684 {
685 if let Some(pid) = child.id() {
686 unsafe { libc::kill(pid as i32, libc::SIGTERM); }
687 }
688 // Give it a moment to exit gracefully
689 tokio::time::sleep(tokio::time::Duration::from_millis(
690 DEFAULT_GRACEFUL_KILL_WAIT_MS,
691 )).await;
692 let _ = agentmux_common::process::kill_child_and_group(child).await;
693 }
694 #[cfg(not(unix))]
695 {
696 let _ = child.kill().await;
697 }
698 }
699
700 let _ = child.wait().await;
701
702 {
703 let mut inner = self.inner.lock().unwrap();
704 inner.proc_exit_code = -1;
705 SubprocessController::set_status(&mut inner, STATUS_DONE);
706 inner.current_pid = None;
707 inner.kill_tx = None;
708 }
709 }
710 }
711 clean_exit
712 }
713
714 /// Classify a genuine non-zero exit OR a failure reported on stdout as an error `result` frame (auth,
715 /// rate-limit, usage; claude may even exit 0). The stdout and stderr readers are joined first
716 /// (bounded) so their final lines, the ones carrying the error text, are in the buffers before they
717 /// are read.
718 async fn classify_clean_exit(
719 &self,
720 exit_code: i32,
721 exit_signal: Option<i32>,
722 readers: (tokio::task::JoinHandle<()>, tokio::task::JoinHandle<()>),
723 frames: &TurnFrames,
724 codex_home: Option<CodexTurn>,
725 ) -> Option<crate::agents::failure::AgentFailure> {
726 let (stdout_reader_handle, stderr_reader_handle) = readers;
727 let TurnFrames { stderr_tail, last_result_frame, last_inband_error } = frames;
728 let mut run_failure: Option<crate::agents::failure::AgentFailure> = None;
729 let drain = std::time::Duration::from_secs(2);
730 let _ = tokio::time::timeout(drain, stdout_reader_handle).await;
731 let _ = tokio::time::timeout(drain, stderr_reader_handle).await;
732 let result_frame = last_result_frame.lock().unwrap().clone();
733 let frame_is_error = result_frame
734 .as_ref()
735 .and_then(|f| f.get("is_error"))
736 .and_then(|v| v.as_bool())
737 .unwrap_or(false);
738 // Also catch in-band API errors (e.g. auth 401) delivered as
739 // synthetic assistant messages with exit 0 and is_error:false.
740 let inband_error_frame = last_inband_error.lock().unwrap().clone();
741 let inband_is_api_error = inband_error_frame.is_some();
742 if exit_code != 0 || frame_is_error || inband_is_api_error {
743 let tail = stderr_tail.lock().unwrap().join("\n");
744 // Merge the in-band error text so classify() sees the
745 // "authentication_failed" / "401" string even though it
746 // arrived on stdout, not stderr.
747 let inband_text = inband_error_frame.as_ref().map(crate::agents::limit_reset::inband_error_text).unwrap_or_default();
748 let combined_tail = if inband_text.trim().is_empty() {
749 tail
750 } else {
751 format!("{tail}\n{inband_text}")
752 };
753 run_failure = Some(crate::agents::failure::classify(
754 Some(exit_code),
755 exit_signal,
756 &combined_tail,
757 result_frame.as_ref(),
758 ));
759 }
760 self.publish_codex_context(codex_home).await;
761 run_failure
762 }
763
764 /// A Codex turn's context and the calls it made, read from its session file once it exits (`codex_context.rs`,
765 /// `codex_usage.rs`): `codex exec` reports only the thread's totals.
766 async fn publish_codex_context(&self, codex: Option<CodexTurn>) {
767 let thread_id = self.inner.lock().unwrap().session_id.clone();
768 let (Some(CodexTurn { home, started_ms }), Some(thread_id)) = (codex, thread_id) else { return };
769 let zone = crate::backend::transcript::append::resolve_global_output_zone(&self.mstore, &self.block_id);
770 let (home_for_calls, thread_for_calls) = (home.clone(), thread_id.clone());
771 let calls = tokio::task::spawn_blocking(move || super::codex_usage::read_new(&home_for_calls, &thread_for_calls, started_ms)).await;
772 if let (Ok(calls), Some(zone)) = (calls, zone.as_deref()) {
773 crate::backend::token_ledger::note_found(zone, &calls);
774 }
775 let Some(broker) = self.broker.as_ref() else { return };
776 let read = tokio::task::spawn_blocking(move || super::codex_context::read(&home, &thread_id)).await;
777 if let Ok(Some(ctx)) = read {
778 crate::backend::context_reading::observe_codex(&self.block_id, ctx.tokens, ctx.window, ctx.model.clone());
779 crate::backend::blockcontroller::shell::handle_append_block_file(
780 broker,
781 &self.block_id,
782 SUBPROCESS_OUTPUT_SUBJECT,
783 format!("{}\n", super::codex_context::frame(&ctx)).as_bytes(),
784 self.filestore.as_ref(),
785 zone.as_deref(),
786 );
787 }
788 }
789
790 /// Record the exit for the health monitor, publish the done status, persist or clear the failure,
791 /// and tell the pane about it.
792 fn report_end(&self, exited_on_its_own: bool, run_failure: Option<&crate::agents::failure::AgentFailure>) {
793 // Update health monitor with exit status
794 {
795 let inner = self.inner.lock().unwrap();
796 self.health.set_turn_exited(inner.proc_exit_code, inner.proc_exit_code == 0 && run_failure.is_none());
797 }
798
799 // Publish done status
800 if let Some(ref broker) = self.broker {
801 let status = {
802 let inner = self.inner.lock().unwrap();
803 SubprocessController::build_status_snapshot(&inner, &self.block_id, false)
804 };
805 publish_controller_status(broker, &status);
806 }
807
808 // Persist or clear agent:last_failure in block meta so the recovery
809 // banner survives tab switches and page reloads (P1.1 of
810 // SPEC_AGENT_ERROR_FRAMEWORK_2026_06_20). Done before the MPS
811 // publish so the durable state is written first; the event is then
812 // a low-latency push to any active subscriber.
813 core::persist_last_failure(
814 &self.block_id,
815 run_failure,
816 &self.mstore,
817 &self.event_bus,
818 );
819 // Only a process that exited on its own says anything about the API; a stop leaves `clean_exit` unset.
820 if exited_on_its_own {
821 core::report_provider_turn(&self.block_id, run_failure, &self.mstore);
822 if run_failure.is_none() {
823 crate::backend::limit_evidence::clean_turn(&self.block_id, &self.mstore, &self.event_bus);
824 }
825 }
826
827 // Surface the classified failure cause to the pane (Phase 2 of
828 // SPEC_AGENT_FAILURE_DIAGNOSTICS). persist:1 so reconnecting
829 // subscribers also receive the last failure without needing a
830 // separate meta read (belt-and-suspenders with the meta write above).
831 if let (Some(failure), Some(broker)) = (run_failure, self.broker.as_ref()) {
832 broker.publish_event::<crate::backend::mps_events::AgentFailed>(failure, vec![format!("block:{}", self.block_id)], 1);
833 }
834 }
835
836 /// Stop the renewal task, release the lease (if any), then the run lock.
837 fn release_turn(&self, turn_done: &AtomicBool, claimed_lease: &Option<crate::registry::Lease>) {
838 // Signal the renewal task to stop BEFORE releasing the
839 // lease/run_lock — a queued next turn (dequeued a few
840 // lines below) may spawn immediately and claim its own
841 // lease; this turn's renewal task must not still be
842 // ticking when that happens (reagent P1 on #2359).
843 turn_done.store(true, Ordering::SeqCst);
844
845 // Release the lease (if any), then the run lock — mirrors
846 // the ordering in the spawn-failure closure above.
847 if let (Some(store), Some(lease)) = (&self.lease_store, &claimed_lease) {
848 // Synchronous: the release must land before run_lock drops
849 // below and a queued turn claims its own lease.
850 if let Err(e) = crate::backend::blocking::off_async_worker(|| store.release(lease)) {
851 tracing::warn!(
852 block_id = %self.block_id,
853 instance_id = %lease.instance_id(),
854 error = %e,
855 "lease release failed (self-heals via TTL expiry)"
856 );
857 }
858 }
859 self.run_lock.store(false, Ordering::SeqCst);
860 }
861
862 /// Run the next message queued while the turn was running.
863 fn drain_next_queued(&self) {
864 // Drain message queue: if messages were queued while this turn
865 // was running, pop the next one and spawn it via the weak
866 // self-reference.
867 let next_config = {
868 let mut inner = self.inner.lock().unwrap();
869 inner.pending_messages.pop_front()
870 };
871 if let Some(config) = next_config {
872 if let Some(ctrl) = self.self_ref.upgrade() {
873 tracing::info!(
874 block_id = %self.block_id,
875 "draining queued message"
876 );
877 if let Err(e) = ctrl.spawn_turn(config) {
878 tracing::warn!(
879 block_id = %self.block_id,
880 error = %e,
881 "failed to spawn queued turn"
882 );
883 // The message was already popped from the queue —
884 // a bare warn-log here means it vanishes with no
885 // trace the user can see (reagent P1 on #2359,
886 // most likely to fire on a lease refusal: another
887 // process claimed this session in the gap between
888 // this turn's release and the drain). Surface it
889 // the same way other pre-spawn failures in this
890 // module do (e.g. input.rs's container
891 // ensure_running failure): a visible error frame
892 // in the block, not just a log line.
893 let error_frame = serde_json::json!({
894 "type": "result",
895 "is_error": true,
896 "subtype": "error_during_execution",
897 "error": {"message": format!("[AgentMux] queued message could not be sent: {e}")}
898 }).to_string();
899 if let Some(ref broker) = self.broker {
900 // Into the agent's global zone too: that is what
901 // the pane reads on reload (Phase 5a-3c).
902 let global_zone =
903 crate::backend::transcript::append::resolve_global_output_zone(&self.mstore, &self.block_id);
904 crate::backend::blockcontroller::shell::handle_append_block_file(
905 broker,
906 &self.block_id,
907 SUBPROCESS_OUTPUT_SUBJECT,
908 format!("{error_frame}\n").as_bytes(),
909 self.filestore.as_ref(),
910 global_zone.as_deref(),
911 );
912 }
913 }
914 }
915 }
916 }
917}
918
919/// The most recent frame of one kind a turn's stdout reader retains for its process waiter.
920type FrameSlot = Arc<Mutex<Option<serde_json::Value>>>;
921
922/// A Codex turn's `CODEX_HOME` and when its process started.
923struct CodexTurn {
924 home: std::path::PathBuf,
925 started_ms: i64,
926}
927
928impl CodexTurn {
929 /// The turn about to be waited on, when it is a host Codex one.
930 fn of(resume_strategy: &str, env_vars: &std::collections::HashMap<String, String>) -> Option<Self> {
931 let home = (resume_strategy == "codex-exec").then(|| super::codex_context::codex_home(env_vars)).flatten()?;
932 Some(Self { home, started_ms: agentmux_common::time::now_ms() })
933 }
934}
935
936/// What a turn's process waiter takes over once the process is running.
937struct TurnWait {
938 child: tokio::process::Child,
939 kill_rx: tokio::sync::oneshot::Receiver<bool>,
940 stdout_reader_handle: tokio::task::JoinHandle<()>,
941 stderr_reader_handle: tokio::task::JoinHandle<()>,
942 turn_done: Arc<AtomicBool>,
943 stderr_tail: Arc<Mutex<Vec<String>>>,
944 last_result_frame: FrameSlot,
945 last_inband_error: FrameSlot,
946 claimed_lease: Option<crate::registry::Lease>,
947 /// A Codex turn's `CODEX_HOME`: its context is read from its session file once it exits
948 /// (`codex_context.rs`), since `codex exec` reports only the thread's totals.
949 codex_home: Option<CodexTurn>,
950}
951
952/// Keep the frames a failure is classified from: the terminal `result` frame, and an in-band API error
953/// (a 401 arrives as a synthetic assistant message, or a Codex `error` / `turn.failed` frame, with exit 0).
954/// A completed Codex turn clears the in-band error.
955fn retain_failure_frame(parsed: serde_json::Value, last_result_frame: &FrameSlot, last_inband_error: &FrameSlot) {
956 // Retain the terminal `result` frame for failure
957 // classification.
958 if parsed.get("type").and_then(|v| v.as_str()) == Some("result") {
959 *last_result_frame.lock().unwrap() = Some(parsed);
960 } else if parsed.get("type").and_then(|v| v.as_str()) == Some("assistant")
961 && (parsed.get("isApiErrorMessage").and_then(|v| v.as_bool()).unwrap_or(false)
962 || parsed.get("error").is_some())
963 {
964 // In-band API error: 401 / auth failures arrive as a synthetic
965 // assistant message (exit 0, is_error:false on result frame) —
966 // capture it so the process_waiter can trip the failure gate.
967 *last_inband_error.lock().unwrap() = Some(parsed);
968 } else if crate::agents::limit_reset::codex_failure_text(&parsed).is_some() {
969 // Codex reports a failed turn (a usage limit
970 // included) as `error` / `turn.failed` frames on
971 // stdout, not on stderr.
972 *last_inband_error.lock().unwrap() = Some(parsed);
973 } else if parsed.get("type").and_then(|v| v.as_str()) == Some("turn.completed") {
974 *last_inband_error.lock().unwrap() = None;
975 }
976}
977
978/// The CLI's own session id is authoritative: it overwrites any earlier value (a stale hydrated id from a
979/// picker reattach included) and is de-duplicated when the same id repeats across turns. See
980/// `SubprocessController::record_captured_session_id_inner`.
981fn capture_session_id(
982 inner: &Arc<Mutex<super::SubprocessControllerInner>>,
983 block_id: &str,
984 session_id_field: &str,
985 sid: &str,
986 mstore: &Option<Arc<crate::backend::storage::store::Store>>,
987 event_bus: &Option<Arc<crate::backend::eventbus::EventBus>>,
988) {
989 if SubprocessController::record_captured_session_id_inner(inner, sid) {
990 tracing::info!(block_id = %block_id, field = %session_id_field, session_id = %sid, "captured session id");
991 core::persist_session_id(block_id, sid, mstore, event_bus);
992 }
993}