agentmux_srv_core/backend/blockcontroller/persistent/spawn_steps.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The steps of [`spawn_process`](PersistentSubprocessController::spawn_process), one function
5//! each, in the order they ran: launch the child, take its pipes, mark the process running,
6//! register the spawn, start the stdin writer, the stdout reader and the process waiter. Moved
7//! out of `spawn_process` without a change in behaviour.
8
9use super::process_waiter::ProcessWaiterCtx;
10use super::spawn::ResumeSpawn;
11use super::stderr_reader::StderrReaderCtx;
12use super::stdout_reader::StdoutReaderCtx;
13use super::*;
14#[cfg(windows)]
15use agentmux_common::win32::NoWindow;
16
17/// What one spawn learned while launching its child, for the steps that follow.
18pub(super) struct Launch {
19 child: tokio::process::Child,
20 pid: u32,
21 spawn_args: Vec<String>,
22 attempted_resume_sid: Option<String>,
23 relocated_copy: Option<crate::backend::continuity_relocate::Relocated>,
24 forked: bool,
25 resume_claim: Option<std::sync::MutexGuard<'static, ()>>,
26 agent_lease: Option<Arc<crate::backend::agent_admission::HeldAgentLease>>,
27 my_generation: u64,
28 my_registration_nonce: u64,
29 continuation: Option<String>,
30 had_retry_payload: bool,
31}
32
33/// The child's pipes, the kill channel and the stderr reader's handle.
34pub(super) struct Pipes {
35 pub(super) stdin: tokio::process::ChildStdin,
36 pub(super) stdout: tokio::process::ChildStdout,
37 pub(super) kill_tx: tokio::sync::oneshot::Sender<KillRequest>,
38 pub(super) kill_rx: tokio::sync::oneshot::Receiver<KillRequest>,
39 pub(super) stderr_reader_handle: Option<tokio::task::JoinHandle<()>>,
40}
41
42/// What registering the spawn produced, for the readers and the waiter.
43pub(super) struct Registered {
44 agent_id_for_muxbus: Option<String>,
45 segment_read: super::segments::SegmentRef,
46 segment_wait: super::segments::SegmentRef,
47 relocated_copy_read: Option<crate::backend::continuity_relocate::Relocated>,
48 forked_from_read: Option<String>,
49 exit_cleanup_nonce: u64,
50}
51
52/// The stdout reader's handle, and what the waiter needs from the same record.
53pub(super) struct StdoutTask {
54 handle: tokio::task::JoinHandle<()>,
55 global_output_zone_wait: Option<String>,
56 record_fence_wait: Option<crate::backend::agent_admission::RecordFence>,
57}
58
59impl PersistentSubprocessController {
60 /// Builds the command, takes the agent's lease, decides the resume and starts the child.
61 pub(super) fn start_child(
62 &self,
63 config: &PersistentSpawnConfig,
64 resume_retry_payload: Option<persistent_resume::QueuedRetryEntry>,
65 ) -> Result<Launch, String> {
66 // Captured before `resume_retry_payload` is moved further down (the
67 // resume-bookkeeping match), for the turn-active decision in
68 // `take_pipes` — see that check's own comment. Every
69 // pre-existing caller either passes `Some(payload)` (a message is
70 // about to be delivered directly) or `None` because a message is
71 // already sitting in `pending_send_messages` waiting to be drained
72 // right after this spawn succeeds (`respawn_once_for_leftover_
73 // queue`) — this flag alone can't tell those two `None` cases
74 // apart, which is exactly why the check in `take_pipes` also looks at
75 // the queue.
76 let had_retry_payload = resume_retry_payload.is_some();
77
78 // Build command — use make_cli_cmd to resolve .cmd wrappers to node on Windows
79 let mut cmd = crate::backend::pane_env::make_cli_cmd(&config.cli_command);
80
81 self.hydrate_session_id_from_config(config);
82
83 let inherited = self.inherited_fork_session();
84 let unreachable_history_session =
85 self.continue_first_spawn_history(config, inherited.as_deref());
86 // Claim the agent's single-live-instance lease, then — under it — let
87 // the resume gate decide which session is resumed. Any early return
88 // after this point drops the handle, which releases the lease.
89 let gfs = crate::backend::agent_session::global_transcript_store();
90 let agent_lease =
91 self.lease_then_gate(config, gfs.map(|g| &**g), unreachable_history_session)?;
92 // The parent session a fork inherited is resumed as a fork, never in
93 // place, however its id got here: the launch, the pane's history, the
94 // gate (`agent_session::fork_history`).
95 if let Some(parent_sid) = inherited.as_deref() {
96 let mut inner = self.inner.lock().unwrap();
97 if inner.session_id.as_deref() == Some(parent_sid) {
98 inner.fork_next = true;
99 }
100 }
101
102 let ResumeSpawn {
103 spawn_args,
104 attempted_resume_sid,
105 relocated_copy,
106 forked,
107 claim: resume_claim,
108 } = self.resume_spawn(config)?;
109 cmd.args(&spawn_args);
110
111 self.prepare_command(&mut cmd, config);
112
113 // Don't even start a config restart's replacement a Stop has already
114 // cancelled (see `restart_spawn_still_permitted_locked`); the decision
115 // itself is made where the child is installed, below.
116 Self::restart_spawn_still_permitted_locked(&mut self.inner.lock().unwrap())?;
117
118 // In the block's tracker before it runs (`spawn_tracked`).
119 let child = crate::backend::process_tracker::registry::spawn_tracked(&self.block_id, &mut cmd, crate::backend::process_tracker::registry::Join::Agent).map_err(|e| {
120 tracing::error!(block_id = %self.block_id, error = %e, "persistent process spawn failed");
121 format!("failed to spawn persistent process: {e}")
122 })?;
123
124 let (child, my_generation, superseded_effects) =
125 self.install_new_process(child, config, &attempted_resume_sid, resume_retry_payload)?;
126 // Identity for this spawn's muxbus/registry registrations
127 // (`registration_nonce` on `AgentRegistration`/`AgentEntry`).
128 // Deliberately NOT `my_generation`: the generation is
129 // controller-LOCAL (starts at 0 per controller instance), so a
130 // replacement controller for this same block
131 // (`resync_controller` stops the old one asynchronously and
132 // constructs a new one immediately) restarts at generation 1 —
133 // the old and new processes could then share a generation, and
134 // the old exit-handler's compare-and-remove would accept the
135 // replacement's fresh registration as its own and delete it
136 // (codex P1 on PR #2500). A process-wide counter can never
137 // collide across controller instances.
138 let my_registration_nonce = next_registration_nonce();
139 self.flush_superseded_effects(superseded_effects);
140 self.arm_route_trial();
141
142 let continuation = self.disclose_fresh_start(&attempted_resume_sid, my_generation, had_retry_payload);
143 let continuation = self.carry_prep_handoff(continuation);
144 let pid = child.id().unwrap_or(0);
145 Ok(Launch {
146 child,
147 pid,
148 spawn_args,
149 attempted_resume_sid,
150 relocated_copy,
151 forked,
152 resume_claim,
153 agent_lease,
154 my_generation,
155 my_registration_nonce,
156 continuation,
157 had_retry_payload,
158 })
159 }
160
161 /// Sets the working directory and environment, and pipes the child's stdio.
162 fn prepare_command(&self, cmd: &mut tokio::process::Command, config: &PersistentSpawnConfig) {
163 core::apply_working_dir(cmd, &self.block_id, &config.working_dir, &config.env_vars);
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::Persistent,
168 &config.env_vars,
169 );
170
171 // On Windows: suppress console-window allocation. The srv runs without a
172 // console of its own, so spawning the agent CLI without CREATE_NO_WINDOW
173 // makes Windows allocate a fresh console — which Windows 11's default-
174 // terminal handler renders as a NEW Windows Terminal window. One leaks per
175 // agent start / resume / respawn; a flapping or restart-heavy session
176 // accumulates dozens. stdio is piped here, so the console is never needed.
177 // See docs/retro/retro-windows-terminal-window-leak-2026-06-21.md.
178 // Matches acp.rs / subprocess/host_spawn.rs; sibling of shell/pty.rs's
179 // PTY path.
180 #[cfg(windows)]
181 {
182 cmd.no_window();
183 }
184
185 cmd.stdin(std::process::Stdio::piped());
186 cmd.stdout(std::process::Stdio::piped());
187 cmd.stderr(std::process::Stdio::piped());
188 }
189
190 /// Takes the child's pipes, marks the turn active when one is under way and starts the stderr reader.
191 pub(super) fn take_pipes(
192 &self,
193 config: &PersistentSpawnConfig,
194 launch: &mut Launch,
195 ) -> Result<Pipes, String> {
196 let pid = launch.pid;
197 let spawn_args = &launch.spawn_args;
198 let attempted_resume_sid = &launch.attempted_resume_sid;
199 let my_generation = launch.my_generation;
200 let had_retry_payload = launch.had_retry_payload;
201 // Notify the turn-activity tracker that a turn is starting — but
202 // only if one actually is. Every pre-existing caller of this method
203 // always has a message about to flow through, one way or the other
204 // (see `had_retry_payload`'s own comment), so this was previously
205 // unconditionally correct. `PersistentSubprocessController::
206 // start()`'s eager-resume path (issue #3463) is the first caller
207 // that genuinely has nothing queued — it revives a session so it is
208 // ready for the NEXT message, the same as `ShellController::
209 // start()` reviving a shell leaves it idle rather than mid-command.
210 // Marking a turn active here with no message ever sent meant a
211 // freshly eager-resumed pane was reported as perpetually WORKING —
212 // to the pane UI, Swarm view, subagent watcher, and shutdown logic,
213 // all of which read this flag — until a human happened to notice
214 // and send it something, since nothing would ever produce the
215 // `result` frame that normally clears it (codex P1 on PR #3513).
216 if had_retry_payload || !self.inner.lock().unwrap().pending_send_messages.is_empty() {
217 self.health_monitor.set_active_turn(true);
218 }
219
220 tracing::info!(
221 block_id = %self.block_id,
222 pid = pid,
223 cmd = %config.cli_command,
224 args = ?spawn_args,
225 working_dir = %config.working_dir,
226 "persistent process spawned"
227 );
228
229 let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<KillRequest>();
230 let stdin = launch.child.stdin.take().ok_or_else(|| {
231 format!(
232 "[persistent] stdin not captured for block {}",
233 self.block_id
234 )
235 })?;
236 let stdout = launch.child.stdout.take().ok_or_else(|| {
237 format!(
238 "[persistent] stdout not captured for block {}",
239 self.block_id
240 )
241 })?;
242 let stderr = launch.child.stderr.take();
243
244 // Drain stderr in background — log lines for debugging. The
245 // JoinHandle is kept (not discarded) so the process-waiter task
246 // can await this task's full completion before deciding whether a
247 // stale-resume retry was confirmed — codex P1/P2 on PR #2360
248 // (second review pass): `child.wait()` resolving is NOT proof this
249 // task has already seen and reacted to a "No conversation found"
250 // line, or finished its OWN subsequent `persist_session_id("")`
251 // call (`stderr_reader.rs`). See the process-waiter's own comment
252 // (`process_waiter.rs`) for the two
253 // failure modes this closes.
254 let stderr_reader_handle: Option<tokio::task::JoinHandle<()>> = stderr.map(|stderr_pipe| {
255 let block_id_stderr = self.block_id.clone();
256 let inner_stderr = Arc::clone(&self.inner);
257 let mstore_stderr = self.mstore.clone();
258 let event_bus_stderr = self.event_bus.clone();
259 let attempted_resume_sid = attempted_resume_sid.clone();
260 let my_generation_stderr = my_generation;
261 tokio::spawn(Self::run_stderr_reader(StderrReaderCtx {
262 stderr_pipe,
263 block_id_stderr,
264 inner_stderr,
265 mstore_stderr,
266 event_bus_stderr,
267 attempted_resume_sid,
268 my_generation_stderr,
269 }))
270 });
271 Ok(Pipes {
272 stdin,
273 stdout,
274 kill_tx,
275 kill_rx,
276 stderr_reader_handle,
277 })
278 }
279
280 /// Records the running process in the controller's state; returns the stdin writer's channel.
281 pub(super) fn mark_running(
282 &self,
283 launch: &mut Launch,
284 kill_tx: tokio::sync::oneshot::Sender<KillRequest>,
285 ) -> mpsc::Receiver<String> {
286 let pid = launch.pid;
287 let spawn_args = &launch.spawn_args;
288 let agent_lease = &launch.agent_lease;
289 // Create stdin writer channel
290 let (msg_tx, msg_rx) = mpsc::channel::<String>(32);
291
292 {
293 let mut inner = self.inner.lock().unwrap();
294 inner.current_pid = Some(pid);
295 crate::backend::cli_native::pids::set(&self.block_id, pid);
296 // Its first turn may now take a while: whoever waits on this identity's refresh waits for it.
297 crate::identity::token_warmup::started(&self.block_id);
298 inner.kill_tx = Some(kill_tx);
299 inner.stdin_tx = Some(msg_tx);
300 // The same `Arc` when an earlier generation's lease was reused
301 // (see `acquire_agent_lease`), so no release happens here.
302 inner.agent_lease = agent_lease.clone();
303 Self::set_status(&mut inner, STATUS_RUNNING);
304 inner.spawn_runtime = Some(crate::backend::agent_runtime::spawn_runtime_from_args(
305 spawn_args,
306 ));
307 inner.effective_runtime = None;
308 // A reply from before this start, from another model, says nothing about the model it runs.
309 if let Some(model) = inner.spawn_runtime.as_ref().and_then(|rt| rt.model.as_deref()) {
310 crate::backend::context_reading::drop_model_other_than(&self.block_id, model);
311 }
312 // Ask the CLI what it is really using as soon as it is up: the argv
313 // carries an alias, the CLI resolves it. Only a control-protocol
314 // process reads such requests from stdin. An answer is folded into
315 // the `agentruntime` event (the stdout reader, `stdout_reader.rs`).
316 inner.settings_readback = spawn_args.iter().any(|a| a == "--permission-prompt-tool");
317 inner.context_usage = None;
318 if inner.settings_readback {
319 if let Some(tx) = inner.stdin_tx.as_ref() {
320 let _ = tx.try_send(crate::backend::agent_runtime::settings_request_line());
321 // And where it will auto-compact (agent_context_usage.rs),
322 // answered before the first message too.
323 let _ = tx.try_send(
324 crate::backend::agent_context_usage::context_usage_request_line(),
325 );
326 }
327 }
328 }
329 // Now visible to `session_held_elsewhere` — a concurrent resume of
330 // the same session may run its check.
331 drop(launch.resume_claim.take());
332 self.health_monitor.note_spawned();
333 self.publish_status();
334 msg_rx
335 }
336
337 /// Registers the spawn with the muxbus and records its segment of the conversation.
338 pub(super) fn register_spawn(
339 &self,
340 config: &PersistentSpawnConfig,
341 launch: &Launch,
342 ) -> Registered {
343 let attempted_resume_sid = &launch.attempted_resume_sid;
344 let forked = launch.forked;
345 let relocated_copy = &launch.relocated_copy;
346 let continuation = &launch.continuation;
347 let agent_lease = &launch.agent_lease;
348 let my_registration_nonce = launch.my_registration_nonce;
349 // Auto-register with the muxbus reactive handler so inter-agent
350 // messages reach this persistent (no-PTY) agent. The PTY shell
351 // controller (shell.rs) was the only prior auto-register path, so
352 // stream-json agents were in the directory but absent from the
353 // delivery registry — `inject_message` returned "agent not found"
354 // (issue #1470). Tier-1 delivery is routed through the controller-
355 // aware MessageSender (→ send_user_message), not PTY keystrokes.
356 // See SPEC_MUXBUS_AGENT_DISCOVERY_AND_PERSISTENT_DELIVERY_2026_06_16.
357 let agent_id_for_muxbus = muxbus_agent_id_from_env(&config.env_vars);
358 *self.agent_id.lock().unwrap() = agent_id_for_muxbus.clone();
359 // Write-once: unlike `agent_id` above (refreshed every turn by
360 // `input.rs`'s Register-tail), `stable_agent_id` is only ever set
361 // here, at spawn, and never touched again — see its field doc
362 // comment. `spawn_process` can in principle run again for the same
363 // controller on a respawn; re-writing the SAME env-derived value
364 // each time is harmless (idempotent), and a respawn with genuinely
365 // different env (rare, config change) correctly updates the alias
366 // to match, same as the primary registration already does.
367 *self.stable_agent_id.lock().unwrap() = agent_id_for_muxbus.clone();
368 // Identity M2: the UID carried in the spawn env (M1a). Captured with
369 // the same write-once discipline as `stable_agent_id`; `None` when
370 // the env carried none (no `db_agents` row at spawn — a continuation
371 // launch eager-resumes before the frontend creates the row, spec
372 // §4.4.4 Q1 — or a quick-launch pane), in which case this spawn
373 // registers name-only and the first turn's Register-tail upgrades
374 // the block in place.
375 let agent_uid_for_registry = config
376 .env_vars
377 .get("AGENTMUX_AGENT_UID")
378 .map(|u| u.trim().to_string())
379 .filter(|u| !u.is_empty());
380 *self.stable_agent_uid.lock().unwrap() = agent_uid_for_registry.clone();
381 // This process is one segment of the agent's conversation
382 // (SPEC_DURABLE_CONVERSATION_MEMORY_2026_09_23.md §4.1, P1). The
383 // stdout reader records its provider session id, the waiter its end.
384 let segment: super::segments::SegmentRef =
385 agent_uid_for_registry.as_deref().and_then(|uid| {
386 self.record_segment_start(
387 uid,
388 config,
389 attempted_resume_sid.as_deref(),
390 attempted_resume_sid.as_deref().filter(|_| forked),
391 relocated_copy.is_some(),
392 continuation.is_some(),
393 agent_lease.as_ref().map(|l| l.epoch()),
394 )
395 });
396 *self.current_segment.lock().unwrap() = segment.as_ref().map(|(_, id)| id.clone());
397 let segment_read = segment.clone();
398 let segment_wait = segment;
399 // A relocated resume's copy, removed once the fork reports its id.
400 let relocated_copy_read = relocated_copy.clone();
401 let forked_from_read = attempted_resume_sid.clone().filter(|_| forked);
402 let exit_cleanup_nonce = self.register_with_muxbus(
403 &agent_id_for_muxbus,
404 &agent_uid_for_registry,
405 my_registration_nonce,
406 );
407 Registered {
408 agent_id_for_muxbus,
409 segment_read,
410 segment_wait,
411 relocated_copy_read,
412 forked_from_read,
413 exit_cleanup_nonce,
414 }
415 }
416
417 /// Records the pid for crash recovery and starts the stdin writer; returns the prompts it will send.
418 pub(super) fn start_stdin_writer(
419 &self,
420 launch: &mut Launch,
421 stdin: tokio::process::ChildStdin,
422 msg_rx: mpsc::Receiver<String>,
423 ) -> crate::backend::cli_native::sent::SentPrompts {
424 let pid = launch.pid;
425 // Record active pid for crash recovery (Phase 4.2). If the server
426 // dies while this subprocess is running, scan_orphans() will find
427 // the stale pid on next boot and flag the session as interrupted.
428 if let Some(ref mstore) = self.mstore {
429 super::super::session_recovery::mark_active_pid(mstore, &self.block_id, pid);
430 }
431
432 // The user turns the stdin writer sends, by uuid: the CLI echoes them back (`cli_native::sent`).
433 let sent_prompts = crate::backend::cli_native::sent::SentPrompts::default();
434 Self::spawn_stdin_writer(
435 stdin,
436 msg_rx,
437 launch.continuation.take(),
438 sent_prompts.clone(),
439 );
440 sent_prompts
441 }
442
443 /// A new process starts its own provider-reported spend total, as the
444 /// harness's own `total_cost_usd` starts again with it (#30143). Called
445 /// before the reader task exists, so a response settling first cannot land
446 /// in the previous process's total.
447 fn reset_route_cost_session(&self) {
448 if let Some(mstore) = self.mstore.as_deref() {
449 if let Some(agent) = crate::identity::resolver::block_agent_id(mstore, &self.block_id) {
450 crate::backend::model_gateway::spend::reset_session(&agent);
451 }
452 }
453 }
454
455 /// Starts the stdout reader task.
456 pub(super) fn spawn_stdout_reader(
457 &self,
458 stdout: tokio::process::ChildStdout,
459 config: &PersistentSpawnConfig,
460 launch: &Launch,
461 registered: &Registered,
462 sent_prompts: crate::backend::cli_native::sent::SentPrompts,
463 ) -> StdoutTask {
464 let my_generation = launch.my_generation;
465 let my_registration_nonce = launch.my_registration_nonce;
466 let agent_lease = &launch.agent_lease;
467 let segment_read = registered.segment_read.clone();
468 let relocated_copy_read = registered.relocated_copy_read.clone();
469 let forked_from_read = registered.forked_from_read.clone();
470 // Spawn stdout reader task
471 let block_id_read = self.block_id.clone();
472 let broker_read = self.broker.clone();
473 let inner_read = Arc::clone(&self.inner);
474 let mstore_read = self.mstore.clone();
475 let event_bus_read = self.event_bus.clone();
476 let filestore_read = self.filestore.clone();
477 let health_read = Arc::clone(&self.health_monitor);
478 // Weak, like every other self-reference here: the reader task must not
479 // keep the controller alive. Used only for the deferred
480 // runtime-config restart at turn end (`request_restart_when_idle`).
481 let self_ref_read = self.self_ref.lock().unwrap().clone();
482 let stdout_seq_read = Arc::clone(&self.stdout_seq);
483 let session_id_field = config.session_id_field.clone();
484 let my_generation_read = my_generation;
485 // Resolve the agent's GLOBAL transcript zone (`agent:<defId>:current`)
486 // once, from the block's `agentId` meta, so every `output` line is also
487 // mirrored to the cross-channel store. `None` for non-agent blocks.
488 let global_output_zone = crate::backend::transcript::append::resolve_global_output_zone(
489 &self.mstore,
490 &self.block_id,
491 );
492 // Cloned before `global_output_zone` moves into the stdout-reader
493 // task below — the process-waiter task (spawned in `spawn_waiter`) needs
494 // its own copy for the segment-end record and to append the resume
495 // state machine's exit-time lines (a held-back error-result line, a
496 // session-outcome event).
497 let global_output_zone_wait = global_output_zone.clone();
498 // Writer-side fence on that shared record
499 // (SPEC_AGENT_SINGLE_LIVE_INSTANCE_2026_09_24 Phase 3): once this
500 // process has lost the agent's lease, its output still reaches this
501 // pane's own log but no longer the agent's record. `None` when no
502 // lease is held (no store, or no UID) — nothing to fence.
503 let record_fence = agent_lease.as_ref().map(|l| l.record_fence());
504 let record_fence_wait = record_fence.clone();
505
506 // codex P1 on PR #2371: the JoinHandle is kept (not discarded) so the
507 // process-waiter task can await this task's full completion before
508 // resolving the retry decision, mirroring `stderr_reader_handle`
509 // (started in `take_pipes`). `child.wait()` resolving is NOT proof this task has already
510 // read and held back the doomed attempt's terminal error-result line
511 // (`ResumeState`'s `held_error_line`) — without this wait, the
512 // waiter could resolve the resume state (`ProcessExited`) and launch
513 // the retry first, after which this (now-lagging) reader would find
514 // the state already `NotTracking` and persist the error line
515 // immediately, reproducing the exact bubble this PR exists to
516 // suppress.
517 let model_api = core::attach_model_api(
518 &self.block_id,
519 &config.env_vars,
520 &self.mstore,
521 &self.event_bus,
522 )
523 .unwrap_or(crate::connectivity::Service::ModelApi(
524 &crate::connectivity::ANTHROPIC,
525 ));
526 self.reset_route_cost_session();
527 let stdout_reader_handle: tokio::task::JoinHandle<()> =
528 tokio::spawn(Self::run_stdout_reader(StdoutReaderCtx {
529 stdout,
530 block_id_read,
531 broker_read,
532 inner_read,
533 mstore_read,
534 event_bus_read,
535 filestore_read,
536 health_read,
537 self_ref_read,
538 stdout_seq_read,
539 session_id_field,
540 my_generation_read,
541 mcp_owner_read: my_registration_nonce,
542 global_output_zone,
543 record_fence,
544 segment_read,
545 relocated_copy_read,
546 forked_from_read,
547 sent_prompts,
548 model_api,
549 }));
550 StdoutTask {
551 handle: stdout_reader_handle,
552 global_output_zone_wait,
553 record_fence_wait,
554 }
555 }
556
557 /// Starts the process waiter task, which owns the child from here on.
558 pub(super) fn spawn_waiter(
559 &self,
560 launch: Launch,
561 kill_rx: tokio::sync::oneshot::Receiver<KillRequest>,
562 stderr_reader_handle: Option<tokio::task::JoinHandle<()>>,
563 stdout: StdoutTask,
564 registered: &Registered,
565 ) {
566 let Launch {
567 child,
568 pid,
569 my_generation,
570 my_registration_nonce,
571 ..
572 } = launch;
573 let stdout_reader_handle = stdout.handle;
574 let global_output_zone_wait = stdout.global_output_zone_wait;
575 let record_fence_wait = stdout.record_fence_wait;
576 let segment_wait = registered.segment_wait.clone();
577 let agent_id_for_muxbus = ®istered.agent_id_for_muxbus;
578 let exit_cleanup_nonce = registered.exit_cleanup_nonce;
579 // Spawn process waiter task
580 let block_id_wait = self.block_id.clone();
581 let inner_wait = Arc::clone(&self.inner);
582 let broker_wait = self.broker.clone();
583 let mstore_wait = self.mstore.clone();
584 // Needed to persist a classified failure (rate-limit/overloaded/etc.)
585 // into block meta alongside the MPS publish below — mirrors
586 // `event_bus_read`'s equivalent clone for the stdout-reader task.
587 let event_bus_wait = self.event_bus.clone();
588 let health_wait = Arc::clone(&self.health_monitor);
589 // Needed to append the resume state machine's exit-time lines: a
590 // held-back error-result line when the stale-resume retry is NOT
591 // confirmed (or is overridden by an explicit stop), and the
592 // session-outcome event — see the exit-handler's own comment in
593 // `process_waiter.rs`.
594 let filestore_wait = self.filestore.clone();
595 // Captured so the waiter can deregister this agent from muxbus on exit.
596 let agent_id_wait = agent_id_for_muxbus.clone();
597 // See `set_self_ref` / `retry_after_resume_failure` — lets this
598 // detached task call back into an instance method once the process
599 // actually exits, to transparently retry a stale-`--resume` failure.
600 let self_ref_wait = self.self_ref.lock().unwrap().clone().unwrap_or_default();
601 // This exact spawn's identity — every resume event below carries it,
602 // and `persistent_resume::update()` ignores one whose generation
603 // isn't the tracked one (see that module's doc comment).
604 let my_generation_wait = my_generation;
605 // This exact spawn's OS pid, for the compare-and-clear below — the
606 // unconditional clear could wipe a fallback respawn's fresh
607 // registration (issue #2363, see clear_active_pid_if_pid).
608 let pid_wait = pid;
609 // This spawn's registration identity, for the guarded
610 // muxbus/registry removals below (issue #2363 / codex P1 on PR
611 // #2500 — see `my_registration_nonce`'s own doc comment). NOT
612 // `my_registration_nonce` directly — `exit_cleanup_nonce` is that
613 // same value UNLESS registration was skipped (`register_with_muxbus`), in which case
614 // it's whatever nonce actually ended up on record instead (reagent
615 // P1 on PR #3084; see the skip arm's own comment for why using our
616 // own never-written nonce here would leak the registration).
617 let nonce_wait = exit_cleanup_nonce;
618
619 tokio::spawn(Self::run_process_waiter(ProcessWaiterCtx {
620 child,
621 kill_rx,
622 stderr_reader_handle,
623 stdout_reader_handle,
624 segment_wait,
625 global_output_zone_wait,
626 record_fence_wait,
627 block_id_wait,
628 inner_wait,
629 broker_wait,
630 mstore_wait,
631 event_bus_wait,
632 health_wait,
633 filestore_wait,
634 agent_id_wait,
635 self_ref_wait,
636 my_generation_wait,
637 pid_wait,
638 nonce_wait,
639 mcp_owner_wait: my_registration_nonce,
640 }));
641 }
642}