Skip to main content

agentmux_srv/server/
http_shell.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Shell drawer HTTP handlers and the agent shell lock.
5//! Split out of server/mod.rs unchanged (SPEC_LARGE_FILE_MODULE_ANALYSIS_2026_09_30.md §4.1).
6
7use super::*;
8use super::app_api::connections::{self, AgentTarget};
9
10/// What a command's Vault entries come to once checked and asked for: the values it is given, and what its
11/// output is stored as (with the labels of the entries nobody answered for).
12type Prepared = (Option<super::shell_secrets::Injected>, (Option<crate::backend::vault::capture::Job>, Vec<String>));
13
14/// Asks for the Vault secrets a command is given and checks the values its output goes into the Vault as, together,
15/// so the whole asking fits the Terminal tool's wait. The agent says why first (a rotation's own commands carry the
16/// rotation's): a missing reason is refused before anything is asked or run.
17async fn prepare_secrets(
18    state: &AppState,
19    caller: Option<&super::caller::Caller>,
20    req: &ShellCreateRequest,
21    remote: bool,
22    preapproved: Option<&super::shell_secrets::Preapproved>,
23) -> Result<Prepared, Response> {
24    let gives = req.secrets.as_ref().is_some_and(|m| !m.is_empty())
25        || req.stdin_secret.as_deref().is_some_and(|s| !s.trim().is_empty())
26        || req.secret_files.as_ref().is_some_and(|m| !m.is_empty())
27        || req.capture.as_ref().is_some_and(|c| !c.is_empty());
28    let reason = if gives && preapproved.is_none() {
29        crate::backend::vault::history::require_reason(req.reason.as_deref()).map_err(|e| (StatusCode::BAD_REQUEST, Json(json!({ "error": e }))).into_response())?
30    } else {
31        req.reason.clone().unwrap_or_default()
32    };
33    let wanted = super::shell_secrets::Wanted { env: req.secrets.as_ref(), stdin: req.stdin_secret.as_deref(), files: req.secret_files.as_ref(), reason: &reason, caller };
34    let cwd = req.cwd.as_deref().unwrap_or("");
35    let injecting = super::shell_secrets::inject(state, &req.agent_block_id, req.auth.as_ref(), wanted, remote, &req.cmd, cwd, preapproved);
36    let capturing = super::shell_secrets::plan_capture(state, caller, &req.agent_block_id, req.auth.as_ref(), req.capture.as_deref(), &req.cmd, cwd, &reason);
37    tokio::try_join!(injecting, capturing).map_err(|(code, why)| (code, Json(json!({ "error": why }))).into_response())
38}
39
40/// The pane a shell call acts for: the caller's own, from its token or, without one, its signed identity, never a
41/// field of the request. `Err` is the refusal to send.
42pub(super) fn calling_pane(
43    state: &AppState,
44    caller: Option<&super::caller::Caller>,
45    auth: Option<&agentmux_common::api_types::UiAutomationAuth>,
46) -> Result<String, String> {
47    if let Some(uid) = caller.and_then(super::caller::Caller::uid) {
48        return crate::backend::reactive::handler::get_global_handler()
49            .block_for_uid(uid)
50            .ok_or_else(|| "this agent has no pane registered".to_string());
51    }
52    match auth {
53        Some(auth) => crate::server::ui_handlers::verified_block_id(state, caller, auth)
54            .map_err(|e| format!("could not verify which agent is asking: {e}")),
55        None => Err("a shell call needs the calling agent's token or signed identity, which this call did not carry".to_string()),
56    }
57}
58
59/// [`calling_pane`] for a request that also names a pane: the proven pane, or the response that refuses the call
60/// (the caller could not be proven, or the request names another pane).
61pub(super) fn own_pane(
62    state: &AppState,
63    caller: Option<&super::caller::Caller>,
64    named: &str,
65    auth: Option<&agentmux_common::api_types::UiAutomationAuth>,
66) -> Result<String, Response> {
67    let refuse = |why: &str| (StatusCode::FORBIDDEN, Json(json!({ "error": why }))).into_response();
68    let pane = calling_pane(state, caller, auth).map_err(|e| refuse(&e))?;
69    if !named.is_empty() && named != pane {
70        return Err(refuse("this request names another agent's pane: a shell call acts on your own pane, so use your own pane's shell, or message that agent"));
71    }
72    Ok(pane)
73}
74
75/// The refusal when `shell_id` is a shell another pane started; `None` for the caller's own shell, and for an id no
76/// shell holds (there is nothing there to act on).
77fn refuse_foreign_shell(state: &AppState, caller: Option<&super::caller::Caller>, shell_id: &str) -> Option<Response> {
78    let pane = match own_pane(state, caller, "", None) {
79        Ok(pane) => pane,
80        Err(refusal) => return Some(refusal),
81    };
82    let owner = state.shell_sessions.get_status(shell_id).block_id;
83    (!owner.is_empty() && owner != pane)
84        .then(|| (StatusCode::FORBIDDEN, Json(json!({ "error": "this shell belongs to another agent's pane: use your own pane's shell, or message that agent" }))).into_response())
85}
86
87/// `POST /api/v1/shell/create` — start a persistent background shell.
88///
89/// Called by `agentmux-mcp`'s `Shell` tool. Returns immediately with a
90/// `shell_id`; the `ShellNodeRunner` streams stdout/stderr to the frontend
91/// as `shell_chunk` MPS events without blocking the agent.
92pub(super) async fn handle_shell_create(
93    State(state): State<AppState>,
94    caller: Option<axum::Extension<super::caller::Caller>>,
95    Json(mut req): Json<ShellCreateRequest>,
96) -> Response {
97    match own_pane(&state, caller.as_deref(), &req.agent_block_id, req.auth.as_ref()) {
98        Ok(pane) => req.agent_block_id = pane,
99        Err(refusal) => return refusal,
100    }
101    create_shell(state, caller.as_deref(), req, None).await
102}
103
104/// A JSON `{ "error": .. }` reply with `status`.
105fn refuse(status: StatusCode, error: impl serde::Serialize) -> Response {
106    (status, Json(json!({ "error": error }))).into_response()
107}
108
109/// Where the command runs, and for an SSH host the agent that asked. Checked before anything is
110/// published, so a refused connection (no ssh, a distro that isn't installed, a bad name) fails the
111/// call with its reason instead of running the command here.
112async fn resolve_target(state: &AppState, req: &ShellCreateRequest) -> Result<(AgentTarget, String), Response> {
113    let target = connections::for_agent(&state.broker, req.connection.as_deref()).await.map_err(|e| refuse(StatusCode::BAD_REQUEST, e))?;
114    // An SSH host runs with the user's identity: their consent first (asked
115    // once, or remembered as "always"), then every ssh prompt goes to them
116    // through the askpass bridge, never to the agent.
117    let mut ssh_agent = String::new();
118    if let AgentTarget::Ssh(dest) = &target {
119        // Before anything is asked: with no askpass helper this cannot run, and
120        // consent (or an "always") given for it would be given for nothing.
121        if crate::backend::remote::askpass::program().is_none() {
122            let e = "this AgentMux has no askpass helper (agentmux-bashwrap) to run an agent's SSH command with";
123            return Err(refuse(StatusCode::BAD_REQUEST, e));
124        }
125        ssh_agent = connections::verified_agent(state, &req.agent_block_id, req.auth.as_ref()).map_err(|e| refuse(StatusCode::FORBIDDEN, e))?;
126        let connection = dest.name();
127        connections::consent_for_ssh(state, &req.agent_block_id, &ssh_agent, &connection, &req.cmd).await.map_err(|e| refuse(StatusCode::FORBIDDEN, e))?;
128    }
129    Ok((target, ssh_agent))
130}
131
132/// Where the command starts. If cwd wasn't supplied by the caller, fall back to the agent block's
133/// cmd:cwd — the working directory the agent pane was launched with. Without this, ShellNodeRunner
134/// would inherit agentmux-srv's cwd (typically the portable runtime/ dir) instead of the project dir.
135///
136/// In WSL or over SSH the cwd is a path on the other side, given as is, and the agent's own
137/// directory is no fallback for it: the remote home is. A local one is normalized before it reaches
138/// the spawner: agents on Windows run inside a bash shell and emit MSYS paths like
139/// `/c/Users/user/project`, which `Command::current_dir` rejects with os error 267
140/// (ERROR_DIRECTORY); this converts them to native form and expands `~`.
141fn effective_cwd(req: &ShellCreateRequest, agent_block: Option<&crate::backend::obj::Block>, remote: bool) -> Option<String> {
142    if remote {
143        return req.cwd.clone();
144    }
145    let block_cwd = || {
146        agent_block.and_then(|block| {
147            let cwd = crate::backend::obj::meta_get_string(&block.meta, "cmd:cwd", "");
148            if cwd.is_empty() { None } else { Some(cwd.to_string()) }
149        })
150    };
151    req.cwd.clone().or_else(block_cwd).and_then(|c| crate::backend::base::normalize_working_dir(&c))
152}
153
154/// Env parity with the agent CLI: start from the agent block's stored cmd:env (the per-agent env
155/// the agent process is launched with — same shape app_api/agent_io.rs / agent_handlers/input.rs
156/// read), then let the caller-supplied req.env override on top (explicit Shell env wins).
157///
158/// NOT forwarded here: the dynamic identity bindings (identity/resolver/inject.rs) and the bundled
159/// tools/bin PATH prefix that `build_persistent_spawn_env` (agent_handlers/input.rs) and
160/// blockcontroller/shell/lifecycle.rs inject at agent-CLI spawn time — those are resolved live per
161/// spawn, not stored in cmd:env. The MCP server (agentmux-mcp) is itself launched by the agent CLI
162/// through the bundled tools/bin, so tools it spawns inherit that PATH; shells created here run
163/// from agentmux-srv's env plus cmd:env + req.env.
164fn base_env(req: &ShellCreateRequest, agent_block: Option<&crate::backend::obj::Block>) -> std::collections::HashMap<String, String> {
165    let mut env = agent_block.map(|block| crate::backend::blockcontroller::cmd_env_of(&block.meta)).unwrap_or_default();
166    env.extend(req.env.iter().flatten().map(|(k, v)| (k.clone(), v.clone())));
167    env
168}
169
170/// What the Vault secrets given to the command leave for its runner to hold.
171struct SecretRuntime {
172    scrubber: Option<Arc<crate::backend::vault::scrub::Scrubber>>,
173    stdin_once: Option<zeroize::Zeroizing<String>>,
174    secret_dir: Option<crate::backend::vault::files::SecretDir>,
175}
176
177/// Puts the injected Vault values into `env` (after the caller's, so the agent can't name a value
178/// of its own over one) and their private files in a folder of their own, removed when the runner
179/// ends (or at the next start).
180fn apply_injected(
181    injected: Option<super::shell_secrets::Injected>,
182    env: &mut std::collections::HashMap<String, String>,
183    went_ahead: &mut Vec<String>,
184) -> Result<SecretRuntime, Response> {
185    let Some(i) = injected else {
186        return Ok(SecretRuntime { scrubber: None, stdin_once: None, secret_dir: None });
187    };
188    went_ahead.extend(i.went_ahead);
189    env.extend(i.env);
190    let mut secret_dir = None;
191    if !i.files.is_empty() {
192        let dir = crate::backend::vault::files::SecretDir::create().map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, e))?;
193        for (name, value) in &i.files {
194            let path = dir.write(name, value).map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, e))?;
195            env.insert(name.clone(), path.to_string_lossy().into_owned());
196        }
197        secret_dir = Some(dir);
198    }
199    Ok(SecretRuntime { scrubber: Some(Arc::new(i.scrubber)), stdin_once: i.stdin, secret_dir })
200}
201
202/// The program and arguments that run the command on the other side of a WSL or SSH `target`
203/// (`None` runs it here), and for SSH the askpass secret its prompts are answered through.
204fn launch_for(
205    state: &AppState,
206    req: &ShellCreateRequest,
207    target: &AgentTarget,
208    ssh_agent: &str,
209    env: &mut std::collections::HashMap<String, String>,
210    cwd_there: &str,
211) -> Result<(Option<(String, Vec<String>)>, Option<String>), Response> {
212    match target {
213        AgentTarget::Local => Ok((None, None)),
214        // WSL passes on only what WSLENV names: the caller's own variables and the gh guard, never
215        // the rest of the agent's env.
216        AgentTarget::Wsl(distro) => {
217            // Whether the distro has an identity of its own (a gh-agent there) is not known from
218            // here, and the guard above looked at this machine: keep the person's gh login from
219            // a shell in the distro, as every spawn did before the guard became conditional.
220            crate::backend::gh_guard::apply_gh_guard_in(env, &crate::backend::gh_guard::guard_config_home());
221            let caller_keys: Vec<String> = req.env.iter().flat_map(|e| e.keys().cloned()).collect();
222            let wslenv = shell_wslenv(&std::env::var("WSLENV").unwrap_or_default(), &caller_keys, env);
223            env.insert("WSLENV".to_string(), wslenv);
224            let args = crate::backend::remote::wsl::launch(distro, &req.cmd, &[], cwd_there).args;
225            Ok((Some(("wsl.exe".to_string(), args)), None))
226        }
227        AgentTarget::Ssh(dest) => {
228            use crate::backend::remote::{askpass, ssh};
229            let (Some(ssh_path), Some(askpass_program)) = (ssh::binary(), askpass::program()) else {
230                let e = "this AgentMux has no ssh or no askpass helper (agentmux-bashwrap) to run an agent's SSH command with";
231                return Err(refuse(StatusCode::BAD_REQUEST, e));
232            };
233            // Named from AgentMux's own record of the agent and host, never
234            // from the request, whose env the agent controls.
235            let secret = askpass::grant(askpass::AskpassGrant {
236                agent_block_id: req.agent_block_id.clone(),
237                agent: ssh_agent.to_string(),
238                connection: dest.name(),
239                user_pane: false,
240            });
241            let local_url = std::env::var("AGENTMUX_LOCAL_URL").unwrap_or_default();
242            env.extend(askpass::ssh_env(&secret, &askpass_program, &local_url, &state.auth_key));
243            let args = ssh::launch_exec(dest, &req.cmd, cwd_there, ssh::shared_control_dir().as_deref());
244            Ok((Some((ssh_path.to_string_lossy().into_owned(), args)), Some(secret)))
245        }
246    }
247}
248
249/// Starts a shell for `req`. `preapproved`: the person approved its secrets with a
250/// rotation (`Vault` `rotate`), which runs its commands through here.
251pub(super) async fn create_shell(
252    state: AppState, caller: Option<&super::caller::Caller>,
253    req: ShellCreateRequest,
254    preapproved: Option<&super::shell_secrets::Preapproved>,
255) -> Response {
256    let (target, ssh_agent) = match resolve_target(&state, &req).await {
257        Ok(resolved) => resolved,
258        Err(refused) => return refused,
259    };
260    let remote = !matches!(target, AgentTarget::Local);
261
262    // stdin is closed once a Vault value is written to it, so nothing can type there after.
263    if req.capture_stdin == Some(true) && req.stdin_secret.as_deref().is_some_and(|s| !s.trim().is_empty()) {
264        let e = "stdin_secret and capture_stdin can't be used together: stdin is closed once the value is written";
265        return refuse(StatusCode::BAD_REQUEST, e);
266    }
267    // Vault secrets for this command: the person is asked first, and the values go into this one process (its
268    // environment, stdin or private files, further down) and out of its output.
269    let (injected, (capture, mut went_ahead)) = match prepare_secrets(&state, caller, &req, remote, preapproved).await {
270        Ok(both) => both,
271        Err(refused) => return refused,
272    };
273    let shell_id = uuid::Uuid::new_v4().to_string();
274    let title = req.title.as_deref().unwrap_or(&req.cmd).to_string();
275
276    // Read the agent block once for both the cwd and env fallbacks.
277    let agent_block = state.mstore.get::<crate::backend::obj::Block>(&req.agent_block_id).ok().flatten();
278    let effective_cwd = effective_cwd(&req, agent_block.as_ref(), remote);
279    let mut effective_env = base_env(&req, agent_block.as_ref());
280    let secrets = match apply_injected(injected, &mut effective_env, &mut went_ahead) {
281        Ok(secrets) => secrets,
282        Err(refused) => return refused,
283    };
284    reserve_agent_env(&state.mstore, &req.agent_block_id, &mut effective_env);
285    let (launch, askpass_secret) = match launch_for(&state, &req, &target, &ssh_agent, &mut effective_env, effective_cwd.as_deref().unwrap_or_default()) {
286        Ok(launched) => launched,
287        Err(refused) => return refused,
288    };
289
290    tracing::info!(
291        block_id = %req.agent_block_id,
292        shell_id = %shell_id,
293        cmd = %req.cmd,
294        cwd = ?effective_cwd,
295        wsl = ?(if let AgentTarget::Wsl(distro) = &target { Some(distro) } else { None }),
296        ssh = matches!(target, AgentTarget::Ssh(_)),
297        "shell.create"
298    );
299
300    // Publish shell_node_create so the frontend inserts the row
301    // before the first chunk arrives (avoids a flash of orphaned chunks).
302    // persist: 64 — retain up to 64 shell_node_create events per block scope
303    // so multiple shells in a pane all replay on WS reconnect / pane remount.
304    // (persist: 1 meant only the last shell's create event was kept; earlier
305    // shells lost their create event while their shell_chunk events at
306    // persist: 1024 still replayed, causing the reducer to silently drop
307    // orphaned chunks.)
308    let created = crate::backend::shell_node::ShellNodeCreateEvent {
309        shell_id: shell_id.clone(),
310        cmd: req.cmd.clone(),
311        cwd: effective_cwd.clone(),
312        title: title.clone(),
313        timestamp: agentmux_common::time::now_ms_u64(),
314    };
315    state.broker.publish_event::<crate::backend::mps_events::ShellNodeCreate>(&created, vec![format!("block:{}", req.agent_block_id)], 64);
316
317    // Spawn the runner — fire-and-forget; events flow independently.
318    let runner = crate::backend::shell_node::ShellNodeRunner {
319        shell_id: shell_id.clone(),
320        block_id: req.agent_block_id,
321        cmd: req.cmd,
322        title,
323        cwd: if launch.is_some() { None } else { effective_cwd },
324        launch,
325        askpass_secret,
326        extra_env: effective_env,
327        broker: Arc::clone(&state.broker),
328        registry: Arc::clone(&state.shell_sessions),
329        capture_stdin: req.capture_stdin.unwrap_or(false),
330        scrubber: secrets.scrubber,
331        stdin_once: secrets.stdin_once,
332        secret_dir: secrets.secret_dir,
333        capture,
334    };
335    tokio::spawn(runner.run());
336
337    (StatusCode::OK, Json(ShellCreateResponse { shell_id, approval: super::vault_ask::approval(&went_ahead) })).into_response()
338}
339
340/// `POST /api/v1/shell/stop` — stop a running persistent shell.
341///
342/// Called by `agentmux-mcp`'s `ShellStop` tool. Tree-kills the shell's
343/// process group (so `task dev` → `task.exe`/`node` grandchildren die too),
344/// which makes the runner publish a `stopped` exit event. Returns `{ stopped }`
345/// — false if the id is unknown (never started or already exited).
346pub(super) async fn handle_shell_stop(
347    State(state): State<AppState>,
348    caller: Option<axum::Extension<super::caller::Caller>>,
349    Json(req): Json<ShellStopRequest>,
350) -> Response {
351    if let Some(refusal) = refuse_foreign_shell(&state, caller.as_deref(), &req.shell_id) {
352        return refusal;
353    }
354    let stopped = state.shell_sessions.stop(&req.shell_id);
355    tracing::info!(shell_id = %req.shell_id, stopped, "shell.stop");
356    (StatusCode::OK, Json(json!({ "stopped": stopped }))).into_response()
357}
358
359/// `POST /api/v1/shell/input` — write text to a running shell's stdin (Phase 3b).
360///
361/// Appends a newline so single answers like "y" work without the caller
362/// needing to know the line discipline. Returns `{ written: false }` if the
363/// shell is not running or the write fails (e.g. the process closed its stdin).
364pub(super) async fn handle_shell_input(
365    State(state): State<AppState>,
366    caller: Option<axum::Extension<super::caller::Caller>>,
367    Json(req): Json<ShellInputRequest>,
368) -> Response {
369    if let Some(refusal) = refuse_foreign_shell(&state, caller.as_deref(), &req.shell_id) {
370        return refusal;
371    }
372    // Non-blocking send to the stdin relay task — no mutex, no risk of
373    // blocking if the child's pipe buffer is full (the relay owns that concern).
374    // resolve_stdin distinguishes "not running" from "running but no captured
375    // stdin" so the caller gets an actionable reason instead of a bare false.
376    let (written, reason) = match state.shell_sessions.resolve_stdin(&req.shell_id) {
377        Ok(tx) => {
378            let mut text = req.text.clone();
379            if !text.ends_with('\n') {
380                text.push('\n');
381            }
382            if tx.send(text).is_ok() {
383                tracing::debug!(shell_id = %req.shell_id, "shell.input: written");
384                (true, None)
385            } else {
386                // Relay task gone / channel closed — process closed its stdin.
387                tracing::debug!(shell_id = %req.shell_id, "shell.input: write failed");
388                (false, Some(ShellInputFailure::WriteFailed))
389            }
390        }
391        Err(failure) => {
392            tracing::debug!(shell_id = %req.shell_id, ?failure, "shell.input: no target");
393            (false, Some(failure))
394        }
395    };
396    (StatusCode::OK, Json(ShellInputResponse { written, reason })).into_response()
397}
398
399/// `POST /api/v1/shell/status` — query a shell's running state (Phase 3b).
400///
401/// Returns `{ running, exit_code, line_count }`. If the shell_id is unknown
402/// (never started or never seen by this sidecar), `running` is false and
403/// `exit_code` is absent.
404pub(super) async fn handle_shell_status(
405    State(state): State<AppState>,
406    caller: Option<axum::Extension<super::caller::Caller>>,
407    Json(req): Json<ShellStatusRequest>,
408) -> Response {
409    if let Some(refusal) = refuse_foreign_shell(&state, caller.as_deref(), &req.shell_id) {
410        return refusal;
411    }
412    let s = state.shell_sessions.get_status(&req.shell_id);
413    (StatusCode::OK, Json(ShellStatusResponse {
414        running: s.running,
415        exit_code: s.exit_code,
416        line_count: s.line_count,
417    }))
418    .into_response()
419}
420
421/// `POST /api/v1/shell/output` - the cleaned output of a job that was given Vault
422/// secrets, to the agent whose pane started it (spec section 7.1). Any other job has
423/// no kept output, and another agent's pane is refused.
424pub(super) async fn handle_shell_output(
425    State(state): State<AppState>,
426    caller: Option<axum::Extension<super::caller::Caller>>,
427    Json(req): Json<agentmux_common::api_types::ShellOutputRequest>,
428) -> impl IntoResponse {
429    // The pane is the caller's own, from its signed identity: the instance key every agent
430    // holds proves nothing about which agent is asking.
431    let pane = match crate::server::ui_handlers::verified_block_id(&state, caller.as_deref(), &req.auth) {
432        Ok(p) => p,
433        Err(e) => return (StatusCode::FORBIDDEN, Json(json!({ "error": format!("could not verify which agent is asking: {e}") }))).into_response(),
434    };
435    let s = state.shell_sessions.get_status(&req.shell_id);
436    let (Some(tail), true) = (s.tail.as_ref(), s.block_id == pane) else {
437        let why = "no cleaned output is kept for this job: only a job given Vault secrets keeps it, and only for the pane that started it";
438        return (StatusCode::NOT_FOUND, Json(json!({ "error": why }))).into_response();
439    };
440    let lines: Vec<String> = tail.lock().iter().cloned().collect();
441    let truncated = s.line_count as usize > lines.len() || s.tail_clipped;
442    (
443        StatusCode::OK,
444        Json(agentmux_common::api_types::ShellOutputResponse {
445            running: s.running,
446            exit_code: s.exit_code,
447            output: lines.join("\n"),
448            truncated,
449            captured: s.captured.clone(),
450            withheld: s.withheld.clone(),
451        }),
452    )
453        .into_response()
454}
455
456// Meta key persisting which sub-block is "this pane's one shell" — the same
457// key the human-facing shell drawer uses: `agent-view.tsx` reads it into
458// `AgentShellDrawer`'s `shellSubBlockId` prop, and `AgentShellDrawer.tsx`'s
459// `onSubBlockCreated` handler writes it. `PtyShell` reuses this instead of
460// minting an independent, invisible shell: reusing it means the agent
461// drives the SAME shell a human sees in the drawer, and a drawer opened
462// later attaches to whatever the agent already started, live output and
463// scrollback included.
464pub(super) use crate::backend::blockcontroller::META_KEY_SHELL_SUBBLOCK_ID;
465
466// How long an agent's write (input/resize) locks the shell out from human
467// keyboard input, refreshed on every subsequent write. Deliberately a lease,
468// not an explicit lock/unlock pair: an explicit "release" call is one the
469// agent could simply never make (error, crash, forgetting), which would
470// leave a human locked out indefinitely — the opposite of "unlock as soon
471// as the agent stops." A short, self-expiring window means the frontend
472// needs no server push to release it either — it just compares the
473// timestamp against its own clock.
474pub(super) const AGENT_LOCK_WINDOW_MS: i64 = 4000;
475
476// Meta key holding the lock's absolute expiry (epoch ms). The frontend
477// gates human keyboard input purely on `Date.now() < this`, reactively —
478// no server-side timer to leak or get stuck; a quiet agent just lets the
479// timestamp lapse and control returns on its own.
480// pub(crate): `server::websocket`'s `controllerinput` handler also reads
481// this — see that handler's own doc comment for why.
482pub(crate) use crate::backend::blockcontroller::agent_lock::META_KEY_AGENT_LOCK_UNTIL;
483
484/// Whether `shell_id` is a real `view:"term"` sub-block PARENTED TO
485/// `agent_block_id` — the actual safety property Codex asked for (PR
486/// #3177): `shell_id` lives in the same block-id namespace as every other
487/// pane, and `Layout` exposes block ids for ordinary panes, so without this
488/// check an agent could point `PtyShellInput`/`PtyShellStop`/etc. at any
489/// controller-backed block (another agent's own CLI pane, a human's
490/// terminal pane) and inject input into it or tear it down. Framed as
491/// parentage rather than "did `PtyShell` create it" (the original,
492/// narrower check) specifically so it also covers the reuse case above: a
493/// shell the HUMAN created via the drawer is just as legitimate a target as
494/// one `PtyShell` created itself, as long as it's this agent's own pane.
495pub(super) fn is_owned_by_agent(
496    mstore: &crate::backend::storage::store::Store,
497    shell_id: &str,
498    agent_block_id: &str,
499) -> bool {
500    mstore
501        .get::<crate::backend::obj::Block>(shell_id)
502        .ok()
503        .flatten()
504        .map(|b| {
505            b.parentoref == format!("block:{agent_block_id}")
506                && b.meta.get("view").and_then(|v| v.as_str()) == Some("term")
507        })
508        .unwrap_or(false)
509}
510
511/// Merge `meta_update` into `block_id`'s meta and broadcast a
512/// `waveobj:update` WS event so every subscribed frontend (the drawer, if
513/// open) picks it up immediately — the same two steps the `setmeta` WS
514/// handler performs (`websocket.rs`'s `COMMAND_SET_META` handler), factored
515/// out since `ptyshell/*` needs the identical pattern from a plain HTTP
516/// handler with no `WshRpcEngine` in scope.
517pub(super) fn broadcast_meta_update(
518    state: &AppState,
519    block_id: &str,
520    meta_update: &crate::backend::obj::MetaMapType,
521) -> Result<(), String> {
522    let oref_str = format!("block:{block_id}");
523    crate::server::service::object_helpers::update_object_meta(&state.mstore, &oref_str, meta_update)?;
524    let block = state
525        .mstore
526        .must_get::<crate::backend::obj::Block>(block_id)
527        .map_err(|e| e.to_string())?;
528    let update = crate::backend::obj::MuxObjUpdate {
529        updatetype: "update".into(),
530        otype: "block".into(),
531        oid: block_id.to_string(),
532        obj: Some(crate::backend::obj::mux_obj_to_value(&block)),
533    };
534    state.event_bus.broadcast_event(&crate::backend::eventbus::EventBus::typed_ws_event::<crate::backend::mps_events::MuxObjUpdated>(&update, oref_str));
535    Ok(())
536}
537
538// ---------------------------------------------------------------------------
539// PTY shell handlers (docs/specs/SPEC_AGENT_INTERACTIVE_PTY_SHELL_API_2026_09_10.md)
540//
541// A REAL PTY, unlike the piped `/api/v1/shell/*` family above — for driving
542// genuinely interactive programs (Sharprompt-style wizards, `sudo`, `ssh`,
543// REPLs) that check for a real terminal and refuse or misbehave on a pipe.
544// Reuses `blockcontroller::shell` verbatim (the same controller backing the
545// `term` widget and `AgentShellSubblock.tsx`'s composer-drawer shell) —
546// this is a new agent-facing entry point onto existing PTY plumbing, not a
547// new PTY implementation.
548//
549// Every handler here is a plain HTTP call with no WS/tab dependency, same as
550// `handle_shell_create` above — deliberately NOT wired through the
551// `WshRpcEngine` that `createsubblock`/`controllerresync`/`controllerinput`
552// use (those are instantiated per-WebSocket-connection, so they exist only
553// while a frontend tab is connected). An agent calling these tools gets a
554// live, fully functional PTY regardless of whether any window is open,
555// focused, or rendering the shell's `term` sub-block at all.
556// ---------------------------------------------------------------------------
557
558/// Shared by both the top-level reuse check and the "lost the atomic
559/// claim" fallback in `handle_pty_shell_create`: resync `id`'s controller
560/// and reply, or return `None` if `id` doesn't resolve to a real block
561/// (stale pointer), OR if its shell has already exited, so the caller
562/// falls through to creating a fresh one. A pane has one agent shell: asking
563/// for it, while it runs, on another connection than its own is refused (409),
564/// not answered with the shell on the wrong machine. An exited one is replaced
565/// whatever its connection was.
566pub(super) async fn try_attach_to_existing_shell(
567    state: &AppState,
568    agent_block_id: &str,
569    id: &str,
570    connection: &str,
571) -> Option<axum::response::Response> {
572    let block = state.mstore.get::<crate::backend::obj::Block>(id).ok().flatten()?;
573
574    if let Some(conflict) = connection_conflict(&block, connection) {
575        if let std::ops::ControlFlow::Break(answer) = settle_connection_conflict(state, agent_block_id, id, &block, conflict) {
576            return answer;
577        }
578    }
579
580    // Baseline BEFORE resync — see `answer_conpty_handshake_if_seen`'s doc
581    // comment (Codex P1 on PR #3194) for why this matters: the `term` file
582    // is append-only for the block's whole lifetime, so an already-running
583    // reused shell's history almost certainly still contains its own old,
584    // long-since-answered `ESC[6n` from whenever it first started.
585    let baseline_len = state
586        .filestore
587        .stat(id, "term")
588        .ok()
589        .flatten()
590        .map(|info| info.size as usize)
591        .unwrap_or(0);
592
593    if let Err(e) = resync_existing_shell(state, &block) {
594        if e == blockcontroller::RESYNC_ERR_ALREADY_EXITED {
595            drop_exited_shell(state, agent_block_id, id);
596            return None;
597        }
598        return Some(
599            (
600                StatusCode::INTERNAL_SERVER_ERROR,
601                Json(json!({ "error": format!("ptyshell.create: resync existing shell: {e}") })),
602            )
603                .into_response(),
604        );
605    }
606    // A shell that started or changed connection between the check above and
607    // the resync (a concurrent caller) is still not handed out on the wrong one.
608    if let Some(conflict) = connection_conflict(&block, connection) {
609        return Some(conflict);
610    }
611    answer_conpty_handshake_if_seen(state, id, baseline_len).await;
612    tracing::info!(block_id = %id, parent_id = %agent_block_id, "ptyshell.create: reused");
613    Some((StatusCode::OK, Json(PtyShellCreateResponse { shell_id: id.to_string() })).into_response())
614}
615
616/// Settled before the resync, which would otherwise start a shell on the
617/// block's own connection: a running shell on another connection is refused
618/// and left as it is, and so is one this srv run created and is still
619/// starting (a concurrent create won the claim). One with no controller from
620/// an earlier run (before a srv restart) is replaced, like an exited one,
621/// rather than revived on the old connection. An exited one is replaced
622/// whatever its connection was.
623///
624/// `Break(Some(conflict))` refuses, `Break(None)` falls through to a fresh shell, `Continue` goes on to the resync.
625fn settle_connection_conflict(
626    state: &AppState,
627    agent_block_id: &str,
628    id: &str,
629    block: &crate::backend::obj::Block,
630    conflict: axum::response::Response,
631) -> std::ops::ControlFlow<Option<axum::response::Response>> {
632    use std::ops::ControlFlow;
633    let created_this_run = crate::backend::obj::meta_get_string(&block.meta, META_KEY_PTYSHELL_BOOT_ID, "") == *state.boot_id;
634    match blockcontroller::get_block_controller_status(id) {
635        Some(s) if s.shellprocstatus == blockcontroller::STATUS_RUNNING => ControlFlow::Break(Some(conflict)),
636        None if created_this_run => ControlFlow::Break(Some(conflict)),
637        None => {
638            clear_shell_pointer_if(state, agent_block_id, id);
639            tracing::info!(
640                block_id = %id,
641                parent_id = %agent_block_id,
642                "ptyshell.create: pane's shell is not running and was on another connection — falling through to a fresh shell"
643            );
644            ControlFlow::Break(None)
645        }
646        Some(_) => ControlFlow::Continue(()),
647    }
648}
649
650fn resync_existing_shell(state: &AppState, block: &crate::backend::obj::Block) -> Result<(), String> {
651    let registry = state.mstore.shared_agent_registry();
652    blockcontroller::resync_controller(
653        block,
654        "ptyshell",
655        None,
656        false,
657        // respawn_if_done=false: don't resurrect a shell that already
658        // exited (e.g. the human typed `exit`). The unconditional-respawn
659        // default is correct for crash/backend-restart recovery
660        // (`TermResyncHandler` on the WS path) but wrong here: every
661        // subsequent `PtyShellCreate` against this same pane-shell pointer
662        // would otherwise silently respawn it again, each respawn
663        // appending a fresh shell-startup banner to the pane's
664        // append-only `term` scrollback — indistinguishable from the
665        // exited shell's output looping forever. Checked inside
666        // `resync_controller` itself (one status read, not a separate
667        // check-then-call here) so a shell that exits in the gap between
668        // an earlier check and this call can't slip through and get
669        // respawned anyway (Codex P2 on PR #3225) — see that parameter's
670        // own doc comment.
671        false,
672        Some(Arc::clone(&state.broker)),
673        Some(Arc::clone(&state.event_bus)),
674        Some(Arc::clone(&state.mstore)),
675        Some(Arc::clone(&state.filestore)),
676        Some(Arc::clone(&state.id_store)),
677        Some(Arc::clone(&state.identity_store)),
678        registry,
679        state.boot_id.clone(),
680        &state.auth_key,
681        Some(Arc::clone(&state.config_watcher)),
682    )
683    .map(|_| ())
684    .map_err(|e| e.to_string())
685}
686
687/// Treating an exited shell like a stale pointer (the caller returns
688/// `None`) reuses the existing "create a fresh one" fallback in
689/// both callers instead of inventing a new response shape.
690///
691/// Also clear the now-stale pointer on the agent's own block:
692/// without this, two concurrent `PtyShellCreate` calls against
693/// the same exited pane would both fall through to
694/// `handle_pty_shell_create`'s atomic-claim transaction, both
695/// read the SAME still-set dead pointer, both take the "lost
696/// the race, reuse THEIRS" branch pointing at that same dead
697/// id, both find it exited too, and both independently execute
698/// the non-transactional "vanished, create for real" fallback —
699/// leaving one orphaned live controller and two callers holding
700/// different shell_ids for what's supposed to be one pane's one
701/// shell (Codex P2 on PR #3225). Clearing the pointer first
702/// makes the already-correct atomic claim transaction see
703/// "unclaimed" instead of "claimed by a dead id," so its
704/// existing single-writer serialization (documented on that
705/// transaction) resolves concurrent callers to one winner the
706/// normal way.
707///
708/// GUARDED, not unconditional (ReAgent P1 on this PR, round 2):
709/// `resync_controller`'s STATUS_DONE read happens outside
710/// any lock — a concurrent resync with `respawn_if_done=true`
711/// (e.g. the WS `ControllerResyncCommand`/`TermResyncHandler`
712/// path, which always revives a `STATUS_DONE` controller in
713/// place) can respawn THIS SAME shell in the gap between that
714/// read and this clear. Nulling the pointer unconditionally
715/// would then wipe a pointer that's valid again, orphaning a
716/// live, correctly-pointed shell — exactly the one-shell-per-
717/// pane invariant this PR exists to protect. Re-read the parent
718/// fresh and only clear if its pointer still names `id`, the
719/// same compare-before-clear pattern this file already uses a
720/// few hundred lines down for the identical class of race (see
721/// the `parent.meta.get(META_KEY_SHELL_SUBBLOCK_ID) ==
722/// Some(child_id.as_str())` guard in the spawn-failure rollback
723/// path). Not fully transactional (same as that existing
724/// pattern) — a failed/skipped clear just costs one more round
725/// trip through the fallback chain, not correctness.
726fn drop_exited_shell(state: &AppState, agent_block_id: &str, id: &str) {
727    clear_shell_pointer_if(state, agent_block_id, id);
728    tracing::info!(
729        block_id = %id,
730        parent_id = %agent_block_id,
731        "ptyshell.create: pane's shell already exited, not respawning — falling through to a fresh shell"
732    );
733}
734
735/// Block meta on a `PtyShell` block: the srv boot id of the run that created it.
736pub(super) const META_KEY_PTYSHELL_BOOT_ID: &str = "ptyshell:bootid";
737
738/// Clear the agent block's shell pointer, if it still names `id` (see the
739/// exited-shell branch of `try_attach_to_existing_shell` for why it is
740/// compare-before-clear), so the next create claims a fresh shell.
741fn clear_shell_pointer_if(state: &AppState, agent_block_id: &str, id: &str) {
742    if let Ok(mut parent) = state.mstore.must_get::<crate::backend::obj::Block>(agent_block_id) {
743        if parent.meta.get(META_KEY_SHELL_SUBBLOCK_ID).and_then(|v| v.as_str()) == Some(id) {
744            parent.meta.insert(META_KEY_SHELL_SUBBLOCK_ID.to_string(), serde_json::Value::Null);
745            if state.mstore.update(&mut parent).is_ok() {
746                let update = crate::backend::obj::MuxObjUpdate {
747                    updatetype: "update".into(),
748                    otype: "block".into(),
749                    oid: agent_block_id.to_string(),
750                    obj: Some(crate::backend::obj::mux_obj_to_value(&parent)),
751                };
752                state.event_bus.broadcast_event(&crate::backend::eventbus::EventBus::typed_ws_event::<crate::backend::mps_events::MuxObjUpdated>(&update, format!("block:{agent_block_id}")));
753            }
754        }
755    }
756}
757
758/// 409 when the pane's running shell is on another connection than `wanted`.
759/// PtyShellStop releases the keyboard lock and leaves the shell running, so
760/// ending the shell is the way to switch.
761pub(super) fn connection_conflict(
762    shell_block: &crate::backend::obj::Block,
763    wanted: &str,
764) -> Option<axum::response::Response> {
765    let running_on = crate::backend::obj::meta_get_string(
766        &shell_block.meta,
767        blockcontroller::META_KEY_CONNECTION,
768        "local",
769    );
770    if crate::backend::remote::conn::same_connection(&running_on, wanted) {
771        // An SSH shell the user opened (not started for an agent) has an ssh
772        // that asks for passwords and host keys in its own terminal, which an
773        // agent reads and types into: it is never shared with an agent.
774        let ssh = matches!(
775            crate::backend::remote::ConnTarget::parse(&running_on),
776            Ok(crate::backend::remote::ConnTarget::Ssh(_))
777        );
778        let for_an_agent = !crate::backend::obj::meta_get_string(
779            &shell_block.meta,
780            crate::backend::remote::askpass::META_KEY_AGENT_BLOCK,
781            "",
782        )
783        .is_empty();
784        if ssh && !for_an_agent {
785            let error = format!(
786                "this pane's shell on '{running_on}' was opened by the user, and its ssh may ask for a \
787                 password in it, so an agent cannot share it. Use Terminal with action \"run\" and background: true instead, or ask the user to close it."
788            );
789            return Some((StatusCode::CONFLICT, Json(json!({ "error": error }))).into_response());
790        }
791        return None;
792    }
793    let error = format!(
794        "this pane's shell is running on '{running_on}', not '{wanted}'. \
795         End it with Terminal action \"type\" (text \"exit\", submit: true) and open it again, \
796         or open it with connection '{running_on}' to use it"
797    );
798    Some((StatusCode::CONFLICT, Json(json!({ "error": error }))).into_response())
799}
800
801/// The values a Shell command's env takes from the server, applied after
802/// the request's `env` and the injected secrets so neither can set them: the
803/// agent's current identity over a persisted or requested one, as its own
804/// spawn has it (`identity_env`), the plain-`gh` guard the agent itself gets,
805/// and no account cloud login.
806fn reserve_agent_env(
807    mstore: &crate::backend::storage::store::Store,
808    agent_block_id: &str,
809    env: &mut std::collections::HashMap<String, String>,
810) {
811    crate::server::agent_handlers::identity_env::carry_block_slug_identity_env(mstore, agent_block_id, env);
812    crate::backend::gh_guard::apply_gh_guard(env);
813    if let Some(block) = mstore.get::<crate::backend::obj::Block>(agent_block_id).ok().flatten() {
814        crate::backend::git_program_settings::apply_for_spawn(env, &block.meta);
815    }
816    crate::backend::account_login_guard::strip_account_login(env);
817}
818
819/// `WSLENV` for a Shell command in a distro: the caller's own variables and
820/// the reserved identity [`reserve_agent_env`] set, so the command names the
821/// agent there as it would on Windows (`wsl::AGENT_IDENTITY_ENV`).
822fn shell_wslenv(existing: &str, caller_keys: &[String], env: &std::collections::HashMap<String, String>) -> String {
823    let identity = crate::backend::remote::wsl::AGENT_IDENTITY_ENV.into_iter().filter(|k| env.contains_key(*k));
824    crate::backend::remote::wsl::wslenv_with(existing, caller_keys.iter().map(String::as_str).chain(identity))
825}
826
827#[cfg(test)]
828mod reserved_env_tests {
829    /// The reserved identity crosses into a distro beside the caller's own
830    /// variables; `GH_CONFIG_DIR` as a translated path; a key the env lacks
831    /// isn't listed.
832    #[test]
833    fn the_reserved_identity_crosses_into_wsl() {
834        let env: std::collections::HashMap<String, String> =
835            ["AGENTMUX_AGENT_ID", "AGENTMUX_AGENT_SLUG", "MUXBUS_AGENT_ID", "GIT_AUTHOR_EMAIL"]
836                .into_iter()
837                .map(|k| (k.to_string(), "loap-3".to_string()))
838                .collect();
839        let wslenv = super::shell_wslenv("", &["MY_VAR".to_string()], &env);
840        let names: Vec<&str> = wslenv.split(':').collect();
841        for key in ["MY_VAR", "AGENTMUX_AGENT_ID", "AGENTMUX_AGENT_SLUG", "MUXBUS_AGENT_ID", "GIT_AUTHOR_EMAIL", "GH_CONFIG_DIR/p"] {
842            assert!(names.contains(&key), "{key} in {wslenv}");
843        }
844        assert!(!names.contains(&"GIT_COMMITTER_NAME"), "{wslenv}");
845        assert!(!wslenv.contains("AGENTMUX_AUTH_KEY"), "{wslenv}");
846    }
847
848    /// A request carrying the agent's old id (and its slug, MuxBus id, git
849    /// email) ends with the definition's: the reserved values are applied
850    /// last.
851    #[test]
852    fn a_request_env_cannot_put_back_an_old_identity() {
853        use crate::backend::storage::store::Store;
854        let store = Store::open_in_memory().unwrap();
855        let mut def = crate::backend::storage::agents::test_agent_def("uid-shell", "Loap #3", "claude", "host", 1, "");
856        def.slug = "loap-3".to_string();
857        store.agent_def_insert(&mut def).unwrap();
858        let mut meta = crate::backend::obj::MetaMapType::new();
859        meta.insert("view".to_string(), serde_json::json!("agent"));
860        meta.insert("agentId".to_string(), serde_json::json!("uid-shell"));
861        let mut block = crate::backend::obj::Block { oid: "block-shell".to_string(), meta, ..Default::default() };
862        store.insert(&mut block).unwrap();
863
864        let old = "loap-loap-2-loap-3";
865        let mut env: std::collections::HashMap<String, String> = [
866            ("AGENTMUX_AGENT_ID", old),
867            ("AGENTMUX_AGENT_SLUG", old),
868            ("MUXBUS_AGENT_ID", old),
869            ("GIT_AUTHOR_EMAIL", "loap-loap-2-loap-3@agents.local"),
870        ]
871        .into_iter()
872        .map(|(k, v)| (k.to_string(), v.to_string()))
873        .collect();
874        super::reserve_agent_env(&store, "block-shell", &mut env);
875        for key in ["AGENTMUX_AGENT_ID", "AGENTMUX_AGENT_SLUG", "MUXBUS_AGENT_ID"] {
876            assert_eq!(env[key], "loap-3", "{key}");
877        }
878        assert_eq!(env["GIT_AUTHOR_EMAIL"], "loap-3@agents.local");
879        assert!(env["GH_CONFIG_DIR"].ends_with("gh-loap-3"));
880    }
881
882    /// A command an agent runs in a folder a container agent can write has git settings that run nothing of the
883    /// folder's own configuration; a command of an agent in any other folder has none added.
884    #[test]
885    fn a_shell_command_in_a_shared_folder_has_git_that_runs_nothing_the_folder_names() {
886        use crate::backend::storage::store::Store;
887        let (data, shared, plain) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
888        crate::backend::mcp_config_file::with_data_home(data.path(), || {
889            crate::backend::mcp_folder_rule::mark(&shared.path().to_string_lossy());
890            let store = Store::open_in_memory().unwrap();
891            for (id, folder) in [("block-shared", shared.path()), ("block-plain", plain.path())] {
892                let mut meta = crate::backend::obj::MetaMapType::new();
893                meta.insert("view".to_string(), serde_json::json!("agent"));
894                meta.insert("agentMode".to_string(), serde_json::json!("host"));
895                meta.insert("cmd:cwd".to_string(), serde_json::json!(folder.to_string_lossy()));
896                let mut block = crate::backend::obj::Block { oid: id.to_string(), meta, ..Default::default() };
897                store.insert(&mut block).unwrap();
898            }
899            let given = |block: &str| {
900                let mut env = std::collections::HashMap::new();
901                super::reserve_agent_env(&store, block, &mut env);
902                env
903            };
904            let shared_env = given("block-shared");
905            assert!(shared_env.values().any(|v| v == "core.fsmonitor"), "{shared_env:?}");
906            assert_eq!(shared_env.get("GIT_PROXY_COMMAND").map(String::as_str), Some(""));
907            let plain_env = given("block-plain");
908            assert!(!plain_env.values().any(|v| v == "core.fsmonitor") && !plain_env.contains_key("GIT_PROXY_COMMAND"), "{plain_env:?}");
909        });
910    }
911}
912
913#[cfg(test)]
914mod shared_shell_tests {
915    use super::connection_conflict;
916
917    fn shell(conn: &str, for_agent: bool) -> crate::backend::obj::Block {
918        let mut b = crate::backend::obj::Block::default();
919        b.meta.insert("connection".into(), serde_json::json!(conn));
920        if for_agent {
921            b.meta.insert(
922                crate::backend::remote::askpass::META_KEY_AGENT_BLOCK.into(),
923                serde_json::json!("agent-pane"),
924            );
925        }
926        b
927    }
928
929    /// The user's own SSH shell (its ssh prompts in its terminal) is never
930    /// handed to an agent; one started for an agent, or a local one, is.
931    #[test]
932    fn an_agent_never_shares_the_users_own_ssh_shell() {
933        assert!(connection_conflict(&shell("area54", false), "area54").is_some());
934        assert!(connection_conflict(&shell("area54", true), "area54").is_none());
935        assert!(connection_conflict(&shell("local", false), "local").is_none());
936        assert!(connection_conflict(&shell("wsl://Ubuntu", false), "wsl://Ubuntu").is_none());
937        assert!(connection_conflict(&shell("area54", true), "local").is_some(), "another connection");
938    }
939}
940
941#[cfg(test)]
942#[path = "http_shell_create_tests.rs"]
943mod create_tests;