Skip to main content

agentmux_srv/server/
http_pty_shell.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! PTY shell HTTP handlers.
5//! Split out of server/mod.rs unchanged (SPEC_LARGE_FILE_MODULE_ANALYSIS_2026_09_30.md §4.1).
6
7use super::*;
8
9/// A `ptyshell` handler that acts for the caller's own pane: the pane comes from the caller's token (or signed
10/// identity), a pane named in the request that differs is refused, and the rest of the handler runs on the proven one.
11macro_rules! own_pane_handler {
12    ($name:ident, $inner:ident, $req:ty) => {
13        pub(super) async fn $name(
14            State(state): State<AppState>,
15            caller: Option<axum::Extension<super::caller::Caller>>,
16            Json(mut req): Json<$req>,
17        ) -> axum::response::Response {
18            match own_pane(&state, caller.as_deref(), &req.agent_block_id, None) {
19                Ok(pane) => {
20                    req.agent_block_id = pane;
21                    $inner(State(state), Json(req)).await.into_response()
22                }
23                Err(refusal) => refusal,
24            }
25        }
26    };
27}
28own_pane_handler!(handle_pty_shell_input, pty_shell_input, PtyShellInputRequest);
29own_pane_handler!(handle_pty_shell_resize, pty_shell_resize, PtyShellResizeRequest);
30own_pane_handler!(handle_pty_shell_read, pty_shell_read, PtyShellReadRequest);
31own_pane_handler!(handle_pty_shell_status, pty_shell_status, PtyShellStatusRequest);
32own_pane_handler!(handle_pty_shell_stop, pty_shell_stop, PtyShellStopRequest);
33
34/// `POST /api/v1/ptyshell/create` — attach to (creating if needed) "this
35/// pane's one shell."
36///
37/// Reuses the same sub-block a human's composer-drawer shell already uses
38/// or will use (`META_KEY_SHELL_SUBBLOCK_ID`), in either direction: if the
39/// human already opened the drawer, the agent joins that exact PTY — same
40/// scrollback, same live output. If nothing exists yet, this creates it
41/// (the same `view: "term", controller: "shell"` headless-sub-block shape
42/// `createsubblock`'s WS handler builds for `AgentShellSubblock.tsx`) and
43/// persists the pointer, so a drawer opened *afterward* attaches to what
44/// the agent already started instead of spawning a second, independent
45/// shell. Either way, `resync_controller` runs before returning — unlike
46/// the WS path (which waits for a frontend to mount a `term` view and call
47/// `ControllerResyncCommand`), the PTY is live the moment this call
48/// returns; a UI viewer for it is optional, not a prerequisite.
49pub(super) async fn handle_pty_shell_create(
50    State(state): State<AppState>,
51    caller: Option<axum::Extension<super::caller::Caller>>,
52    Json(mut req): Json<PtyShellCreateRequest>,
53) -> axum::response::Response {
54    match own_pane(&state, caller.as_deref(), &req.agent_block_id, req.auth.as_ref()) {
55        Ok(pane) => req.agent_block_id = pane,
56        Err(refusal) => return refusal,
57    }
58    match create_steps::create_pty_shell(&state, &req).await {
59        Ok(resp) | Err(resp) => resp,
60    }
61}
62
63/// Answer Windows ConPTY's own startup handshake, if seen, before the
64/// caller proceeds. Discovered live (not assumed): the moment a Windows
65/// ConPTY is created, it queries the cursor position (`ESC[6n`, Device
66/// Status Report) and blocks its own internal state — and therefore every
67/// later write — until it sees a `ESC[<row>;<col>R` reply. A human-facing
68/// `term` pane gets this for free because xterm.js, running in the
69/// browser, answers real cursor queries as part of being an actual
70/// terminal emulator; this headless facility has nothing playing that
71/// role, so without this the PTY would sit permanently stuck before
72/// printing even its first prompt — confirmed by a live round trip that
73/// hung indefinitely until this was added. `ESC[1;1R` (cursor at row 1,
74/// col 1) is a plausible-enough fixed answer: nothing here has rendered
75/// anything yet, so "top-left" is as true as any other coordinate, and
76/// ConPTY only wants to reconcile its internal buffer, not validate the
77/// value against anything a person would see.
78///
79/// `baseline_len` MUST be the "term" file's byte length taken immediately
80/// before `resync_controller` ran (0 for a genuinely new block) — see the
81/// call sites. Only bytes appended AFTER that offset are ever inspected.
82/// **Not** safe to scan the whole file regardless of reuse/fresh (an
83/// earlier version of this function did exactly that): the "term" file is
84/// append-only for the block's entire lifetime
85/// (`handle_append_block_file`'s `FILE_OP_APPEND`), so a long-running
86/// reused shell's history almost always still contains its own original,
87/// long-since-answered `ESC[6n` from whenever it first started — matching
88/// against that stale byte sequence would inject an unsolicited
89/// `ESC[1;1R` into whatever a human is doing RIGHT NOW on that shell
90/// (Codex P1 on PR #3194, confirmed live before this fix: `create` on an
91/// already-running reused shell always found the old query and misfired).
92/// The baseline makes every case correct uniformly: nothing new appears
93/// (the common reuse case) → correctly finds nothing; `resync_controller`
94/// had to respawn a dead process → correctly sees only ITS fresh query,
95/// never anything from the block's former life.
96#[cfg_attr(not(windows), allow(unused_variables))]
97pub(super) async fn answer_conpty_handshake_if_seen(state: &AppState, block_id: &str, baseline_len: usize) {
98    #[cfg(windows)]
99    {
100        let mut answered = false;
101        for _ in 0..20 {
102            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
103            let saw_dsr = state
104                .filestore
105                .read_file(block_id, "term")
106                .ok()
107                .flatten()
108                .map(|bytes| {
109                    let new_bytes = bytes.get(baseline_len..).unwrap_or(&[]);
110                    new_bytes.windows(4).any(|w| w == b"\x1b[6n")
111                })
112                .unwrap_or(false);
113            if saw_dsr {
114                let _ = blockcontroller::send_input(
115                    block_id,
116                    blockcontroller::BlockInputUnion::data(b"\x1b[1;1R".to_vec()),
117                    None,
118                );
119                answered = true;
120                break;
121            }
122        }
123        tracing::info!(block_id = %block_id, answered_dsr = answered, "ptyshell: ConPTY handshake check");
124    }
125}
126
127/// `POST /api/v1/ptyshell/input` — write raw text to the PTY, as if typed.
128/// Unlike `/api/v1/shell/input`, no newline is appended: a real terminal
129/// doesn't add one either, and PTY programs (readline, Sharprompt) expect
130/// the caller to send exactly what a keyboard would (e.g. `"y\n"` to answer
131/// a prompt and press Enter, or `"\x03"` for Ctrl+C — the OS PTY layer
132/// translates that raw byte into a real interrupt delivered to the
133/// foreground process, same as a human pressing Ctrl+C in a real terminal,
134/// without ending the shell).
135///
136/// There is deliberately no separate "send a signal" endpoint: an earlier
137/// version of this API had one (`PtyShellSignal`, `BlockInputUnion::signal`),
138/// removed after Codex correctly flagged (PR #3177) that
139/// `ShellController`'s input loop treats ANY signal as "close the PTY" —
140/// `if input.sig_name.is_some() { break; }` in
141/// `blockcontroller/shell/lifecycle.rs` — so it terminated the whole shell
142/// instead of interrupting just the foreground command, the opposite of
143/// what it advertised. Real signal delivery through a PTY is the raw
144/// control byte, handled here, not a separate primitive.
145async fn pty_shell_input(
146    State(state): State<AppState>,
147    Json(req): Json<PtyShellInputRequest>,
148) -> impl IntoResponse {
149    if !is_owned_by_agent(&state.mstore, &req.shell_id, &req.agent_block_id) {
150        return (
151            StatusCode::OK,
152            Json(PtyShellInputResponse {
153                written: false,
154                error: Some("not a shell belonging to this agent's own pane".to_string()),
155            }),
156        );
157    }
158    // Lock BEFORE writing, not after (ReAgent P1 on PR #3194): the
159    // previous ordering left `term:agentlockuntil` unset for the entire
160    // duration of `send_input` — the exact window `controllerinput`'s own
161    // lock check (added for Codex's earlier P1 on this same PR) needs the
162    // lock to already exist to catch anything. Locking first doesn't make
163    // the race provably impossible (a human keystroke processed in the
164    // sliver of time before this write actually commits could still slip
165    // through — true elimination would need a real mutex shared between
166    // this HTTP path and the WS `controllerinput` path, disproportionate
167    // machinery for a UX-level collision guard, not a hard security
168    // boundary), but it shrinks the window from "all of send_input's own
169    // duration plus the lock write's" down to just the lock write's own
170    // commit latency — the actual, meaningful fix here.
171    lock_shell_for_agent(&state, &req.shell_id);
172    let result = blockcontroller::send_input(
173        &req.shell_id,
174        blockcontroller::BlockInputUnion::data(req.text.into_bytes()),
175        None,
176    );
177    match result {
178        Ok(()) => (StatusCode::OK, Json(PtyShellInputResponse { written: true, error: None })),
179        Err(e) => (StatusCode::OK, Json(PtyShellInputResponse { written: false, error: Some(e) })),
180    }
181}
182
183/// Lock `shell_id` out from human keyboard input for `AGENT_LOCK_WINDOW_MS`
184/// from now — called BEFORE every agent write (input/resize), not after
185/// (see the call sites' own comment for why the ordering matters).
186/// Best-effort: a failure to write the lock meta just means the human's
187/// input isn't blocked this time, not that the agent's write itself failed.
188pub(super) fn lock_shell_for_agent(state: &AppState, shell_id: &str) {
189    let until_ms = agentmux_common::time::now_ms() + AGENT_LOCK_WINDOW_MS;
190
191    // In-memory first, and unconditionally: this is what `controllerinput`
192    // actually enforces against (see `blockcontroller::agent_lock`'s module
193    // doc for why the enforcement path can't afford a `Store` read). It
194    // cannot fail and costs a hash insert, so the lock is live before the
195    // persisted/broadcast half is even attempted — which also shrinks the
196    // pre-existing "human keystroke in the sliver before the write commits"
197    // window described above to the width of a mutex acquire.
198    blockcontroller::agent_lock::lock_until(shell_id, until_ms);
199
200    // Then the meta write, which drives the frontend's own badge + gate
201    // (`AgentShellSubblock.tsx`). Best-effort, exactly as before: a failure
202    // here costs the human the "Agent is using this shell" indicator, not
203    // the enforcement itself.
204    let mut meta = crate::backend::obj::MetaMapType::new();
205    meta.insert(META_KEY_AGENT_LOCK_UNTIL.to_string(), json!(until_ms));
206    if let Err(e) = broadcast_meta_update(state, shell_id, &meta) {
207        tracing::warn!(shell_id = %shell_id, error = %e, "ptyshell: failed to write agent lock");
208    }
209}
210
211/// `POST /api/v1/ptyshell/resize` — resize the PTY. Some TUIs render
212/// differently or wrap badly at the fallback geometry (25x200).
213async fn pty_shell_resize(
214    State(state): State<AppState>,
215    Json(req): Json<PtyShellResizeRequest>,
216) -> impl IntoResponse {
217    if !is_owned_by_agent(&state.mstore, &req.shell_id, &req.agent_block_id) {
218        return (
219            StatusCode::OK,
220            Json(PtyShellResizeResponse {
221                resized: false,
222                error: Some("not a shell belonging to this agent's own pane".to_string()),
223            }),
224        );
225    }
226    // Lock BEFORE writing — see the identical comment in
227    // `handle_pty_shell_input` for why the ordering matters.
228    lock_shell_for_agent(&state, &req.shell_id);
229    let result = blockcontroller::send_input(
230        &req.shell_id,
231        blockcontroller::BlockInputUnion::resize(crate::backend::obj::TermSize {
232            rows: req.rows as i64,
233            cols: req.cols as i64,
234        }),
235        None,
236    );
237    match result {
238        Ok(()) => (StatusCode::OK, Json(PtyShellResizeResponse { resized: true, error: None })),
239        Err(e) => (StatusCode::OK, Json(PtyShellResizeResponse { resized: false, error: Some(e) })),
240    }
241}
242
243/// `POST /api/v1/ptyshell/read` — read back the shell's raw output tail.
244///
245/// Reads the block's `term` file straight from `FileStore` — the same file
246/// `blockcontroller::shell::lifecycle`'s real PTY read loop write-throughs
247/// to (`handle_append_block_file(..., "term", ..., filestore, ...)`,
248/// `SPEC_TERMINAL_SCROLLBACK_PERSISTENCE_2026_07_23.md` §2.1). Deliberately
249/// NOT the optimized `blockfile:read_range` path (byte-offset index,
250/// cross-channel global-transcript fallback, and a different filename —
251/// "output" — used for agent CLI transcripts, a different content stream
252/// entirely), which solves problems this endpoint doesn't have: a PTY shell
253/// created through this API is always local and short-lived, so a plain
254/// whole-file read + in-memory tail is simpler and correct. This is a raw
255/// line log, not a rendered-screen snapshot — see the type's own doc
256/// comment in `api_types.rs`.
257async fn pty_shell_read(
258    State(state): State<AppState>,
259    Json(req): Json<PtyShellReadRequest>,
260) -> impl IntoResponse {
261    if !is_owned_by_agent(&state.mstore, &req.shell_id, &req.agent_block_id) {
262        return (
263            StatusCode::OK,
264            Json(PtyShellReadResponse { content: String::new(), truncated: false, end: 0 }),
265        )
266            .into_response();
267    }
268    let mut end = 0u64;
269    // Where the bytes `read_file` returns start in the whole log: 0, unless the
270    // file is a circular one that has wrapped.
271    let start_idx = match state.filestore.stat(&req.shell_id, "term") {
272        Ok(Some(f)) => f.data_start_idx().max(0) as u64,
273        _ => 0,
274    };
275    let content = match state.filestore.read_file(&req.shell_id, "term") {
276        Ok(Some(bytes)) => {
277            let (range, abs_end) = since_slice(&bytes, start_idx, req.since);
278            end = abs_end;
279            String::from_utf8_lossy(&bytes[range]).to_string()
280        }
281        Ok(None) => String::new(),
282        Err(e) => {
283            return (
284                StatusCode::INTERNAL_SERVER_ERROR,
285                Json(json!({ "error": format!("ptyshell.read: {e}") })),
286            )
287                .into_response();
288        }
289    };
290    let tail_lines = req.tail_lines.unwrap_or(200).max(1) as usize;
291    let lines: Vec<&str> = content.lines().collect();
292    let start = lines.len().saturating_sub(tail_lines);
293    let truncated = start > 0;
294    let tail = lines[start..].join("\n");
295    (StatusCode::OK, Json(PtyShellReadResponse { content: tail, truncated, end })).into_response()
296}
297
298/// Where to start reading `len` bytes that begin at `start_idx` in the whole
299/// log, for a reader that has seen everything before `since`; and the log's
300/// absolute end, the next `since`. Offsets are absolute, so they keep growing
301/// even when a circular file drops its oldest bytes. A `since` before what is
302/// still held reads all of it; one past the end (a cleared log) reads it all
303/// again. The range holds whole characters only: it starts past any
304/// continuation bytes (a wrapped log can begin mid-character) and stops
305/// before a character still being written, which the next read returns.
306fn since_slice(bytes: &[u8], start_idx: u64, since: Option<u64>) -> (std::ops::Range<usize>, u64) {
307    let len = bytes.len();
308    let to = len - incomplete_tail(bytes);
309    let end = start_idx + to as u64;
310    let mut from = match since {
311        Some(s) if s >= start_idx && s <= end => (s - start_idx) as usize,
312        _ => 0,
313    };
314    while from < to && bytes[from] & 0xC0 == 0x80 {
315        from += 1;
316    }
317    (from..to, end)
318}
319
320/// How many bytes at the end of `bytes` begin a UTF-8 character that isn't
321/// complete yet.
322fn incomplete_tail(bytes: &[u8]) -> usize {
323    let len = bytes.len();
324    for back in 1..=len.min(4) {
325        let b = bytes[len - back];
326        if b & 0xC0 == 0x80 {
327            continue;
328        }
329        let need = match b {
330            0xC0..=0xDF => 2,
331            0xE0..=0xEF => 3,
332            0xF0..=0xF7 => 4,
333            _ => 1,
334        };
335        return if need > back { back } else { 0 };
336    }
337    0
338}
339
340/// `POST /api/v1/ptyshell/status` — query whether the shell is still running.
341async fn pty_shell_status(
342    State(state): State<AppState>,
343    Json(req): Json<PtyShellStatusRequest>,
344) -> impl IntoResponse {
345    if !is_owned_by_agent(&state.mstore, &req.shell_id, &req.agent_block_id) {
346        return (StatusCode::OK, Json(PtyShellStatusResponse { running: false, exit_code: None }));
347    }
348    match blockcontroller::get_block_controller_status(&req.shell_id) {
349        Some(status) => {
350            let running = status.shellprocstatus == blockcontroller::STATUS_RUNNING;
351            let exit_code = (status.shellprocstatus == blockcontroller::STATUS_DONE)
352                .then_some(status.shellprocexitcode);
353            (StatusCode::OK, Json(PtyShellStatusResponse { running, exit_code }))
354        }
355        // No controller registered — unknown id or already torn down via
356        // ptyshell/stop. Same "plain not-running answer, not an error"
357        // contract ShellStatus already documents.
358        None => (StatusCode::OK, Json(PtyShellStatusResponse { running: false, exit_code: None })),
359    }
360}
361
362/// `POST /api/v1/ptyshell/stop` — release the agent's lock immediately,
363/// without waiting for `AGENT_LOCK_WINDOW_MS` to lapse on its own.
364///
365/// Does not touch the process or the block at all (see
366/// `PtyShellStopResponse`'s doc comment in `api_types.rs` for why: this
367/// shell is a shared, pane-scoped resource now, not a private one this API
368/// owns outright).
369async fn pty_shell_stop(
370    State(state): State<AppState>,
371    Json(req): Json<PtyShellStopRequest>,
372) -> impl IntoResponse {
373    if !is_owned_by_agent(&state.mstore, &req.shell_id, &req.agent_block_id) {
374        return (StatusCode::OK, Json(PtyShellStopResponse { released: false }));
375    }
376    // Released in memory first — that's the copy `controllerinput` enforces
377    // against, so the human's keyboard is live again the instant this
378    // returns, not once the meta write commits and the frontend hears about
379    // it. The return value is the authoritative "was a lease actually held",
380    // for the same reason.
381    let was_locked = blockcontroller::agent_lock::release(&req.shell_id);
382
383    let mut meta = crate::backend::obj::MetaMapType::new();
384    meta.insert(META_KEY_AGENT_LOCK_UNTIL.to_string(), serde_json::Value::Null);
385    let released = broadcast_meta_update(&state, &req.shell_id, &meta).is_ok() && was_locked;
386
387    tracing::info!(block_id = %req.shell_id, released, "ptyshell.stop: released lock");
388    (StatusCode::OK, Json(PtyShellStopResponse { released }))
389}
390
391/// The 409 for a pane whose agent shell is running (or starting, created by
392/// this run) on another connection than `connection`, checked without
393/// touching the shell; the same cases `try_attach_to_existing_shell` refuses.
394fn running_shell_conflict(state: &AppState, agent_block_id: &str, connection: &str) -> Option<axum::response::Response> {
395    let shell_id = state
396        .mstore
397        .get::<crate::backend::obj::Block>(agent_block_id)
398        .ok()
399        .flatten()
400        .and_then(|b| b.meta.get(META_KEY_SHELL_SUBBLOCK_ID).and_then(|v| v.as_str()).map(str::to_string))?;
401    let shell = state.mstore.get::<crate::backend::obj::Block>(&shell_id).ok().flatten()?;
402    // Running, or created by this srv run and still starting (a concurrent
403    // create won the claim): either way `try_attach_to_existing_shell` would
404    // refuse it, so it is refused here too, before anything is asked.
405    let live = match blockcontroller::get_block_controller_status(&shell_id) {
406        Some(s) => s.shellprocstatus == blockcontroller::STATUS_RUNNING,
407        None => {
408            crate::backend::obj::meta_get_string(&shell.meta, super::http_shell::META_KEY_PTYSHELL_BOOT_ID, "")
409                == *state.boot_id
410        }
411    };
412    if !live {
413        return None;
414    }
415    super::http_shell::connection_conflict(&shell, connection)
416}
417
418#[cfg(test)]
419mod since_tests {
420    use super::since_slice;
421
422    fn ascii(n: usize) -> Vec<u8> {
423        vec![b'a'; n]
424    }
425
426    #[test]
427    fn a_cursor_reads_only_what_came_after_it() {
428        // A plain log: offsets are byte positions.
429        assert_eq!(since_slice(&ascii(100), 0, None), (0..100, 100));
430        assert_eq!(since_slice(&ascii(100), 0, Some(40)), (40..100, 100));
431        assert_eq!(since_slice(&ascii(100), 0, Some(100)), (100..100, 100));
432        // A cleared log (the cursor is past the end) is read again from its start.
433        assert_eq!(since_slice(&ascii(10), 0, Some(100)), (0..10, 10));
434    }
435
436    #[test]
437    fn offsets_stay_absolute_when_a_circular_log_wraps() {
438        // 300 bytes written, the newest 256 held: they start at 44.
439        assert_eq!(since_slice(&ascii(256), 44, Some(250)), (206..256, 300));
440        assert_eq!(since_slice(&ascii(256), 44, Some(300)), (256..256, 300));
441        // A cursor older than what is still held reads all of it.
442        assert_eq!(since_slice(&ascii(256), 44, Some(10)), (0..256, 300));
443    }
444
445    #[test]
446    fn a_read_never_splits_a_character() {
447        let done = "ok é ✓".as_bytes().to_vec();
448        assert_eq!(since_slice(&done, 0, None), (0..done.len(), done.len() as u64));
449        // The last character is half written: it waits for the next read.
450        let mut half = "ok ".as_bytes().to_vec();
451        half.extend_from_slice(&"✓".as_bytes()[..2]);
452        assert_eq!(since_slice(&half, 0, None), (0..3, 3));
453        // A wrapped log that starts mid-character skips the leftover bytes.
454        let wrapped = &"✓ok".as_bytes()[1..];
455        assert_eq!(since_slice(wrapped, 1, None), (2..4, 5));
456    }
457}
458
459#[path = "http_pty_shell_create.rs"]
460mod create_steps;
461
462#[cfg(test)]
463#[path = "http_pty_shell_tests.rs"]
464mod route_tests;