Skip to main content

agentmux_srv/server/agent_handlers/
turn_steps.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The steps of `run_agent_turn_joining` (input.rs), one function each, in the order it runs them. Moved from it unchanged.
5
6use std::collections::HashMap;
7use std::sync::Arc;
8
9use crate::backend::blockcontroller;
10use crate::backend::message_origin::{MessageOrigin, RecordOrigin};
11use crate::backend::obj::Block;
12use crate::backend::rpc_types::AttachmentRef;
13use crate::backend::runtime_adapter::{RuntimeAdapter, RuntimeKind};
14use crate::backend::spawn_env::build::build_persistent_spawn_env;
15
16use super::input::{AgentTurnDeps, ArmedJoinHint, TurnGate};
17
18/// What a pane's meta says to run.
19pub(super) struct SpawnBase {
20    pub cli_command: String,
21    pub cli_args: Vec<String>,
22    pub working_dir: String,
23}
24
25/// One turn, ready to hand to the controller that will run it.
26pub(super) struct Turn<'a> {
27    pub deps: &'a AgentTurnDeps,
28    pub block: &'a Block,
29    pub block_id: &'a str,
30    pub base: SpawnBase,
31    pub env_vars: HashMap<String, String>,
32    pub session_id_field: String,
33    pub message: String,
34    pub message_id: Option<String>,
35    pub from: MessageOrigin,
36    pub joins_turn: Option<u64>,
37    pub record: RecordOrigin,
38    pub inline_images: Vec<serde_json::Value>,
39    /// The send-copies of the message's pictures, by path, for a provider that takes a picture that way.
40    pub image_paths: Vec<String>,
41}
42
43/// Re-read the spawn config from block metadata.
44pub(super) fn spawn_base(block: &Block) -> SpawnBase {
45    let cli_command = crate::backend::obj::meta_get_string(&block.meta, "cmd", "claude");
46    let cli_args: Vec<String> = match block.meta.get("cmd:args") {
47        Some(serde_json::Value::Array(arr)) => arr
48            .iter()
49            .filter_map(|v| v.as_str().map(|s| s.to_string()))
50            .collect(),
51        _ => vec![
52            "-p".to_string(),
53            "--input-format".to_string(),
54            "stream-json".to_string(),
55            "--output-format".to_string(),
56            "stream-json".to_string(),
57        ],
58    };
59    // A pane stored without --model/--effort (saved before the launch fixes, or
60    // written by a path that forgot) would spawn on the CLI default; fill what
61    // its `agent:runtime` says. Never overrides a flag already there.
62    // A container agent's turns are one-shot and read `cmd:args` again each time; its runtime picker records the
63    // choice in `agent:runtime` alone, so the model and effort stored at launch must not outrank it.
64    let cli_args = if crate::backend::runtime_adapter::RuntimeKind::of_block_meta(&block.meta).is_container() {
65        crate::backend::agent_runtime::runtime_over_stale_flags(&block.meta, cli_args)
66    } else {
67        cli_args
68    };
69    let cli_args = crate::backend::agent_runtime::with_runtime_flags(&block.meta, cli_args);
70    let working_dir = crate::backend::obj::meta_get_string(&block.meta, "cmd:cwd", "");
71    SpawnBase { cli_command, cli_args, working_dir }
72}
73
74/// The spawn environment, after the single-live-instance check and the identity gate.
75pub(super) async fn gated_spawn_env(
76    deps: &AgentTurnDeps,
77    ctrl: &Arc<dyn blockcontroller::Controller>,
78    block: &Block,
79    block_id: &str,
80    env_vars: HashMap<String, String>,
81) -> Result<HashMap<String, String>, TurnGate> {
82    let AgentTurnDeps { mstore, id_store, identity_store, auth_key, broker, .. } = deps.clone();
83    // First, before anything is written for the spawn: a harness other than Claude Code is not started on
84    // the host in a folder a container agent can write. Asked off the async workers (it reads the disk).
85    let meta = block.meta.clone();
86    let refusal = tokio::task::spawn_blocking(move || crate::backend::mcp_folder_rule::turn_refusal(&meta)).await.unwrap_or_else(|_| Some(crate::backend::mcp_folder_rule::TURN_REFUSAL.to_string()));
87    if let Some(why) = refusal {
88        return Err(TurnGate::Folder(why));
89    }
90    crate::server::mcp_folder_notice::tell(&broker, &deps.filestore_gate, &mstore, block).await;
91    // Identity gate, MuxBus token, reserved wrapper vars, agent identity,
92    // git identity, tools PATH — see `build_persistent_spawn_env`'s own doc
93    // comment. Broker hand-in lets the identity resolver publish
94    // `identity:no-direct-links`, and its OAuth expiry probe
95    // `identityaccounts:changed` when it flips a token's status.
96    //
97    // Before all of that — the env build writes shared identity state — a
98    // persistent pane about to spawn checks that no other AgentMux instance
99    // on this host runs this agent (SPEC_AGENT_SINGLE_LIVE_INSTANCE_2026_09_24
100    // Phase 1, I9). A refusal is returned as a `TurnGate`, which the caller
101    // persists and shows in the pane like any other spawn refusal.
102    let admission = match ctrl
103        .as_any()
104        .downcast_ref::<blockcontroller::persistent::PersistentSubprocessController>()
105    {
106        Some(p) if p.needs_spawn() => {
107            let uid = crate::backend::obj::meta_get_string(&block.meta, "agentId", "");
108            let name = crate::backend::obj::meta_get_string(&block.meta, "agentName", "");
109            p.check_admission(&uid, &name).await
110        }
111        // Another provider's controller (ACP, App Server, a plain subprocess) has no lease path of its own, so the
112        // hand-over mark is checked here, for every turn it would start.
113        Some(_) => Ok(()),
114        None => {
115            let uid = crate::backend::obj::meta_get_string(&block.meta, "agentId", "");
116            let name = crate::backend::obj::meta_get_string(&block.meta, "agentName", "");
117            match crate::backend::agent_admission::handed_over_check(&mstore, &uid, &name) {
118                Some(refusal) => Err(refusal),
119                None => Ok(()),
120            }
121        }
122    };
123    let env_result = match admission {
124        Err(refusal) => Err(TurnGate::Admission(refusal)),
125        Ok(()) => build_persistent_spawn_env(
126            mstore.clone(),
127            id_store.clone(),
128            identity_store.clone(),
129            Some(broker.clone()),
130            &block.meta,
131            &block_id,
132            &auth_key,
133            env_vars,
134        )
135        .await
136        .map_err(TurnGate::Identity),
137    };
138    env_result
139}
140
141/// Show a refusal that happened before any process ran in the pane: the raw frame in the output log, plus the
142/// classified failure the recovery row reads.
143pub(super) fn surface_refusal(deps: &AgentTurnDeps, block_id: &str, message: &str) {
144    let AgentTurnDeps { mstore, broker, filestore_gate, event_bus_gate, .. } = deps.clone();
145    let error_frame = serde_json::json!({
146        "type": "result",
147        "is_error": true,
148        "subtype": "error_during_execution",
149        "error": {"message": format!("[AgentMux] {message}")}
150    })
151    .to_string();
152    // Some(&filestore_gate): the frame must be PERSISTED
153    // to the block file, not just live-broadcast —
154    // otherwise the error vanishes on pane
155    // reload/reconnect (reagent P1, PR #2164 round 2). And to
156    // the agent's global zone: a pane with an agentId reads
157    // that on reload, so without it the frame still vanished
158    // (Phase 5a-3c).
159    // A pane bound with Open here is refused once and answers it with Move here: that refusal is
160    // left out of its history (open_here_mark.rs) and reaches the recovery row below all the same.
161    if !crate::backend::open_here_mark::expected_for_block(&mstore, block_id, message) {
162        let global_zone = crate::backend::transcript::append::resolve_global_output_zone(
163            &Some(mstore.clone()),
164            &block_id,
165        );
166        crate::backend::blockcontroller::shell::handle_append_block_file(
167            &broker,
168            &block_id,
169            crate::backend::blockcontroller::subprocess::SUBPROCESS_OUTPUT_SUBJECT,
170            format!("{error_frame}\n").as_bytes(),
171            Some(&filestore_gate),
172            global_zone.as_deref(),
173        );
174    }
175    // codex P1, PR #2802: the frame above only lands in
176    // the block's raw output log, which the recovery
177    // banner does NOT read from — it reads the
178    // structured `agent:last_failure` block-meta key
179    // (persist_last_failure) + the ephemeral
180    // EVENT_AGENT_FAILURE push, same as every POST-spawn
181    // exit classification (host_spawn.rs). No process
182    // ever ran here, so classify() gets no exit
183    // code/stderr/result-frame — just the gate's own
184    // Display text, exactly like health.rs's in-band-error
185    // reclassification call.
186    let gate_failure =
187        crate::agents::failure::classify(None, None, message, None);
188    crate::backend::blockcontroller::core::persist_last_failure(
189        &block_id,
190        Some(&gate_failure),
191        &Some(mstore.clone()),
192        &Some(event_bus_gate.clone()),
193    );
194    broker.publish_event::<crate::backend::mps_events::AgentFailed>(&gate_failure, vec![format!("block:{}", block_id)], 1);
195}
196
197/// The attachments of a message: a numbered list appended to the text, and the inline images for a persistent Claude.
198pub(super) async fn prepare_attachments(
199    deps: &AgentTurnDeps,
200    ctrl: &Arc<dyn blockcontroller::Controller>,
201    block: &Block,
202    block_id: &str,
203    message: String,
204    attachments: Vec<AttachmentRef>,
205) -> Result<(String, Vec<serde_json::Value>, Vec<String>), String> {
206    // Attachments (SPEC_AGENT_PANE_IMAGE_ATTACHMENTS_2026_09_26.md §6.6,
207    // SPEC_AGENT_PANE_FILE_ATTACHMENTS_2026_09_26.md §7): every provider gets
208    // a numbered list of the files appended to the text; Claude's persistent
209    // stream-json path also gets images and short PDFs inline. A container
210    // agent can't reach a host path, so its copies are rehomed into the
211    // pane's working folder (the host side of its workspace bind mount,
212    // narko #198 piece 2) and the list points there instead.
213    let mut inline_images: Vec<serde_json::Value> = Vec::new();
214    let mut image_paths: Vec<String> = Vec::new();
215    let message = if attachments.is_empty() {
216        message
217    } else {
218        // Refusals go through surface_refusal like every other early exit
219        // here, so the reason survives a pane reload.
220        let container_cwd = match attachment_destination(block) {
221            Ok(cwd) => cwd,
222            Err(msg) => {
223                surface_refusal(deps, block_id, msg);
224                return Err(msg.to_string());
225            }
226        };
227        let Some(svc) = crate::backend::attachments::get() else {
228            let msg = "Image attachments are unavailable: the attachment service isn't running.";
229            surface_refusal(deps, block_id, msg);
230            return Err(msg.to_string());
231        };
232        let is_persistent = ctrl
233            .as_any()
234            .downcast_ref::<blockcontroller::persistent::PersistentSubprocessController>()
235            .is_some();
236        let limits = svc.limits();
237        let inline_max = if is_persistent { limits.claude_inline_max } else { 0 };
238        // Claude Code keeps every inline image in its own session transcript,
239        // so inline bytes are budgeted per session too (spec §6.6). A new
240        // session has no id yet; its first turn counts against the block.
241        // Once the id is known, that first turn's count moves to the session.
242        let sid = crate::backend::obj::meta_get_string(&block.meta, "agent:sessionid", "");
243        let new_session_key = format!("block:{block_id}:new");
244        let session_key = if sid.is_empty() { new_session_key.clone() } else { format!("session:{sid}") };
245        // Re-derive any send-copy whose fingerprint is stale (a changed send
246        // edge) under the service's CPU and memory limits, before the
247        // blocking resolve below looks the files up.
248        // The person is sending these in their own message, so a file stored unread is opened now.
249        for a in &attachments {
250            svc.open_derived(&a.id).await;
251        }
252        let by_path = ctrl.as_any().downcast_ref::<blockcontroller::app_server_controller::AppServerController>().is_some();
253        let (prepared, pictures) = tokio::task::spawn_blocking(move || {
254            use crate::backend::attachments::prompt;
255            let (found, missing) = prompt::resolve(&svc, &attachments);
256            let (found, missing) = match &container_cwd {
257                Some(cwd) => rehome_for_container(found, missing, cwd),
258                None => (found, missing),
259            };
260            let pictures = if by_path { prompt::image_paths(&found) } else { Vec::new() };
261            // Read, spend and record the session budget as one locked step.
262            let prepared = svc.with_session_inline_budget(
263                &session_key,
264                Some(&new_session_key),
265                limits.claude_session_inline_bytes,
266                |budget| {
267                    let prepared = prompt::prepare(&found, &missing, inline_max, budget);
268                    let spent = prompt::inline_bytes(&prepared.inline);
269                    (prepared, spent)
270                },
271            );
272            (prepared, pictures)
273        })
274        .await
275        .map_err(|e| format!("attachments: {e}"))?;
276        inline_images = prepared.inline;
277        image_paths = pictures;
278        crate::backend::attachments::prompt::append(&message, &prepared.list)
279    };
280    Ok((message, inline_images, image_paths))
281}
282
283/// Where this turn's attachments land, or why they can't: `Ok(None)` for a host agent (nothing to
284/// rehome — the host path already means something to it); `Ok(Some(cwd))` for a container agent with a
285/// working folder to copy into; `Err` for a runtime that refuses attachments and isn't a container (none
286/// does today; kept so a future one still refuses cleanly), or a container with no working folder yet.
287pub(crate) fn attachment_destination(block: &Block) -> Result<Option<String>, &'static str> {
288    let runtime = RuntimeKind::of_block_meta(&block.meta);
289    if !runtime.adapter().accepts_attachments() && !runtime.is_container() {
290        return Err("Attachments aren't supported for this agent yet.");
291    }
292    if !runtime.is_container() {
293        return Ok(None);
294    }
295    // A container's workspace bind mount is this turn's `cmd:cwd`, host side (`ContainerMountSpec::for_agent`,
296    // container/mounts.rs): with none set yet there is nowhere on the host to put the copies. Expanded
297    // the same way `ContainerMountSpec::for_agent` expands it before binding it as `/workspace`
298    // (mounts.rs:50) — a `~/...` cwd (what `agent.open` records for an agent with no workspace of its
299    // own) must resolve to the exact folder Docker mounted, or the copy lands somewhere nothing reads it
300    // from and the list points at a container path that was never written.
301    let cwd = crate::backend::obj::meta_get_string(&block.meta, "cmd:cwd", "");
302    let cwd = cwd.trim();
303    if cwd.is_empty() {
304        return Err("Attachments need a working folder, and this agent's pane has none yet.");
305    }
306    Ok(Some(crate::backend::base::expand_home_dir_safe(cwd).to_string_lossy().into_owned()))
307}
308
309/// The subfolder, under a container's working folder, that rehomed attachments live in.
310const CONTAINER_ATTACHMENTS_SUBDIR: &str = ".agentmux-attachments";
311
312/// Copy each resolved attachment's send-copy from its host path into `host_cwd` (the pane's working
313/// folder) and point it at the container-side path instead (narko #198 piece 2): a container agent can
314/// open a file under its workspace mount, never a bare host path. The copy keeps the exact trailing path
315/// [`id_bearing_suffix`] finds — `<sha256>.…` for an image/derived file, `named/<sha256>/<realname>` for
316/// any other kind — the same two shapes the composer's reload parser (`ID_RE`, `attached-images.ts`) and
317/// the image counter (`images_in_text`, `transcript/images.rs`) already recognize (#7434): renaming to
318/// the display name instead would make every container attachment unrecognizable to both on reload. A
319/// path with neither shape, or a copy that fails, joins `missing`, the same treatment a send-copy swept
320/// by retention gets.
321///
322/// The write goes through [`crate::backend::workdir_fs::Workdir`], the same primitive every other write
323/// into an agent's working directory uses: a container agent has read-write access to this whole tree
324/// through its bind mount, so the destination needs the same defenses a native agent's own workdir
325/// already gets against a symlinked ancestor folder or a symlinked destination file, not a hand-rolled
326/// check here that has to rediscover them (#7434).
327///
328/// A document's extracted-text companion (`item.note`'s `text version: <path>`, from PDFs and Office
329/// files) is rehomed the same way and the note rewritten to the container path: a container agent
330/// could open the one file this leaves pointed at a host path but not the other (#7434). If the
331/// companion can't be rehomed, that part of the note is dropped rather than leaving a host path the
332/// container never gets.
333pub(crate) fn rehome_for_container(
334    found: Vec<crate::backend::attachments::prompt::Resolved>,
335    mut missing: Vec<String>,
336    host_cwd: &str,
337) -> (Vec<crate::backend::attachments::prompt::Resolved>, Vec<String>) {
338    use crate::backend::runtime_adapter::MountRole;
339    let container_root = RuntimeKind::Container.adapter().map_mount(MountRole::Workspace, host_cwd);
340    let workdir = crate::backend::workdir_fs::Workdir::open(std::path::Path::new(host_cwd));
341    let mut rehomed = Vec::with_capacity(found.len());
342    for mut item in found {
343        let Some(container_path) = rehome_one(&workdir, &container_root, &item.path) else {
344            missing.push(item.name);
345            continue;
346        };
347        item.path = std::path::PathBuf::from(container_path);
348        item.note = item.note.map(|note| rehome_text_companion(&note, &workdir, &container_root));
349        rehomed.push(item);
350    }
351    (rehomed, missing)
352}
353
354/// Copies `host_path`'s send-copy into `host_cwd`'s `CONTAINER_ATTACHMENTS_SUBDIR`, keeping the exact
355/// id-bearing suffix [`id_bearing_suffix`] finds, and returns the container-side path string. `None`
356/// when `host_path` carries no recognizable id, or the copy fails — logged either way, so a caller
357/// that only has a name to report (`missing`) still has the reason in the log.
358fn rehome_one(workdir: &std::io::Result<crate::backend::workdir_fs::Workdir>, container_root: &str, host_path: &std::path::Path) -> Option<String> {
359    let Some(suffix) = id_bearing_suffix(host_path) else {
360        tracing::warn!(path = %host_path.display(), "container attachment: its host path carries no recognizable id");
361        return None;
362    };
363    let rel = format!("{CONTAINER_ATTACHMENTS_SUBDIR}/{}", suffix.to_string_lossy().replace('\\', "/"));
364    let copied: std::io::Result<()> = (|| {
365        let wd = workdir.as_ref().map_err(|e| std::io::Error::new(e.kind(), e.to_string()))?;
366        let bytes = std::fs::read(host_path)?;
367        wd.write(&rel, &bytes, false)
368    })();
369    match copied {
370        Ok(()) => Some(format!("{container_root}/{rel}")),
371        Err(e) => {
372            tracing::warn!(path = %host_path.display(), error = %e, "container attachment: could not copy into the pane's working folder");
373            None
374        }
375    }
376}
377
378/// Rewrites a `text version: <path>` segment of a document's note to the container-side path
379/// [`rehome_one`] copied it to, keeping the rest of the note (page count, "contains macros") as is.
380/// Drops just that segment, rather than leaving a host path, when the companion carries no
381/// recognizable id or its copy fails. Matches only a segment that STARTS WITH the marker, never a
382/// bare substring: `file_note`'s failure note reads "no text version: {e}", which contains "text
383/// version: " too but names no path to rehome — matching that would delete the error text instead
384/// (#2586). A note with neither segment shape (an image's note is always `None`) is unchanged.
385fn rehome_text_companion(note: &str, workdir: &std::io::Result<crate::backend::workdir_fs::Workdir>, container_root: &str) -> String {
386    const MARKER: &str = "text version: ";
387    note.split("; ")
388        .filter_map(|segment| match segment.strip_prefix(MARKER) {
389            Some(path_str) => rehome_one(workdir, container_root, std::path::Path::new(path_str)).map(|p| format!("{MARKER}{p}")),
390            None => Some(segment.to_string()),
391        })
392        .collect::<Vec<_>>()
393        .join("; ")
394}
395
396/// The trailing part of a send-copy's host path that carries its attachment id: `<sha256>.…` for an
397/// image or other derived file (`prompt.rs`'s module doc), or `named/<sha256>/<realname>` for any other
398/// kind. `None` for a path with neither shape — a send-copy always has one, so this only trips on a path
399/// this function doesn't recognize, which must not be guessed at.
400fn id_bearing_suffix(path: &std::path::Path) -> Option<std::path::PathBuf> {
401    let file_name = path.file_name()?;
402    if let Some(hash_dir) = path.parent() {
403        if hash_dir.parent().and_then(|p| p.file_name()).is_some_and(|n| n == "named") {
404            if let Some(hash) = hash_dir.file_name().and_then(|n| n.to_str()).filter(|n| is_sha256_hex(n)) {
405                return Some(std::path::Path::new("named").join(hash).join(file_name));
406            }
407        }
408    }
409    let leading_id = file_name.to_str()?.split('.').next()?;
410    is_sha256_hex(leading_id).then(|| std::path::PathBuf::from(file_name))
411}
412
413fn is_sha256_hex(s: &str) -> bool {
414    s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit())
415}
416
417/// Dispatch to a persistent controller: it starts (or respawns) the CLI and carries the message on its input.
418pub(super) fn dispatch_persistent(turn: Turn<'_>, persistent_ctrl: &blockcontroller::persistent::PersistentSubprocessController) -> Result<(), String> {
419    let Turn { deps, block, block_id, base, env_vars, session_id_field, message, message_id, from, joins_turn, record, inline_images, .. } = turn;
420    let SpawnBase { cli_command, cli_args, working_dir } = base;
421    // Container agents use per-turn docker exec — incompatible with a
422    // long-lived persistent subprocess. Fail loudly instead of silently
423    // spawning the CLI on the host.
424    if !RuntimeKind::of_block_meta(&block.meta).adapter().accepts_persistent_controller() {
425        return Err("container agents require a subprocess controller; this provider uses a persistent controller".to_string());
426    }
427    // Resume support: a /model (or effort/permission) change
428    // respawns the persistent CLI with new flags; pass the
429    // resume flag + captured session id so the respawn continues
430    // the same conversation. Same meta keys the subprocess path
431    // reads below. Without this, switching model on a persistent
432    // agent would either no-op (old behavior) or lose context.
433    let resume_flag =
434        crate::backend::obj::meta_get_string(&block.meta, "agent:resume_flag", "--resume");
435    let persisted_session_id =
436        crate::backend::obj::meta_get_string(&block.meta, "agent:sessionid", "");
437    let config = blockcontroller::persistent::PersistentSpawnConfig {
438        cli_command,
439        cli_args,
440        working_dir,
441        env_vars,
442        session_id_field,
443        resume_flag,
444        session_id: persisted_session_id,
445        message_id: message_id.clone(),
446    };
447    let input = crate::backend::blockcontroller::health::TurnInput { from: from.clone(), text: message.clone(), joins_turn };
448    if let Err(e) = persistent_ctrl.send_message_with_images_from(message, inline_images, config, Some(input), record) {
449        // A single-live-instance refusal from inside the controller (the spawn-time claim losing
450        // to another instance or pane, or the pre-turn fence) gets the early check's pane treatment.
451        if crate::backend::agent_admission::is_admission_refusal(&e) || blockcontroller::persistent::is_held_elsewhere_error(&e) {
452            surface_refusal(deps, block_id, &e);
453        }
454        return Err(e);
455    }
456    Ok(())
457}
458
459/// The container runtime a container agent's turn runs in, or the reason there is none. The reason is written to
460/// the pane like every other refusal before a process starts: otherwise the turn returns an error nobody sees and the
461/// pane shows work that never happens.
462async fn runtime_for_turn(deps: &AgentTurnDeps, block_id: &str) -> Result<crate::backend::container::ContainerManager, String> {
463    deps.container_manager.get_or_explain().await.map_err(|reason| {
464        let said = format!("{reason} Start one, or run this agent on this computer instead.");
465        surface_refusal(deps, block_id, &said);
466        said
467    })
468}
469
470/// A pane opened with a harness AgentMux no longer offers runs no more turns: it is told why, in the pane, and nothing starts.
471/// The pane records the provider and the output format it was opened with, so a pane that was running before the harness
472/// was removed (or restored from a layout saved before) is recognised without its agent definition. Every turn path asks
473/// this first: subprocess, persistent, app-server and ACP alike.
474pub(super) fn refuse_retired_harness(deps: &AgentTurnDeps, block_id: &str, meta: &crate::backend::obj::MetaMapType) -> Result<(), String> {
475    let provider = crate::backend::obj::meta_get_string(meta, "agentProvider", "");
476    let format = crate::backend::obj::meta_get_string(meta, "agentOutputFormat", "");
477    let reason = crate::backend::providers::retired_reason(&provider).or_else(|| crate::backend::providers::retired_reason_for_output_format(&format));
478    match reason {
479        Some(why) => {
480            surface_refusal(deps, block_id, why);
481            Err(why.to_string())
482        }
483        None => Ok(()),
484    }
485}
486
487/// Dispatch to a per-turn subprocess controller (a host CLI, or a Docker exec for a container agent).
488pub(super) async fn dispatch_subprocess(
489    turn: Turn<'_>,
490    subprocess_ctrl: &blockcontroller::subprocess::SubprocessController,
491    tracker: Option<Arc<crate::backend::blockcontroller::health::TurnActivityTracker>>,
492) -> Result<(), String> {
493    let Turn { deps, block, block_id, base, mut env_vars, session_id_field, message, message_id, joins_turn, record, .. } = turn;
494    let SpawnBase { cli_command, cli_args, working_dir } = base;
495    let AgentTurnDeps { mstore, container_manager, broker, filestore_gate, .. } = deps.clone();
496    let resume_flag =
497        crate::backend::obj::meta_get_string(&block.meta, "agent:resume_flag", "--resume");
498    let resume_strategy = crate::backend::obj::meta_get_string(
499        &block.meta,
500        "agent:resume_strategy",
501        if session_id_field == "thread_id" {
502            "codex-exec"
503        } else if resume_flag.is_empty() {
504            "none"
505        } else {
506            "flag"
507        },
508    );
509    // A provider that passes its prompt as an argument names the flag here; the others read it from stdin.
510    let prompt_arg_flag =
511        crate::backend::obj::meta_get_string(&block.meta, "agent:prompt_arg_flag", "");
512    // Picker reattach: the frontend writes the prior
513    // block's session id here when launching with
514    // `continueOfInstanceId`. spawn_turn hydrates its
515    // inner.session_id from this on the first turn so
516    // --resume <sid> lands on the very first launch.
517    let persisted_session_id =
518        crate::backend::obj::meta_get_string(&block.meta, "agent:sessionid", "");
519
520    // Container agent: a Docker socket API exec per turn (P1a: no secrets in argv). Host agent:
521    // a regular CLI subprocess. The adapter is the one place the two differ.
522    let adapter: Box<dyn RuntimeAdapter> = match RuntimeKind::of_agent_mode(&crate::backend::obj::meta_get_string(&block.meta, "agentMode", "host")) {
523        RuntimeKind::Host => RuntimeKind::Host.adapter(),
524        RuntimeKind::Container => {
525            let cm = runtime_for_turn(deps, block_id).await?;
526            // Starting the container takes minutes the first time, so it runs in the turn's own task: this
527            // handler is dropped after five seconds. The pre-start builds the same one.
528            let adapter = super::container_turn::container_adapter_for_block(
529                cm,
530                block_id,
531                &block.meta,
532                &mut env_vars,
533                &working_dir,
534                broker.clone(),
535                filestore_gate.clone(),
536                mstore.clone(),
537            );
538            // Env is passed via CreateExecOptions.env (Docker socket API), NOT as -e KEY=VALUE argv
539            // args: this prevents CWE-214 exposure. It is filtered per turn, so cmd:cwd (host path)
540            // and host-path vars never reach the container, and each queued turn uses its own env.
541            Box::new(adapter)
542        }
543    };
544    adapter.materialize(subprocess_ctrl);
545    // Cross-process session-lease key (registry::LeaseStore). Only a host turn enforces it.
546    let instance_id = crate::backend::obj::meta_get_string(&block.meta, "agentId", "");
547    let config = blockcontroller::subprocess::SubprocessSpawnConfig {
548        cli_command,
549        cli_args,
550        working_dir,
551        env_vars,
552        message,
553        resume_flag,
554        resume_strategy,
555        prompt_arg_flag,
556        session_id_field,
557        message_id,
558        session_id: if persisted_session_id.is_empty() { None } else { Some(persisted_session_id) },
559        instance_id,
560        record: Some(record),
561    };
562    let hint = ArmedJoinHint::arm(joins_turn, tracker);
563    adapter.launch(subprocess_ctrl, config)?;
564    hint.keep();
565    Ok(())
566}
567
568/// Register the agent with the cloud subscriber and the reactive handler, so cloud-injected messages reach it.
569pub(super) fn register_turn_agent(block: &Block, block_id: &str, local_web_url: &str, turn_agent_id: Option<&str>, turn_uid: Option<&str>) {
570    // Register with cloud subscriber + reactive handler so cloud-injected
571    // messages (e.g. GitHub PR review notifications) reach this agent.
572    // Uses agentName (the logical display name, e.g. "smike") as the name
573    // binding — matching the namespace used by `handle_reactive_register`
574    // in server/reactive.rs (`req.agent_id`) and the delivery path's
575    // lowercased `name_to_blocks` map — with this turn's UID as the key.
576    // PR bodies embed $AGENTMUX_AGENT_ID, the stable binding (a fork's
577    // `loap-3` under `Loap-3`), so both are subscribed (idempotently).
578    // As its route name for every use below ("Loap #3" → "Loap-3"), or the
579    // controller's own id disagrees with what a jekt resolves to (#2695).
580    let display = crate::backend::obj::meta_get_string(&block.meta, "agentName", "");
581    let agent_name = crate::backend::reactive::sanitize::route_name(&display).unwrap_or_default();
582    if !agent_name.is_empty() {
583        // Identity M2: the display binding is `agentName`, the key is
584        // the UID carried in this turn's spawn env. A block that spawned
585        // before its row existed (continuation eager-resume, spec §4.4.4
586        // Q1) is upgraded in place here on its first turn.
587        let registered = crate::backend::reactive::handler::get_global_handler()
588            .register_agent_full(
589                &agent_name,
590                &block_id,
591                None,
592                0,
593                turn_agent_id,
594                turn_uid,
595                "registration.no_uid.register_tail",
596            );
597        if registered.is_ok() {
598            // Refresh the block's OWN captured identity too
599            // (reagentx P1, round 2 on #2697): this call runs on
600            // EVERY turn, using block.meta["agentName"] as the
601            // source of truth — which can diverge from whatever
602            // a PersistentSubprocessController captured at its
603            // original spawn_process call (rename, reconfigured
604            // cmd:env) without the block ever respawning. Without
605            // this, inject_message_inner's recipient-identity
606            // check (#2695) would compare the current (correct)
607            // target_agent against that stale spawn-time value
608            // and falsely reject the agent's own, correctly-
609            // addressed jekts as an identity mismatch. A no-op
610            // for controller types that don't override
611            // set_agent_id (e.g. SubprocessController).
612            if let Some(ctrl) = crate::backend::blockcontroller::get_controller(block_id) {
613                ctrl.set_agent_id(Some(agent_name.clone()));
614            }
615            if let Some(sub) = crate::muxbus::cloud_subscriber::get_global_subscriber() {
616                let names = crate::backend::reactive::handler::get_global_handler().names_for_block(block_id);
617                names.iter().for_each(|n| sub.add_agent(n));
618            }
619            // Also mirror into the per-channel + host-global
620            // shared file registries — this AgentInput/
621            // SubprocessController path (unlike ShellController/
622            // PersistentSubprocessController) previously only
623            // ever registered in the in-memory Tier-1 map,
624            // leaving it permanently unreachable via Tier 2/2b
625            // cross-instance/cross-channel delivery (reagent P1,
626            // third round on PR #2350).
627            let data_dir = crate::backend::base::get_mux_data_dir();
628            crate::backend::reactive::registry::write(
629                &data_dir,
630                &agent_name,
631                local_web_url,
632                &block_id,
633            );
634            crate::backend::reactive::registry::write_shared_from_env(
635                &agent_name,
636                local_web_url,
637                &block_id,
638            );
639        }
640    }
641}
642
643/// App Server owns a persistent thread/turn process and has its own typed
644/// protocol path. Keep it ahead of the legacy stream-json branches.
645///
646/// KNOWN GAP (#3215, tracked for a follow-up, not fixed here): the turn's
647/// env vars (including this turn's freshly-resolved identity
648/// bindings from inject_identity_env_async) are computed but never reach
649/// this branch — send_message carries no env, and the App Server child was
650/// already spawned earlier using only command_from_meta's cmd:env snapshot.
651/// Unlike the subprocess/persistent controllers, this isn't a missing
652/// plumbing call: env vars are fixed at process exec() time, so an
653/// already-running App Server process cannot pick up a per-turn identity
654/// change at all without being torn down and respawned. Deciding when to
655/// force that respawn (e.g. on every identity-binding change vs. only
656/// between turns) is a real design question, not a mechanical fix, so it's
657/// deliberately left for a follow-up PR rather than rushed in here.
658///
659/// A message the pane held during a turn joins that turn (turn-model spec §4.3, J3). The persistent controller carries
660/// it on the input itself; the others start passes with no labelled input, so their tracker is told just before the
661/// dispatch, never earlier: a failure in the preparation must not leave the hint armed for a later message (#4492).
662pub(super) fn dispatch_app_server(
663    turn: Turn<'_>,
664    app_server_ctrl: &blockcontroller::app_server_controller::AppServerController,
665    tracker: Option<Arc<crate::backend::blockcontroller::health::TurnActivityTracker>>,
666) -> Result<(), String> {
667    let hint = ArmedJoinHint::arm(turn.joins_turn, tracker);
668    app_server_ctrl.send_message_from(turn.message, turn.image_paths, turn.message_id.is_some(), Some(&turn.record))?;
669    hint.keep();
670    Ok(())
671}
672
673/// ACP agents (Copilot, OpenClaw, Pi) and Muse Code (MSP): the message
674/// becomes a prompt (a turn) on the agent's running session.
675/// If the agent's process exited or crashed, this starts it again from
676/// the pane's meta; the message waits for the new session.
677pub(super) fn dispatch_session_agent(
678    turn: Turn<'_>,
679    acp_ctrl: &dyn blockcontroller::session_agent::SessionAgent,
680    tracker: Option<Arc<crate::backend::blockcontroller::health::TurnActivityTracker>>,
681) -> Result<(), String> {
682    acp_ctrl.ensure_started(turn.block.meta.clone())?;
683    let hint = ArmedJoinHint::arm(turn.joins_turn, tracker);
684    acp_ctrl.send_message(turn.message, turn.message_id.as_deref(), Some(&turn.record))?;
685    hint.keep();
686    Ok(())
687}
688
689#[cfg(test)]
690#[path = "turn_steps_tests.rs"]
691mod turn_steps_tests;