Skip to main content

agentmux_srv/server/app_api/
agent_open_steps.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The steps `agent.open` runs in order, one function each. `open_agent_inner` (agent_open.rs) calls them;
5//! the code is moved from it unchanged.
6
7use super::*;
8use super::agent_open::{record_agent_open_launch, require_local_agent_row, resolve_cli_args, resolve_vendor_env_override, select_openable_agent, write_agent_config_files, AGENT_OPEN_INSTALL_WAIT_SECS};
9
10/// Step 1: the definition to open, by id or name, with its provider settled.
11pub(super) fn pick_openable_agent(state: &AppState, agent_ref: &str) -> Result<AgentDefinition, String> {
12    let agents = state.mstore.agent_def_list()
13        .map_err(|e| format!("agent.open: {e}"))?;
14    // An agent whose record this build cannot read has no row here to select: it is found by its id or name and refused with why,
15    // not reported as not found.
16    let mut agent = match select_openable_agent(&agents, agent_ref) {
17        Ok(found) => found.clone(),
18        Err(not_found) => return Err(unreadable_refusal(state, agent_ref).unwrap_or(not_found)),
19    };
20    // A definition a newer AgentMux wrote (or a damaged one) is not started from the older copy this channel may still hold: the
21    // agent is kept as its record has it, and the reason is what the person is told.
22    if let Some(why) = state.mstore.agent_def_unreadable_reason(&agent.id) {
23        return Err(unreadable_text(&agent.name, &why));
24    }
25
26    // Settle `agent.provider` once through the shared resolver
27    // (the agent's own, or its bundle's when it has none; see
28    // Store::resolve_effective_provider_id) instead of at every
29    // downstream read in this handler. MUST be
30    // the `id_store`, never `mstore`.
31    agent.provider = state.id_store.resolve_effective_provider_id(&agent);
32    Ok(agent)
33}
34
35/// What a start of an agent whose record this build cannot read is told.
36fn unreadable_text(name: &str, why: &str) -> String {
37    format!("DEFINITION_UNREADABLE: {name} cannot be used by this version of AgentMux: {why}. It is kept exactly as it is, and can be deleted.")
38}
39
40/// The refusal for `agent_ref` (an id or a name) when it names a record this build cannot read, else `None`.
41fn unreadable_refusal(state: &AppState, agent_ref: &str) -> Option<String> {
42    let wanted = agent_ref.trim();
43    state
44        .mstore
45        .agent_def_unreadable_stand_ins()
46        .into_iter()
47        .find(|d| d.id == wanted || (!d.name.is_empty() && d.name.eq_ignore_ascii_case(wanted)))
48        .map(|d| unreadable_text(&d.name, &d.description))
49}
50
51/// Takes the start's marker off `extra_meta` (it is not block meta): whether it is a start with no pane.
52pub(super) fn take_start_marker(extra_meta: &mut MetaMapType) -> bool {
53    extra_meta.remove(super::agent_attach::START_PARKED).is_some()
54}
55
56/// The checks before anything is written for the agent: no live instance elsewhere on this host, and a local row.
57pub(super) async fn admit_open(state: &AppState, agent: &AgentDefinition) -> Result<(), String> {
58    let mstore = &state.mstore;
59    // An agent handed to another computer is not opened here, whatever its provider's controller is.
60    if let Some(refusal) = crate::backend::agent_admission::handed_over_check(mstore, &agent.id, &agent.name) {
61        return Err(refusal);
62    }
63    // One live instance per agent across every AgentMux instance
64    // on this host (SPEC_AGENT_SINGLE_LIVE_INSTANCE_2026_09_24
65    // Phase 1, I9) — checked before this handler writes anything
66    // on the agent's behalf. The in-process checks below only see
67    // this srv; this sees the others.
68    crate::backend::agent_admission::check_before_spawn(
69        crate::backend::agent_admission::lease_store_for(mstore.shared_agent_registry()),
70        &agent.id,
71        &agent.name,
72        &state.boot_id,
73    )
74    .await
75    .map_err(|refusal| format!("AGENT_LIVE_ELSEWHERE: {refusal}"))?;
76
77    // Identity M4b-4 (spec §6.5.8): a user agent known only from
78    // the shared registry (another channel's) gets its local row
79    // before any spawn, so its block resolves to it. Templates
80    // were refused above.
81    require_local_agent_row(&mstore, &agent.id)?;
82
83    // A host agent in a folder a container agent can write opens once the person has gone ahead with that pair
84    // (the window asks them, then opens it again), whoever starts it: a message, a start, restart resume.
85    crate::backend::folder_overlap::check_open(mstore, agent)
86}
87
88/// Step 5: the provider's CLI on disk, installing the pinned version when it is missing.
89pub(super) async fn resolve_cli_path(provider: &providers::ProviderConfig) -> Result<String, String> {
90    let paths = agentmux_common::DataPaths::from_env()
91        .ok_or_else(|| "DataPaths::from_env() failed".to_string())?;
92    let npm_bin = crate::backend::cli_install::npm_bin(
93        &crate::backend::cli_install::install_dir(&paths, &provider.id, provider.pinned_version),
94        provider.cli_command,
95    )
96    .to_string_lossy()
97    .to_string();
98    // The one lookup the picker and the Toolchain pane use too:
99    // AgentMux's install, else the user's own copy for a provider
100    // AgentMux doesn't install (Kimi, Goose, …).
101    let mut resolved_cli_path = crate::server::cli_handlers::locate_provider_cli(provider.id)
102        .await
103        .map(|l| l.path)
104        .unwrap_or_else(|| npm_bin.clone());
105    if !std::path::Path::new(&resolved_cli_path).exists() {
106        // An npm-backed provider whose pinned CLI isn't there yet
107        // (a fresh install, or the minute or two after an upgrade
108        // moved the pin): install it, as the UI's launch flow does,
109        // instead of making the caller go and do that first.
110        if provider.npm_package.is_empty() || provider.pinned_version.is_empty() {
111            return Err(format!(
112                "CLI_NOT_AVAILABLE: {} not found at {}. Install it, then try again.",
113                provider.cli_command, npm_bin
114            ));
115        }
116        let req = crate::backend::cli_install::NpmInstallRequest {
117            provider_id: provider.id.to_string(),
118            npm_package: provider.npm_package.to_string(),
119            pinned_version: provider.pinned_version.to_string(),
120            cli_command: provider.cli_command.to_string(),
121            background: false,
122        };
123        match crate::backend::cli_install::ensure_installed(
124            paths.clone(),
125            req,
126            std::time::Duration::from_secs(AGENT_OPEN_INSTALL_WAIT_SECS),
127        )
128        .await
129        {
130            Ok(bin) => resolved_cli_path = bin.to_string_lossy().to_string(),
131            Err(crate::backend::cli_install::EnsureError::StillInstalling) => {
132                return Err(format!(
133                    "CLI_INSTALLING: {} {} is still being installed. Try again in a minute; \
134                     the install carries on in the background.",
135                    provider.cli_command, provider.pinned_version
136                ));
137            }
138            Err(crate::backend::cli_install::EnsureError::Failed(why)) => {
139                return Err(format!(
140                    "CLI_NOT_AVAILABLE: {} {} could not be installed: {why}",
141                    provider.cli_command, provider.pinned_version
142                ));
143            }
144        }
145    }
146    Ok(resolved_cli_path)
147}
148
149/// The CLI args for the pane: catalog args, the runtime the menu shows, then the definition's own flags.
150pub(super) fn seed_runtime_args(
151    mstore: &Store,
152    agent: &AgentDefinition,
153    provider: &providers::ProviderConfig,
154    controller_type: &str,
155) -> (crate::backend::agent_runtime::SeededLaunch, String) {
156    // Catalog args, the runtime the menu will show applied on top, then the
157    // definition's own flags. Without the middle step a pane opened here
158    // ran on the CLI's default model while its menu read Sonnet — see
159    // backend/agent_runtime.rs.
160    //
161    // What the user last picked in the menu for this agent sits above the
162    // definition's flags (and replaces them in this pane's copy), so
163    // reopening an agent starts where it was left. A read failure only
164    // means "nothing remembered".
165    let remembered = crate::backend::agent_runtime::Remembered::parse(
166        provider.id,
167        &mstore.agent_last_runtime_get(&agent.id).unwrap_or_default(),
168    );
169    let (base_args, pane_flags, remembered_mode) = crate::backend::agent_runtime::apply_remembered(
170        provider.id,
171        resolve_cli_args(&provider, controller_type),
172        &agent.provider_flags,
173        &remembered,
174    );
175    let mut seeded =
176        crate::backend::agent_runtime::seed_launch(provider.id, base_args, &pane_flags);
177    if let (Some(mode), Some(rt)) = (remembered_mode, seeded.runtime.as_mut()) {
178        rt["permissionMode"] = json!(mode);
179    }
180    (seeded, pane_flags)
181}
182
183/// The provider's default auth directory, created with the isolation it needs before a CLI is pointed at it.
184pub(super) fn prepare_auth_dir(provider: &providers::ProviderConfig) -> Result<String, String> {
185    // Auth dir — the DEFAULT provider auth lives in the shared,
186    // instance/channel/version-independent providers area so a single
187    // login is shared everywhere (the structural fix for the per-channel
188    // validate-spin regression). The per-account auth dir
189    // (identity_handlers) still wins for explicit multi-account.
190    let auth_dir = providers::default_auth_dir(provider)?;
191    // Create the dir AND apply its isolation guarantees in one
192    // inseparable step. Claude Code CLI's own user-level CLAUDE.md
193    // discovery falls through to the real $HOME/.claude/CLAUDE.md
194    // when this isolated dir has none of its own — CLAUDE_CONFIG_DIR
195    // relocates credential/session/project storage but NOT that
196    // lookup (proven live, three-arm experiment:
197    // docs/reports/REPORT_CLAUDE_CONFIG_DIR_ISOLATION_EVIDENCE_2026_09_01.md).
198    //
199    // Fail closed (block the spawn) rather than warn-and-continue:
200    // continuing would launch the agent with exactly the
201    // unprotected condition this exists to close (Codex P1 +
202    // ReAgent P1, PR #2854). Non-claude providers get the dir
203    // created and nothing else, so this never blocks their spawns.
204    // See SPEC_ISOLATE_HOST_CLAUDE_MD_2026_08_31.md.
205    providers::prepare_provider_auth_dir(provider, &auth_dir).map_err(|e| {
206        format!(
207            "failed to isolate this agent's Claude Code config ({auth_dir}): {e}. \
208             Refusing to launch with an unprotected config dir."
209        )
210    })?;
211    Ok(auth_dir)
212}
213
214/// The environment the agent's process starts with: provider and auth entries, the vendor override, the definition's
215/// own variables and its identity.
216pub(super) fn launch_env(
217    mstore: &Store,
218    agent: &AgentDefinition,
219    provider: &providers::ProviderConfig,
220    auth_dir: &str,
221    routing_id: &str,
222    controller_type: &str,
223) -> Result<serde_json::Map<String, serde_json::Value>, String> {
224    let mut env_vars = serde_json::Map::new();
225    for key in provider.unset_env {
226        env_vars.insert(key.to_string(), json!(""));
227    }
228    if !provider.auth_config_dir_env_var.is_empty() { env_vars.insert(provider.auth_config_dir_env_var.to_string(), json!(auth_dir)); }
229    for (k, v) in provider.auth_extra_env {
230        env_vars.insert(k.to_string(), json!(v));
231    }
232    // Model vendor override (harness vs. model-vendor decoupling)
233    // — e.g. ANTHROPIC_BASE_URL for a claude-provider agent
234    // pointed at a proxy/Bedrock/OpenRouter instead of
235    // Anthropic's default endpoint. Inserted before the
236    // free-form env blob below so it wins if a definition-level
237    // KEY=VALUE line collides with it (structured field over
238    // free-form blob, same precedence as the auth entries above).
239    if let Some((var, value)) = resolve_vendor_env_override(provider, &agent) {
240        env_vars.insert(var.to_string(), json!(value));
241    }
242    // Merge env vars from the definition's persisted env content blob (KEY=VALUE lines).
243    // Provider/auth entries inserted above take precedence; definition-level vars
244    // are merged after so they can extend (but not override) the auth env.
245    if let Ok(Some(env_blob)) = mstore.agent_content_get(&agent.id, "env") {
246        // Read the way the My Agents editor shows it (`backend::agent_env`): comments
247        // and lines without a valid `NAME=` are skipped, and a repeated name takes its last value.
248        for (k, v) in crate::backend::agent_env::effective(&env_blob.content) {
249            if !env_vars.contains_key(&k) {
250                // A key written in the clear goes into the process as written; it is never written into a transcript.
251                crate::backend::transcript::withhold_sources::env_credential(&agent.id, &k, &v);
252                env_vars.insert(k, json!(v));
253            }
254        }
255    }
256    // Agent identity. `GH_CONFIG_DIR` is not persisted here: it is
257    // a reserved variable set on every spawn by `backend::gh_guard`,
258    // which this env reaches through `build_persistent_spawn_env`.
259    // Use stored slug (stable across renames) for muxbus routing;
260    // fall back to the computed slug derived from the display name.
261    env_vars.insert("AGENTMUX_AGENT_ID".to_string(), json!(routing_id));
262    // Mirror under MUXBUS_AGENT_ID too, matching the same
263    // additive fix in agent_handlers/input.rs (ARCH-002) --
264    // this MuxAPI path (agent.open -> agent.send, via
265    // agent_io.rs reading this back from persisted cmd:env)
266    // builds its own env_vars independently of input.rs's spawn
267    // path, so it needs the same mirror applied here rather than
268    // inheriting it (codex P2 on PR #2345).
269    env_vars.insert("MUXBUS_AGENT_ID".to_string(), json!(routing_id));
270    // Exit delay only for subprocess
271    if controller_type != "persistent" {
272        env_vars.insert("CLAUDE_CODE_EXIT_AFTER_STOP_DELAY".to_string(), json!("30000"));
273    }
274    Ok(env_vars)
275}
276
277/// The provider session this open resumes: the agent's newest captured one, unless another block of it is live.
278pub(super) async fn resume_session_for(mstore: &Store, agent: &AgentDefinition) -> Option<String> {
279    // Cross-tab/cross-restart continuity: this agent may already have
280    // a captured provider session sitting in the shared registry
281    // (backfilled from its provider transcript, or captured live by a
282    // prior block) even though no block for it exists in THIS tab —
283    // e.g. after a full app restart lands on a different/rehydrated
284    // tab. Seed the new block's agent:sessionid meta so its FIRST
285    // turn resumes that conversation instead of silently starting
286    // fresh and orphaning the original — the same thing the
287    // picker's explicit "Continue" flow already does via
288    // continueOfInstanceId (RecentSessionRow.session_id), extended
289    // here to the default open path.
290    // See docs/retro/retro-cross-channel-conversation-continuity-regression-2026-06-16.md
291    // ("Mechanism 2 — continuity"), action item 4.
292    //
293    // Concurrency guard (reagent P1 on PR #2059): only seed
294    // agent:sessionid when no OTHER block for this same agent
295    // definition currently has a LIVE controller registered
296    // anywhere in this process — not just this tab (the reuse check
297    // in `agent_attach::tab_or_reuse` only scoped to the target tab).
298    // Without this, opening the same named agent in a second tab
299    // while the first is still live would seed the new block with
300    // the SAME session_id, letting two controllers concurrently
301    // `--resume` one provider session — risking transcript
302    // corruption or exactly the orphaning bug this fix exists to
303    // prevent. A block with no registered controller (e.g. right
304    // after an app restart, before anything has resynced) is not
305    // "live" and doesn't block seeding.
306    // A block of this agent that is mid-close has already left
307    // CONTROLLER_REGISTRY but its process may still be exiting
308    // (up to the close's grace period). Wait for it, so the check
309    // below sees it gone AND no second `--resume` starts on the
310    // session while the old process still holds it
311    // (SPEC_AGENT_PANE_CLOSE_GRACEFUL_SHUTDOWN_2026_09_18.md §9.6).
312    let closing_blocks: Vec<String> = mstore
313        .get_all::<Block>()
314        .map(|blocks| {
315            blocks
316                .into_iter()
317                .filter(|b| {
318                    obj::meta_get_string(&b.meta, "agentId", "") == agent.id
319                        && blockcontroller::is_closing(&b.oid)
320                })
321                .map(|b| b.oid)
322                .collect()
323        })
324        .unwrap_or_default();
325    for closing in &closing_blocks {
326        blockcontroller::wait_closing_stopped(
327            closing,
328            blockcontroller::SHUTDOWN_GRACE + std::time::Duration::from_secs(2),
329        )
330        .await;
331    }
332    let agent_live_elsewhere = mstore.get_all::<Block>()
333        .map(|blocks| {
334            blocks.iter().any(|b| {
335                obj::meta_get_string(&b.meta, "agentId", "") == agent.id
336                    && blockcontroller::get_controller(&b.oid).is_some()
337            })
338        })
339        .unwrap_or(false);
340    let resume_session_id: Option<String> = if agent_live_elsewhere {
341        None
342    } else {
343        mstore.shared_agent_registry()
344            .and_then(|reg| reg.list_active().ok())
345            .and_then(|records| {
346                records.into_iter()
347                    .filter(|r| r.data.definition_id == agent.id)
348                    .filter(|r| r.data.session_id.as_deref().map_or(false, |s| !s.is_empty()))
349                    .max_by_key(|r| r.data.last_launched_at_ms)
350            })
351            .and_then(|r| r.data.session_id)
352    };
353    resume_session_id
354}
355
356/// The pane meta that says which agent this is: its zoom, colour, seat, icon and container settings.
357pub(super) fn pane_identity_meta(mstore: &Store, agent: &AgentDefinition, provider: &providers::ProviderConfig) -> MetaMapType {
358    let mut meta = MetaMapType::new();
359    meta.insert("view".to_string(), json!("agent"));
360    meta.insert("agentId".to_string(), json!(&agent.id));
361    // Per-agent zoom persistence (SPEC_AGENT_ZOOM_PERSISTENCE): seed
362    // the new block's `term:zoom` from the agent's saved `ui:zoom`
363    // (per-agent content store, global cross-channel) so reopening
364    // the same agent restores its zoom instead of resetting to 1.0.
365    // Stored only for non-default zooms; clamp to the frontend's
366    // [0.5, 2.0] range so a corrupt value can't escape it.
367    if let Ok(Some(c)) = mstore.agent_content_get(&agent.id, "ui:zoom") {
368        if let Some(z) = parse_seed_zoom(&c.content) {
369            meta.insert("term:zoom".to_string(), json!(z));
370        }
371    }
372    // Per-agent color (SPEC_AGENT_COLOR_2026_08_08.md): seed the new block's frame border
373    // colors from the agent's stored ui:color so the existing pane-frame rendering shows
374    // it (frame:activebordercolor; the unfocused border is the same hue's own tone, drawn
375    // by pane-color-scheme.ts, so nothing dimmed is stored). Assign-if-missing write-through covers defs
376    // created by paths the createagent handler doesn't own (forks, imports) and any def
377    // that predates migration m0020 on this channel. Strict #rrggbb validation so a
378    // corrupt row can't inject arbitrary CSS.
379    {
380        use crate::backend::agent_color::{color_for_new_agent, is_valid_agent_color};
381        let stored = mstore
382            .agent_content_get(&agent.id, "ui:color")
383            .ok()
384            .flatten()
385            .map(|c| c.content.trim().to_string())
386            .filter(|c| is_valid_agent_color(c));
387        let color = match stored {
388            Some(c) => c,
389            None => {
390                let picked = color_for_new_agent(&mstore, &agent.id);
391                let now_ms = agentmux_common::time::now_ms();
392                // Best-effort: a store error here shouldn't block
393                // opening the agent — the pane just stays uncolored
394                // this session and we retry next open.
395                let _ = mstore.agent_content_set(&crate::backend::storage::store::AgentContent {
396                    agent_id: agent.id.clone(),
397                    content_type: "ui:color".to_string(),
398                    content: picked.clone(),
399                    updated_at: now_ms,
400                });
401                picked
402            }
403        };
404        meta.insert("frame:activebordercolor".to_string(), json!(&color));
405    }
406    meta.insert("agentProvider".to_string(), json!(&agent.provider));
407    meta.insert("agentName".to_string(), json!(&agent.name));
408    // Its seat, for the header tooltip; agent.setSeat refreshes it (SPEC_AGENT_SEATS_IN_THE_UI_2026_10_23.md §4).
409    crate::backend::agent_seat::seed_meta(&mstore, &agent.id, &mut meta);
410    meta.insert("agentIcon".to_string(), json!(if agent.icon.is_empty() { "wand-magic-sparkles" } else { &agent.icon }));
411    meta.insert("agentMode".to_string(), json!(if agent.agent_type.is_empty() { "host" } else { &agent.agent_type }));
412    if !agent.container_image.is_empty() {
413        meta.insert("agent:container_image".to_string(), json!(&agent.container_image));
414    }
415    if agent.container_volumes != "[]" && !agent.container_volumes.is_empty() {
416        meta.insert("agent:container_volumes".to_string(), json!(&agent.container_volumes));
417    }
418    // Container-local CLI command: the provider's CLI as it resolves
419    // INSIDE the image (on the image's PATH, e.g. `claude`). Distinct
420    // from `cmd` (set in `add_launch_meta`), which is the host-resolved absolute npm path
421    // (`<config_home>/.../node_modules/.bin/claude`) and does NOT exist
422    // in the container — passing it as docker-exec argv[0] would fail
423    // with "no such file or directory". Container turns use this.
424    meta.insert("agent:container_command".to_string(), json!(provider.cli_command));
425    meta
426}
427
428/// What the pane needs to launch the CLI, added to its identity meta.
429pub(super) struct LaunchMeta<'a> {
430    pub controller_type: &'a str,
431    pub cli_path: &'a str,
432    pub seeded: crate::backend::agent_runtime::SeededLaunch,
433    pub pane_flags: &'a str,
434    pub work_dir: &'a str,
435    pub env_vars: serde_json::Map<String, serde_json::Value>,
436    pub resume_session_id: Option<&'a str>,
437    pub extra_meta: MetaMapType,
438}
439
440/// Step 6, the launch half: command, args, working directory, env, resume settings, then the caller's extra keys.
441pub(super) fn add_launch_meta(meta: &mut MetaMapType, provider: &providers::ProviderConfig, launch: LaunchMeta<'_>) {
442    let LaunchMeta { controller_type, cli_path, seeded, pane_flags, work_dir, env_vars, resume_session_id, extra_meta } = launch;
443    // The provider's own format, as the UI launch writes it
444    // (`agent-model.ts`). A hard-coded map here stamped every
445    // provider it didn't list (the ACP ones) as Claude.
446    meta.insert("agentOutputFormat".to_string(), json!(provider.styled_output_format));
447    meta.insert("controller".to_string(), json!(controller_type));
448    meta.insert("cmd".to_string(), json!(cli_path));
449    // cmd:args + agent:runtime + agent:provider_flags, written together.
450    crate::backend::agent_runtime::apply_to_meta(meta, seeded, pane_flags);
451    meta.insert("cmd:cwd".to_string(), json!(work_dir));
452    meta.insert("cmd:env".to_string(), serde_json::Value::Object(env_vars));
453    meta.insert("agent:resume_flag".to_string(), json!(provider.resume_flag.unwrap_or("")));
454    meta.insert("agent:resume_strategy".to_string(), json!(provider.resume_strategy_str()));
455    meta.insert("agent:session_id_field".to_string(), json!(provider.session_id_field));
456    meta.insert("agent:prompt_arg_flag".to_string(), json!(provider.prompt_arg_flag().unwrap_or("")));
457    if let Some(sid) = resume_session_id {
458        meta.insert("agent:sessionid".to_string(), json!(sid));
459    }
460
461    providers::apply_terminal_pane_meta(provider, meta);
462    meta.extend(extra_meta);
463}
464
465/// Step 7 for `layout.open` and Import: give an empty agent pane that already sits in the layout the agent's meta.
466pub(super) async fn fill_existing_pane(state: &AppState, target: &str, meta_val: serde_json::Value) -> Result<String, String> {
467    let mstore = &state.mstore;
468    // `layout.open` and Import…: the pane already exists and sits
469    // in the rebuilt tree — give it the agent's meta through
470    // the reducer (like `pane.open`'s editor reuse) and skip
471    // the layout insert (`create_agent_block`'s job).
472    let target_block = mstore
473        .get::<Block>(target)
474        .map_err(|e| format!("agent.open: read target pane: {e}"))?
475        .ok_or_else(|| format!("agent.open: no such pane: {target}"))?;
476    if obj::meta_get_string(&target_block.meta, "view", "") != "agent"
477        || !obj::meta_get_string(&target_block.meta, "agentId", "").is_empty()
478    {
479        return Err("agent.open: the target pane is not an empty agent pane".to_string());
480    }
481    let mut patch = meta_val.clone();
482    if let Some(p) = patch.as_object_mut() {
483        // The layout's "which agent goes here" hint is spent.
484        p.insert(crate::backend::layout_file::META_LAYOUT_AGENT.to_string(), serde_json::Value::Null);
485    }
486    let meta_events = crate::server::service::dispatch_to_reducer(
487        state,
488        agentmux_common::ipc::Command::UpdateBlockMeta { block_id: target.to_string(), meta_patch: patch },
489    )
490    .await;
491    if let Some(msg) = meta_events.iter().find_map(|e| match e {
492        agentmux_common::ipc::Event::Error { message, .. } => Some(message.clone()),
493        _ => None,
494    }) {
495        return Err(format!("agent.open: UpdateBlockMeta: {msg}"));
496    }
497    for ev in &meta_events {
498        if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, mstore) {
499            tracing::warn!("agent.open: UpdateBlockMeta mstore apply failed: {e}");
500        }
501    }
502    crate::server::service::publish_events(state, &meta_events);
503    Ok(target.to_string())
504}
505
506/// Step 7 for a new pane: create the block through the reducer, then place it in the layout (or park it for a start).
507///
508/// Through the reducer (#1681), not wcore-direct: a store-only block is invisible to the reducer-canonical
509/// `state.blocks` (only hydrated from SQLite at bootstrap), so tearing this agent pane off later was rejected
510/// "block not found". `BlockCreated` carries meta, and `apply_block_created` writes the mstore Block, which the
511/// controller resync reloads by id.
512pub(super) async fn create_agent_block(
513    state: &AppState,
514    tab_id: &str,
515    meta_val: serde_json::Value,
516    headless: bool,
517    cmd: &CommandAgentOpenData,
518) -> Result<String, String> {
519    let block_id = crate::server::service::create_block_in_tab(state, tab_id, meta_val, "agent.open").await?;
520
521    // Place it: srv's tree, then the queued `insert` for the
522    // window. Best-effort: a failure leaves the block unplaced,
523    // for the orphan reaper. `focus` defaults to true, as the UI
524    // flow does (#3032). A split of a named pane, as `pane.open`.
525    if headless {
526        super::agent_attach::park_new(state, &tab_id, &block_id).await?; // a start: parked, no pane
527    } else {
528        let placement = super::pane::resolve_placement(cmd.split_direction.as_deref(), cmd.split_reference_block_id.as_deref(), cmd.focus.unwrap_or(true));
529        if let Err(e) = crate::server::service::layout_intents::place_block(state, &tab_id, &block_id, placement).await {
530            tracing::warn!("agent.open: placing the pane failed: {e}");
531        }
532    }
533    Ok(block_id)
534}
535
536/// Step 9: register the block's controller (not for a terminal-tier CLI: its term view starts it once attached).
537pub(super) fn start_controller(state: &AppState, provider: &providers::ProviderConfig, tab_id: &str, block_id: &str, headless: bool) -> Result<(), String> {
538    let mstore = state.mstore.clone();
539    let broker = state.broker.clone();
540    let event_bus = state.event_bus.clone();
541    let filestore = state.filestore.clone();
542    let app_state = state;
543    let block_for_resync = mstore.must_get::<Block>(block_id)
544        .map_err(|e| format!("agent.open: reload block: {e}"))?;
545    super::agent_attach::set_desired(&mstore, block_id, super::agent_attach::DESIRED_RUNNING);
546    if provider.controller_type != providers::ControllerType::Terminal { blockcontroller::resync_controller(
547        &block_for_resync,
548        if headless { "" } else { tab_id },
549        None,
550        true,
551        true,
552        Some(broker.clone()),
553        Some(event_bus.clone()),
554        Some(mstore.clone()),
555        Some(filestore.clone()),
556        Some(app_state.id_store.clone()),
557        Some(app_state.identity_store.clone()),
558        mstore.shared_agent_registry(),
559        app_state.boot_id.clone(),
560        &app_state.auth_key,
561        Some(app_state.config_watcher.clone()),
562    )?; }
563    Ok(())
564}
565
566/// The controller type a new pane gets for this agent's runtime.
567pub(super) fn open_controller_type(agent: &AgentDefinition, provider: &providers::ProviderConfig) -> Result<&'static str, String> {
568    let runtime = crate::backend::runtime_adapter::RuntimeKind::of_agent_type(&agent.agent_type).adapter();
569    if !runtime.can_host(provider.controller_type) { return Err(format!("{} runs on the host, not in a container", provider.id)); }
570    let controller_type = provider.controller_type_str();
571    // Container agents use per-turn docker exec; the subprocess controller
572    // is required regardless of what the provider defaults to (claude returns
573    // "persistent", which causes AgentInput to skip the container exec path).
574    Ok(runtime.controller_type_for_open(controller_type))
575}
576
577/// Where the agent runs.
578pub(super) fn agent_work_dir(agent: &AgentDefinition) -> String {
579    // Shared with native-memory resolution so the two can never
580    // disagree about where a blank-working_directory agent
581    // actually runs — they did, and Personal Bundle broke for the
582    // common case as a result (ReAgent/Codex P1, PR #2901; see
583    // SPEC_FIX_PERSONAL_MEMORY_EMPTY_WORKDIR_2026_09_01.md).
584    if agent.working_directory.is_empty() {
585        crate::backend::storage::agents::default_agent_working_dir(&agent.name)
586    } else {
587        agent.working_directory.clone()
588    }
589}
590
591/// The id the agent is known by on the message bus: its stored slug (stable across renames), else one derived from its name.
592pub(super) fn routing_id(agent: &AgentDefinition) -> String {
593    if agent.slug.is_empty() { agentmux_common::slug::path_slug(&agent.name) } else { agent.slug.clone() }
594}
595
596/// Step 8: write the agent's config files, then record the launch and stamp the block before the resync.
597pub(super) fn write_files_and_record_launch(state: &AppState, agent: &AgentDefinition, routing_id: &str, work_dir: &str, block_id: &str) -> Result<(), String> {
598    // No collision resolution in this path — the function creates the dir if
599    // missing and overwrites whatever's there. Same-name same-hour launches
600    // will share a workdir; proper allocation is tracked as a follow-up.
601    write_agent_config_files(&state.mstore, &state.id_store, &state.identity_store, agent, routing_id, work_dir)?;
602    // Identity M4b-4: a controller can report its session id during the
603    // resync, and that capture finds the row by block (#3584).
604    record_agent_open_launch(&state.mstore, &agent.id, block_id)
605}
606
607/// The status of the pane's controller, or `init` when it has none yet. A pane seeded with a registry-derived
608/// `agent:sessionid` can come back already `running` (#3513), so this is read, not assumed.
609pub(super) fn launch_status(block_id: &str) -> String {
610    blockcontroller::get_block_controller_status(block_id)
611        .map(|s| s.shellprocstatus)
612        .unwrap_or_else(|| "init".to_string())
613}