Skip to main content

agentmux_srv_core/backend/spawn_env/
build.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The spawn environment of a persistent-controller CLI process.
5
6use std::sync::Arc;
7
8/// Builds the full spawn environment for a persistent-controller CLI
9/// process: `cmd:env` base → Layer 3 identity/credential gate → the two
10/// RESERVED wrapper variables (unconditionally overwritten —
11/// `AGENTMUX_AUTH_KEY`/`AGENTMUX_BLOCKID`) → the two agent-identity
12/// variables and per-agent git identity (from the row's slug when it has
13/// one, `identity_env`) → bundled/user tools PATH → the reserved guards (`gh_guard`,
14/// `account_login_guard`: no agent gets a human's `gh` login or the
15/// account's cloud login).
16///
17/// Shared by every real spawn of a persistent-controller CLI — this
18/// function's own logic used to live inline in `run_agent_turn` below, and
19/// only there. `PersistentSubprocessController::start()`'s eager-resume
20/// path (`SPEC_PERSISTENT_CONTROLLER_EAGER_RESUME_ON_RECONNECT_2026_09_20.md`)
21/// built its own second, independent copy of a SUBSET of this — codex P1 on
22/// PR #3513 found it had already drifted from this one: missing PATH and
23/// (then) MuxBus-token injection entirely, and using `entry().or_insert()` instead
24/// of an unconditional overwrite for the two reserved wrapper variables
25/// (meaning a stale persisted `cmd:env` value for either would silently
26/// survive across an eager resume, unlike a live message send). One
27/// function, not two copies kept in sync by hand.
28///
29/// `Err(SpawnGateError)` means the caller must NOT spawn — same contract as
30/// `inject_identity_env_async` itself, which this wraps.
31pub async fn build_persistent_spawn_env(
32    mstore: Arc<crate::backend::storage::store::Store>,
33    id_store: Arc<crate::backend::storage::store::Store>,
34    identity_store: Arc<crate::backend::storage::store::Store>,
35    broker: Option<Arc<crate::backend::mps::Broker>>,
36    block_meta: &crate::backend::obj::MetaMapType,
37    block_id: &str,
38    auth_key: &str,
39    base_env_vars: std::collections::HashMap<String, String>,
40) -> Result<std::collections::HashMap<String, String>, crate::identity::resolver::SpawnGateError> {
41    // Identity injection: look up the active AgentInstance for this block,
42    // resolve its identity_id's bindings, and merge each per-provider env
43    // var into the spawn map. Api-key-class failures are logged and
44    // skipped — the agent CLI launches with whatever resolved cleanly plus
45    // the static cmd:env block. Oauth-class resolution failures are
46    // BLOCKING unless the agent opted into ambient login (layer-3 spawn
47    // gate, SPEC_ACCOUNT_DELETE_DEAUTH_LAYERS_2_4_2026_07_14.md §2.2).
48    // Kept for the identity-M0 slug lookup below; `mstore` itself moves into
49    // the identity injector.
50    let mstore_for_slug = mstore.clone();
51    let mut env_vars =
52        super::endpoint::inject_identity(mstore, id_store, identity_store, broker, block_meta, block_id, base_env_vars).await?;
53
54    // No MuxBus account login here: agents reach the cloud through the srv,
55    // which uses its own stored login (see `account_login_guard`).
56
57    // Streaming-bash wrapper auth + discovery
58    // (SPEC_STREAMING_BASH_RUNNER_2026_05_11.md §7).
59    //
60    // 1. AGENTMUX_AUTH_KEY — config.rs's `Config::from_env_and_args` removed
61    //    it from the process env at startup (security PR #801). Re-inject for this spawn so the
62    //    wrapper (running inside Claude's bash subprocess tree) can
63    //    authenticate against the auth_middleware-gated
64    //    /agentmux/wps/publish endpoint via X-AuthKey.
65    // 2. PATH — prepend the bundled tools/bin dir so `agentmux-bashwrap.exe`
66    //    resolves when the PreToolUse hook (auto-injected by
67    //    agent_config.rs) rewrites the command to invoke it.
68    //    AGENTMUX_LOCAL_URL is already in the inherited process env
69    //    (set by `bind_listeners_and_network` in bootstrap/network.rs).
70    //
71    // Unconditional `insert`, NOT `entry().or_insert()` — these two are
72    // RESERVED, server-controlled values (the current key, the real block
73    // id), not user configuration. A persisted `cmd:env` carrying a stale
74    // value for either (e.g. from a prior server restart with a different
75    // key) must not survive into this spawn.
76    env_vars.insert("AGENTMUX_AUTH_KEY".to_string(), auth_key.to_string());
77    // Block id so the wrapper can scope its MPS publishes to `block:<id>`.
78    // Without this, chunks publish without a scope and the frontend's
79    // per-block subscription doesn't receive them.
80    env_vars.insert("AGENTMUX_BLOCKID".to_string(), block_id.to_string());
81
82    // Identity M0 + M1. M0: name and slug as two explicit variables, on this
83    // path too — the frontend's `launchAgentDefinition` already sets both;
84    // this path never did, so a reader could only get at either by guessing
85    // what `AGENTMUX_AGENT_ID` held (`split_agent_identity_env`). M1: the
86    // UID and the agent's token, from the row the server itself created
87    // (`carry_agent_uid_env`). One store round-trip serves both.
88    {
89        let display_name = crate::backend::obj::meta_get_string(block_meta, "agentName", "");
90        // P0.3: the workspace `.mcp.json` follows the slug too.
91        let meta = |key, default| crate::backend::obj::meta_get_string(block_meta, key, default);
92        let (cwd, mode) = (meta("cmd:cwd", ""), meta("agentMode", "host"));
93        let identity = {
94            let mstore = mstore_for_slug.clone();
95            let owned_block_id = block_id.to_string();
96            match tokio::task::spawn_blocking(move || {
97                let identity = super::block_identity::persisted_agent_identity(&mstore, &owned_block_id);
98                if let Some(slug) = identity.as_ref().and_then(|i| i.slug.as_deref()) {
99                    crate::backend::mcp_json_identity::realign_workspace_mcp_json(&mstore, &cwd, &mode, slug);
100                }
101                // #3577, re-checked here: this is the last store read before
102                // the process starts. The gate refused a deleted agent, but
103                // the agent can be deleted after the gate's lookup succeeded
104                // (the delete handlers share no lock with the spawn path) —
105                // then no row resolves here, and without this the spawn
106                // would go ahead with no identity (Codex P1 on #3591). A
107                // delete after THIS read is a delete of a running agent.
108                let deleted =
109                    super::block_identity::deleted_agent_of_rowless_block(&mstore, &owned_block_id, identity.as_ref());
110                (identity, deleted)
111            })
112            .await
113            {
114                Ok((_, Some(agent_id))) => {
115                    return Err(crate::identity::resolver::SpawnGateError::AgentDeleted {
116                        agent_id,
117                    });
118                }
119                Ok((identity, None)) => identity,
120                Err(e) => {
121                    tracing::warn!(
122                        block_id = %block_id,
123                        error = %e,
124                        "spawn env: persisted-identity lookup task failed — no UID/token this spawn; AGENTMUX_AGENT_SLUG falls back to cmd:env"
125                    );
126                    None
127                }
128            }
129        };
130        super::block_identity::split_agent_identity_env(
131            &mut env_vars,
132            &display_name,
133            identity.as_ref().and_then(|i| i.slug.as_deref()),
134        );
135        super::block_identity::carry_agent_uid_env(&mut env_vars, identity.as_ref());
136        // The id, its MuxBus mirror and the git identity: from the row's slug
137        // when it has one, over `cmd:env` (see `identity_env`).
138        super::identity::carry_agent_identity_env(&mut env_vars, &display_name, identity.as_ref().and_then(|i| i.slug.as_deref()));
139    }
140    super::block_identity::carry_agent_workdir_env(&mut env_vars, block_meta);
141    carry_model_env(&mstore_for_slug, block_id, block_meta, &mut env_vars).await;
142    super::workspaces::record_launch_workspace(block_id, &env_vars);
143    // PATH gets the bundled tools dir (portable builds, runtime/tools/bin/)
144    // and the user tools dir (~/.agentmux/tools/bin/), both ahead of the
145    // inherited PATH: bundled is None in `task dev` (tool_store excludes
146    // target/debug), so the wrapper is in the user dir and a system copy must
147    // not shadow it. See `UserToolsPrecedence`.
148    crate::backend::tool_store::prepend_agent_tools_path(&mut env_vars);
149    super::bash_prefix::apply_for_spawn(&mut env_vars, block_id, block_meta);
150    // Plain `gh` must not act as a human's gh login (see `gh_guard`), and no
151    // agent holds the account's cloud login (see `account_login_guard`). Last,
152    // so nothing above — a persisted `cmd:env`, an identity binding — can set
153    // them back: these are reserved variables, not defaults.
154    crate::backend::gh_guard::apply_gh_guard(&mut env_vars);
155    crate::backend::account_login_guard::strip_account_login(&mut env_vars);
156    apply_cli_switches(&mut env_vars, block_meta);
157
158    Ok(env_vars)
159}
160
161/// The switches of the agent's CLI that AgentMux sets through its environment, over the agent's own values.
162fn apply_cli_switches(env_vars: &mut std::collections::HashMap<String, String>, block_meta: &crate::backend::obj::MetaMapType) {
163    // AgentMux agents message each other through jekt: the CLI's separate messaging is off by default.
164    crate::backend::cli_messaging::apply_for_spawn(env_vars, block_meta);
165    // A host agent in a folder a container agent can write: its CLI's scheduler is off, and it reads the
166    // startup instructions AgentMux keeps for it outside the folder.
167    crate::backend::host_agent_files::apply_for_spawn(env_vars, block_meta);
168    // Its git runs nothing the folder's own configuration names.
169    crate::backend::git_program_settings::apply_for_spawn(env_vars, block_meta);
170}
171
172/// The models an agent runs on: an agent on a model route is pointed at the gateway, then the sub-agent model
173/// is chosen, which keeps a model the route has already set.
174async fn carry_model_env(mstore: &Arc<crate::backend::storage::store::Store>, block_id: &str, block_meta: &crate::backend::obj::MetaMapType, env_vars: &mut std::collections::HashMap<String, String>) {
175    let (mstore, block, mut route_env) = (mstore.clone(), block_id.to_string(), env_vars.clone());
176    let carried = tokio::task::spawn_blocking(move || {
177        crate::backend::model_gateway::launch::carry_for_block(&mstore, &block, &mut route_env);
178        route_env
179    })
180    .await;
181    if let Ok(carried) = carried {
182        *env_vars = carried;
183    }
184    crate::backend::subagent_model::carry(env_vars, block_meta);
185}