Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

feat(mcp): add resize_session tool and team mode resize

Jack Rudenko9c400d235d7e
diff --git a/CLAUDE.md b/CLAUDE.md
index 64d98377..c822ac4b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -35,9 +35,9 @@ lives in `ROADMAP.md`.
- `custom-endpoints.md`, `predefined-endpoints.md` — user config; the 25-vendor bundled catalog
- `onepassword.md` — secret resolution, the four denial causes, the handshake lock, route pinning
- `keychain.md` — the macOS Keychain backend: enumerate-for-presence vs read-for-value, the `security` traps, the Providers-tab write/delete
-- `mcp-sessions.md` — the 14-tool MCP surface and its four groups, the 4-tool nested mode, sessions
- on panes (`send_input` queueing, `capture_session`, the session records the magus monitor reads),
- `run_prompt`'s Claude Code print path, progress keepalive
+- `mcp-sessions.md` — the 15-tool MCP surface and its four groups, the 4-tool nested mode, sessions
+ on panes (`send_input` queueing, `capture_session`, `resize_session`, the session records the
+ magus monitor reads), `run_prompt`'s Claude Code print path, progress keepalive
- `team-capture.md` — why `team`'s exit 0 proves nothing, and why a slot's answer is every
assistant message of its turn, from the transcript, starting after the task file was read
- `team-lifecycle.md` — why no slot is ever killed on a timer, why `run` returns once every
diff --git a/ai-docs/architecture/README.md b/ai-docs/architecture/README.md
index 2890ed25..c054d53a 100644
--- a/ai-docs/architecture/README.md
+++ b/ai-docs/architecture/README.md
@@ -37,7 +37,7 @@ three earlier write-ups this material cites were lost.
| [`picker.md`](picker.md) | The OpenTUI model picker: why it is an inline dialog and not a dashboard (the density gate that manufactured the rejected build), the provider list as the default screen with nothing prefetched (3915 → 1436 ms), the discovery outcome that stopped `[]` meaning five things, the local served-by index (22 network queries measured at 10 018 ms), the no-terminal gate's complement law, and the capture and compile traps | change `picker/`, `selectModel`, discovery outcomes or fetchers, `should-open-picker.ts`, or a TUI test that asserts on a frame |
| [`context-window.md`](context-window.md) | Why setting one env lever accomplishes nothing, why the status line reports the ENFORCED window, and local-model token accounting | change context-window resolution, the status line, or token accounting |
| [`theming.md`](theming.md) | One detected theme for every surface, and the module-load palette-snapshot bug class it keeps producing (found six times) | add a colored CLI line or TUI surface |
-| [`mcp-sessions.md`](mcp-sessions.md) | The 14-tool MCP surface (groups low-level / agentic / session / debug, `CLAUDISH_MCP_TOOLS`) and the 4-tool nested-mode surface, sessions on panes: the flag check, the owner's verdict, `send_input` queueing, the session records (`spawn.json`, `waits.jsonl`, `meta.json`, `events.jsonl`, `screen.txt`) and what the monitor reads, `get_diagnostics`; `run_prompt`'s two paths (the Claude Code print call on the user's login, the proxy with no `max_tokens`); why the channel push was removed; and the `notifications/progress` keepalive | add or rename an MCP tool or group, change `run_prompt` or nested mode, or change sessions or their records |
+| [`mcp-sessions.md`](mcp-sessions.md) | The 15-tool MCP surface (groups low-level / agentic / session / debug, `CLAUDISH_MCP_TOOLS`; `capture_session` and `resize_session` in the session group) and the 4-tool nested-mode surface, sessions on panes: the flag check, the owner's verdict, `send_input` queueing, the session records (`spawn.json`, `waits.jsonl`, `meta.json`, `events.jsonl`, `screen.txt`) and what the monitor reads, `get_diagnostics`; `run_prompt`'s two paths (the Claude Code print call on the user's login, the proxy with no `max_tokens`); why the channel push was removed; and the `notifications/progress` keepalive | add or rename an MCP tool or group, change `run_prompt` or nested mode, or change sessions or their records |
| [`team-capture.md`](team-capture.md) | Why exit 0 proves nothing under `claude -p` (the measurement behind `require_pattern`), and why a slot's answer is every assistant message of its turn, read from the transcript, starting after the task file was read | change how `team` classifies output or builds `response-<slot>.md` |
| [`team-lifecycle.md`](team-lifecycle.md) | Why nothing kills a slot on a timer, the measurement that removed the deadline, why `run` returns once every prompt is accepted (≤ 120 s), the run registry by `run_id`, the `blocked` rule, the team record ended exactly once, and one driver with two owners | add a deadline, change when `team` returns, or touch per-slot liveness, cancel or the run record |
| [`debugging.md`](debugging.md) | Debug logging, `CLAUDISH_UPSTREAM_ERROR_LOG`, raw SSE capture, and the failed-translation workflow | diagnose a model producing wrong, empty, or garbled output |
diff --git a/ai-docs/architecture/mcp-sessions.md b/ai-docs/architecture/mcp-sessions.md
index f088e23a..330fb1a1 100644
--- a/ai-docs/architecture/mcp-sessions.md
+++ b/ai-docs/architecture/mcp-sessions.md
@@ -1,4 +1,4 @@
-> The 14-tool MCP surface and its four groups, the sessions behind it (panes, records, polling), `run_prompt`'s two paths, the removed channel push, and the progress keepalive.
+> The 15-tool MCP surface and its four groups, the sessions behind it (panes, records, polling, resizing), `run_prompt`'s two paths, the removed channel push, and the progress keepalive.
>
> Extracted from `CLAUDE.md` (v7.64.0). Indexed in [`README.md`](./README.md).
@@ -304,12 +304,12 @@ into one unattributable file. The capture **redacts at write time** now that it
only a path a user opted into: a 401/403 body routinely echoes the credential that failed,
and `get_diagnostics` hands these records to an agent.
-## MCP Tools (14 total)
+## MCP Tools (15 total)
- **Low-level** (3): `run_prompt`, `list_models`, `search_models`
- **Agentic** (3): `preflight`, `team`, `report_error`
-- **Session** (7): `create_session`, `send_input`, `get_output`, `cancel_session`,
- `list_sessions`, `get_diagnostics`, `capture_session`
+- **Session** (8): `create_session`, `send_input`, `get_output`, `cancel_session`,
+ `list_sessions`, `get_diagnostics`, `capture_session`, `resize_session`
- **Debug** (1): `compare_models`
`preflight` exists because `--probe` is CLI-ONLY. An MCP consumer had no way to
@@ -327,10 +327,16 @@ what a caller cannot see from the model id.
`pane-session.md`): `list_sessions` answers `{contract_version, capabilities, sessions}` with one
`SessionRow` per session (state, reason, `reason_detail`, tokens, `cost_usd`, tool calls, turns, `idle_seconds`,
`activity`, `pane`); `cancel_session` answers `{session_id, state, changed}`; `capture_session`
-answers the session's current 160×50 screen `{seq, cols, rows, cursor, lines, final, spans?}`, or
-`{unchanged:true, seq, final}` when `since_seq` is still current — a memory read, meant for polling
-at about 1 Hz. Their errors are a JSON `ContractError`. `team` gains the same verbs as modes
-(`list`, `status`, `capture`, `cancel`).
+answers the session's current screen `{seq, cols, rows, cursor, lines, final, spans?}` (160×50 at
+launch), or `{unchanged:true, seq, final}` when `since_seq` is still current — a memory read, meant
+for polling at about 1 Hz. `resize_session` answers `{session_id, cols, rows, changed, seq,
+pending?}`: the size actually set after clamping to 80–500 × 24–200, and the screen `seq` once the
+redraw at that size has landed, so a capture with that `since_seq` already sees it. Their errors
+are a JSON `ContractError`; `resize` is the only verb that emits the two codes it added,
+`resize_unsupported` (the magmux has no `resize` op) and `delivery_unavailable` (magmux refused, or
+the pane is unreachable). `team` gains the same verbs as modes (`list`, `status`, `capture`,
+`cancel`, `resize`). Why the size is the viewer's and what resizing costs the screen heuristics:
+`pane-session.md`, "Terminal size".
The tool list is pinned by an EXACT frozen array in `mcp-session/e2e-sessions.test.ts`, so
adding or removing a tool without updating that test fails CI. That is deliberate:
@@ -341,12 +347,12 @@ Tool gating via the `CLAUDISH_MCP_TOOLS` env var (lower-cased, `resolveToolGroup
| Value | Tools |
|---|---|
-| unset, `all` | all 14 |
+| unset, `all` | all 15 |
| `low-level` | `run_prompt`, `list_models`, `search_models` |
| `agentic` | `preflight`, `team`, `report_error` |
-| `session` | the 7 session tools |
+| `session` | the 8 session tools |
| `debug` | `compare_models` |
-| `channel`, or any other value | all 14, plus one stderr line naming the value and the valid ones (`unknownToolModeWarning`); for `channel` it says the group was renamed to `session` |
+| `channel`, or any other value | all 15, plus one stderr line naming the value and the valid ones (`unknownToolModeWarning`); for `channel` it says the group was renamed to `session` |
Unknown values keep selecting everything, because a server that lists fewer tools than its host
expects fails later and quietly. The stderr line is there so a typo is not read as `all` with
@@ -354,7 +360,7 @@ no trace.
`session` was `channel` until 10.7.0. The rename removed the old name with no alias, per the
thesaurus rule, so `channel` now falls into the unknown-value rule and selects everything. The
-stderr startup line shows `tools: channel, 14 tools` after the unknown-value warning, but an MCP
+stderr startup line shows `tools: channel, 15 tools` after the unknown-value warning, but an MCP
host does not show stderr.
`compare_models` moved to `debug` at the same time: it sends one prompt to several models in
sequence and shows raw answers, which is a route check, not work. Real multi-model work is `team`.
@@ -545,7 +551,7 @@ not checked". `testing.md` has the rules.
`../mcp-shutdown.e2e.test.ts` — stdin EOF, SIGTERM and SIGKILL of a server holding a live session
and a live team run.
-**The tool list is pinned per group, and adding a tool must break a pin.** `e2e-sessions.test.ts` freezes the full 14-name list, the session-only 7 and the low-level 3, deliberately: that list is a wire contract and an accidental change to it should be loud. `get_diagnostics` and `capture_session` each broke both pins on the way in, which is the guard working.
+**The tool list is pinned per group, and adding a tool must break a pin.** `e2e-sessions.test.ts` freezes the full 15-name list, the session-only 8 and the low-level 3, deliberately: that list is a wire contract and an accidental change to it should be loud. `get_diagnostics`, `capture_session` and `resize_session` each broke both pins on the way in, which is the guard working.
E2E tests use `--strict-mcp-config --bare --dangerously-skip-permissions` for isolation. SessionManager tests point child spawns at the tree under test via `CLAUDISH_BIN` (`spawn-claudish.ts`), never at the installed binary.
diff --git a/ai-docs/architecture/pane-session.md b/ai-docs/architecture/pane-session.md
index c80597a6..ff73cde3 100644
--- a/ai-docs/architecture/pane-session.md
+++ b/ai-docs/architecture/pane-session.md
@@ -24,7 +24,7 @@ first for why print mode is not a faithful subset of the REPL.
owner (MCP server or CLI team) ── spawn, detached, stdin = pipe ──▶ pane watcher (/bin/sh, argv0 claudish-pane-watcher)
│
└── spawn, detached ──▶ magmux --headless --no-status --id <paneId> --sock-dir <root> -e ". <ctl>/pane-launch.sh"
- COLUMNS=160 LINES=50, SHELL=<ctl>/sh-shim
+ COLUMNS=160 LINES=50 (launch size), SHELL=<ctl>/sh-shim
└─ pane 0: sh-shim -l -c ". pane-launch.sh" = /bin/sh -c …
└─ cd -- '<realpath cwd>' || exit 97
exec claudish -i --model <spawnModel> -y --quiet --session-id <uuid> --add-dir <turnDir> [caller flags]
@@ -398,7 +398,8 @@ run the user's profile.
`COLORTERM`, `CLAUDE_CODE_SSE_PORT`, `ENABLE_IDE_INTEGRATION`, `ITERM_*`, `VSCODE_*`, …) that
steer a TUI's rendering and integrations; and the host identity (`CLAUDISH_LAUNCHER_PID`/`PPID`,
`CLAUDE_CODE_SESSION_ID`), which describes the MCP server's host, not the pane's new session.
-- **Added:** `COLUMNS=160 LINES=50`, the slot's `CLAUDISH_TOKEN_FILE` and
+- **Added:** `COLUMNS`/`LINES` at the launch size (160×50 unless a size was requested while the
+ pane was starting; they are not updated by a later resize — "Terminal size" below), the slot's `CLAUDISH_TOKEN_FILE` and
`CLAUDISH_UPSTREAM_ERROR_LOG`, and `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1` when the owner left
it unset (it suppresses side calls billed on the routed model).
- **`MAGMUX_*` survives in the child.** magmux injects `MAGMUX_SOCK` into the pane; it is excluded
@@ -476,6 +477,59 @@ classifier reads. `network-recovery.md` §7 accepts ~300 client attempts only wh
the banner; a headless pane has no viewer. Tier 1's hold still runs; an exhausted episode answers an
inline 400 and the slot is FAILED `api_error`.
+## Terminal size
+
+**The size is the viewer's, not ours.** Every pane used to be born 160×50 and stay there, so a
+docked viewer either showed empty rows below the screen or cut every line. 160×50 is now only the
+launch default (`pane/pane-size.ts`); `resize_session` and `team(mode:"resize")` set it at any time,
+mid-turn included, clamped to cols 80–500 × rows 24–200. The floor is not arbitrary: at 80 columns
+every closed-list dialog marker still fits one row's width, and 24 rows still hold a full permission
+or trust dialog, so boot and blocked-screen detection keep working. magmux's own limits (≥ 20 × 3,
+≤ 10000 per side) are wider, so a clamped size can never earn its `too_small`/`too_large`.
+
+**A resize is a real one.** claudish sends magmux's `resize` op (`{type:"resize", pane:0, cols,
+rows}` → `{rows, cols, changed, manual}`); magmux sets the PTY winsize, the child gets a genuine
+SIGWINCH, and Claude Code reflows by reading the TTY. magmux then pushes a keyframe at the new
+geometry to every frames-mode watcher, which `applyFrame` consumes and which bumps `seq` like any
+other visible change. A magmux without the op (no `resize` in `capabilities.verbs`, read at every
+connect and redial) answers `resize_unsupported`. Once the pin and `MIN_MAGMUX_VERSION` move to the
+magmux release that ships the verb, an older magmux is refused at launch and that path is defensive.
+
+**Last caller wins, without locks.** The session keeps a `desiredSize` and an `appliedSize` (null =
+unknown, e.g. after `client_lost`/`client_timeout`). `resize()` records the desired size and awaits
+one per-pane drain loop that always sends the LATEST desired size, so a viewer dragging an edge
+produces a few requests, not one per intermediate size. The same-size short-circuit (`changed:false`,
+no request) applies only when `appliedSize` is known, equal and nothing is in flight; otherwise
+magmux's `changed` decides. While the client is disconnected, or the pane is still starting, the
+size is stored and the call answers `changed:true, pending:true`; `attach()` re-applies it after
+`capabilities`, and a starting pane launches at it. After every await the phase is re-checked: a
+session that went terminal answers its final capture's size with `changed:false`.
+
+**A capture after a resize sees the new size.** On `changed:true`, `resize()` waits up to 1000 ms
+for the screen model to reach the set size and returns that screen's `seq`, so a caller passing it
+as `since_seq` never reads a pre-resize frame as current.
+
+**What a resize costs the screen heuristics.** The classifier was written against 160 columns;
+at other widths its checks are width-proof: echo prefixes are `min(40, cols − 4)` long and compared
+against box text with row breaks removed, dialog markers match the dialog region joined into one
+string, and the working row tolerates a wrapped tail. They are validated on real Claude Code screens
+captured at 80, 120 and 250 columns. A resize redraw moves the above-box region, which only DELAYS
+settle and boot (it restarts their quiet clocks) and never completes them. Two places would have
+read a redraw as evidence and therefore ignore it for `RESIZE_QUIET_MS` (2 s) after a resize:
+degraded admission (`maybeDegradedAccept` counts only the echo there, so an undelivered prompt
+still fails `prompt_not_accepted`), and the activity timestamp behind `idle_seconds` and
+`last_activity_at` (a separate activity clock; `screen.changedAt` still moves).
+
+**What does not follow a resize.** `COLUMNS`/`LINES` in the child's environment stay at the launch
+values — they are shell-managed keys of the snapshot, and Claude Code reads the TTY winsize, not
+them. Children of Claude Code's Bash tool inherit that environment, so their output stays formatted
+for the launch width. Documented, not fixed.
+
+**Contract additions (additive in v1).** The `resize` verb on both owners (`resize_session`,
+`team(mode:"resize")`), the `resize` capability (advertised only together with the magmux pin that
+ships the op), and two `ContractError` codes that only this verb emits: `resize_unsupported` and
+`delivery_unavailable`.
+
## Nothing outlives its owner (D15)
Three layers, because magmux is detached into its own session and a client disconnect has no effect
@@ -637,9 +691,11 @@ type and new fields may only be added.
- Verbs: `team(mode="list")` → `{contract_version, capabilities, runs}`; `team(mode="status")` adds
`contract_version`, `capabilities` and a `run` row to its payload; `team(mode="cancel")` and
`cancel_session` return per-slot `{state, changed}`; `team(mode="capture")` and `capture_session`
- return the 160×50 screen `{seq, cols, rows, cursor, lines, final, spans?}` or
- `{unchanged:true, seq, final}` when `since_seq` is current. Errors are a JSON `ContractError`
- (`unknown_run`, `unknown_slot`, `unknown_session`, `invalid_args`).
+ return the screen at its current size `{seq, cols, rows, cursor, lines, final, spans?}` or
+ `{unchanged:true, seq, final}` when `since_seq` is current; `team(mode="resize")` and
+ `resize_session` return `{…, cols, rows, changed, seq, pending?}` ("Terminal size"). Errors are a
+ JSON `ContractError` (`unknown_run`, `unknown_slot`, `unknown_session`, `invalid_args`, and from
+ `resize` only `resize_unsupported`, `delivery_unavailable`).
- `run_id` (`<team_session_id>-<base36 start ms>-<6 hex>`) addresses one run even after a newer
run reused its path, while the server retains it (30 minutes after it settles, at most 20 settled
runs). A path holds at most one ACTIVE run.
diff --git a/ai-docs/architecture/team-lifecycle.md b/ai-docs/architecture/team-lifecycle.md
index aac2a8d0..a083598c 100644
--- a/ai-docs/architecture/team-lifecycle.md
+++ b/ai-docs/architecture/team-lifecycle.md
@@ -96,7 +96,9 @@ its handle, then SIGTERM and SIGKILL on the pane's process GROUP after an
identity check. The group matters: `claudish` runs the real CLI under Bun, which
runs `claude`, with a Bash-tool grandchild below that, so signalling one process
leaves the rest billing. `team(mode:"cancel")` stops one slot (`slot`) or the
-whole run and answers per slot `{state, changed}`.
+whole run and answers per slot `{state, changed}`. `team(mode:"resize")` changes
+one slot's terminal size and nothing else — it neither ends nor restarts a turn,
+and its redraw does not count as activity (`pane-session.md`, "Terminal size").
## `outputSize` is not a progress signal, and callers read it as one
@@ -184,7 +186,7 @@ Runs this process started are kept in memory keyed by `run_id`
(`<team_session_id>-<base36 start ms>-<6 hex>`), with an index of the newest run
per path. A path holds at most one ACTIVE run; `run` on an ACTIVE path is refused.
A SETTLED run (every slot terminal) stays listable and capturable for 30 minutes,
-at most 20 of them, oldest evicted first. `status`, `cancel` and `capture` take an
+at most 20 of them, oldest evicted first. `status`, `cancel`, `capture` and `resize` take an
optional `run_id`, which addresses THAT run while it is retained even after a newer
run reused the path; without one they address the newest run at `path`. After
eviction, or after a server restart, `status` still answers from `status.json`
@@ -256,7 +258,7 @@ the non-terminal STARTING, RUNNING, AWAITING_INPUT and AWAITING_PERMISSION
included — as failed; the verdict is `completed` when any slot is ok (the channel
frame's rule), `cancelled` when all were cancelled. Only `run` writes a record:
`run-and-judge` returns its verdict in the call, and `judge`/`status`/`list`/
-`capture`/`cancel` start no work. `loadDiskRecord` returns null for a
+`capture`/`cancel`/`resize` start no work. `loadDiskRecord` returns null for a
`kind: "team"` directory, so session tools answer a `team-*` id as unknown and
`list_sessions` (in-memory only) never lists one.
diff --git a/docs/usage/magmux.md b/docs/usage/magmux.md
index 2d2ed401..e04dc5ef 100644
--- a/docs/usage/magmux.md
+++ b/docs/usage/magmux.md
@@ -73,13 +73,18 @@ has finished, and closes the pane when the slot or session ends.
|---|---|
| `team(mode:"list")` | every run the MCP server holds, with one row per slot: state, activity, idle seconds, tokens |
| `team(mode:"status", path)` | one run's rows under `run.slots` |
-| `team(mode:"capture", path, slot)` | that slot's current 160×50 screen |
-| `capture_session(session_id)` | an MCP session's current 160×50 screen |
+| `team(mode:"capture", path, slot)` | that slot's current screen |
+| `capture_session(session_id)` | an MCP session's current screen |
+| `resize_session(session_id, cols, rows)`, `team(mode:"resize", …)` | set the pane's terminal size; Claude Code redraws at the new width |
| `list_sessions` | every MCP session, same row shape |
A capture carries a `seq` that grows with every visible change; pass it back as `since_seq` and an
-unchanged screen answers `{unchanged: true}`, so polling about once a second is cheap. See
-[MCP server](mcp-server.md).
+unchanged screen answers `{unchanged: true}`, so polling about once a second is cheap.
+
+A pane starts at 160×50. A viewer can resize it at any time (cols 80–500, rows 24–200, clamped);
+the next capture carries the new `cols`/`rows`. Resizing needs a magmux that ships the `resize`
+verb (MIN_MAGMUX_VERSION); an older magmux answers `resize_unsupported` and the pane stays 160×50.
+See [MCP server](mcp-server.md).
**What you might notice on disk.** Each pane has a socket and two small directories under
`/tmp/claudish-mux-<uid>/` (mode 0700), and one `claudish-pane-watcher` shell process. They are
diff --git a/docs/usage/mcp-server.md b/docs/usage/mcp-server.md
index aa5c9cba..ddfd85d1 100644
--- a/docs/usage/mcp-server.md
+++ b/docs/usage/mcp-server.md
@@ -6,7 +6,7 @@ Claudish isn't just a CLI. It's also an MCP server that exposes external AI mode
Claude can call Grok, GPT-5, or Gemini mid-conversation to get a second opinion, or delegate a task to another model as a full async session that it polls and answers with `send_input`.
-The server exposes **14 tools** across four groups: low-level (3), agentic (3), session (7), and debug (1).
+The server exposes **15 tools** across four groups: low-level (3), agentic (3), session (8), and debug (1).
### Requirements for `team` and sessions
@@ -169,7 +169,7 @@ Run AI models on a task with anonymized outputs and optional blind judging. Each
interactive Claude Code session in its own headless magmux pane (see "Requirements" above).
**Parameters:**
-- `mode` (required) - One of: `run`, `status`, `list`, `capture`, `cancel`, `judge`, `run-and-judge`
+- `mode` (required) - One of: `run`, `status`, `list`, `capture`, `cancel`, `resize`, `judge`, `run-and-judge`
- `path` - Session directory path (must be within current working directory). Required by every mode except `list`
- `models` - Model IDs to run (required for `run` and `run-and-judge`). Native Claude names (`opus`, `sonnet`, `haiku`, `internal`) are runnable slots too
- `judges` - Model IDs to use as judges (default: same as runners)
@@ -179,9 +179,10 @@ interactive Claude Code session in its own headless magmux pane (see "Requiremen
- `min_output_bytes` - Report a slot EMPTY when its answer is shorter than this (default 0 = off)
- `agent` - Claude Code subagent every slot runs as (e.g. `dev:reviewer`); an unknown agent fails the slot `agent_rejected`
- `claude_flags` - Other Claude Code flags and their values, space-separated, never positional text (write `--allowedTools Read,Bash`; a value after a Claude Code switch, as in `--brief now`, would be the session's first prompt and is refused). Flags that would break the interactive pane (`-p`, `--output-format`, `--resume`, …) and print-mode-only flags (`--max-turns`, `--max-budget-usd`, …) are refused
-- `slot` - For `capture` (required) and `cancel` (omit to stop the whole run): the anonymised slot id
-- `run_id` - For `status`, `capture` and `cancel`: the `run_id` a `run` answer returned; addresses that run even after a newer run reused the path. Omit it for the newest run at `path`
+- `slot` - For `capture` and `resize` (required) and `cancel` (omit to stop the whole run): the anonymised slot id
+- `run_id` - For `status`, `capture`, `cancel` and `resize`: the `run_id` a `run` answer returned; addresses that run even after a newer run reused the path. Omit it for the newest run at `path`
- `since_seq`, `spans` - For `capture`: see `capture_session`
+- `cols`, `rows` - For `resize` (required): see `resize_session`
**Modes:**
| Mode | What it does |
@@ -191,6 +192,7 @@ interactive Claude Code session in its own headless magmux pane (see "Requiremen
| `list` | Every run this server holds: `{contract_version, capabilities, runs}`. Finished runs stay listed for 30 minutes |
| `capture` | One slot's current terminal screen (same shape as `capture_session`) |
| `cancel` | Stop one slot (`slot`) or every slot of the run; answers each slot's `{state, changed}` |
+| `resize` | Set one slot's terminal size; answers `{run_id, path, slot, cols, rows, changed, seq, pending?}` (same rules as `resize_session`) |
| `judge` | Blind-vote on existing outputs in the session directory |
| `run-and-judge` | Full pipeline: run models, then judge the outputs; holds the call open for the whole run |
@@ -253,23 +255,23 @@ The session tools are in the `session` group, which `all` (the default) includes
| `CLAUDISH_MCP_TOOLS` | Tools |
|---|---|
-| unset, `all` | all 14 |
+| unset, `all` | all 15 |
| `low-level` | `run_prompt`, `list_models`, `search_models` |
| `agentic` | `preflight`, `team`, `report_error` |
-| `session` | `create_session`, `send_input`, `get_output`, `cancel_session`, `list_sessions`, `get_diagnostics`, `capture_session` |
+| `session` | `create_session`, `send_input`, `get_output`, `cancel_session`, `list_sessions`, `get_diagnostics`, `capture_session`, `resize_session` |
| `debug` | `compare_models` |
-| any other value | all 14, with a warning on stderr |
+| any other value | all 15, with a warning on stderr |
Inside a session that claudish itself started (a `create_session` or `team` pane), the server runs in nested mode. Whatever `CLAUDISH_MCP_TOOLS` says, it offers at most the four one-shot tools (`run_prompt`, `compare_models`, `list_models`, `search_models`) and no session tools. A model-running `claudish` launched from that session's shell (`-p`, interactive, `team run`) exits 64 with `nested session refused`. One level of nesting is the limit.
-Any other value still selects all 14 tools, and the server writes one line to stderr naming the
+Any other value still selects all 15 tools, and the server writes one line to stderr naming the
value and the valid ones:
```
[claudish] CLAUDISH_MCP_TOOLS="agentc" is not a tool mode; selecting all tools. Valid values: all, low-level, agentic, session, debug
```
-`channel` was the old name of the `session` group. It is no longer a group, so it selects all 14
+`channel` was the old name of the `session` group. It is no longer a group, so it selects all 15
tools, and the warning says it was renamed to `session`.
### Polling workflow
@@ -418,8 +420,8 @@ resolved model chain, accounting, and the paths to the full records (the transcr
### `capture_session`
-Read a session's current terminal screen, 160×50: what you would see if you were looking at its
-pane. It is a memory read, cheap enough to poll about once a second.
+Read a session's current terminal screen at its current size (160×50 unless someone resized it
+with `resize_session`): what you would see if you were looking at its pane. It is a memory read, cheap enough to poll about once a second.
**Parameters:**
- `session_id` (required) - Session ID from `create_session`
@@ -432,6 +434,32 @@ the same shape for a team slot.
---
+### `resize_session`
+
+Set a session's terminal size. The child gets a real resize signal and Claude Code redraws at the
+new width; the next `capture_session` reports the new `cols`/`rows` under a new `seq`. Allowed in
+every state, mid-turn included. When several callers resize the same session, the last one wins.
+
+Needs a magmux new enough to resize a headless pane (MIN_MAGMUX_VERSION, the release that ships
+the `resize` verb); with an older one the call answers `resize_unsupported`.
+
+**Parameters:**
+- `session_id` (required) - Session ID from `create_session`
+- `cols` (required) - Columns, an integer; clamped to 80–500
+- `rows` (required) - Rows, an integer; clamped to 24–200
+
+**Returns:** `{ session_id, cols, rows, changed, seq, pending? }`. `cols`/`rows` are the size actually
+set, after clamping. `changed: false` means the session already had that size, or has ended (it then
+answers its final size). `seq` is the screen's sequence after the redraw, so a capture with that
+`since_seq` sees the new size. `pending: true` means the pane is still starting or briefly
+disconnected: the size is stored and applied as soon as it can be. Errors are JSON
+`{error: {code, message}}` with `unknown_session`, `invalid_args` (missing or non-integer
+`cols`/`rows`), `resize_unsupported`, or `delivery_unavailable` (magmux refused or the pane is
+unreachable; the message carries magmux's reason). `team(mode:"resize", path, slot, cols, rows)` does
+the same for a team slot.
+
+---
+
### Session records on disk
Every `create_session` session keeps its record under `~/.claudish/sessions/<session_id>/`
@@ -628,16 +656,16 @@ its files.
**Check if MCP server starts:**
```bash
OPENROUTER_API_KEY=sk-or-v1-... claudish --mcp
-# Should output: [claudish] MCP server started (tools: all, 14 tools)
+# Should output: [claudish] MCP server started (tools: all, 15 tools)
```
**Test the tools:**
-Use Claude Code and ask it to list available MCP tools. You should see all 14 tools: `run_prompt`, `list_models`, `search_models`, `compare_models`, `preflight`, `team`, `report_error`, `create_session`, `send_input`, `get_output`, `cancel_session`, `list_sessions`, `get_diagnostics`, and `capture_session`.
+Use Claude Code and ask it to list available MCP tools. You should see all 15: `run_prompt`, `list_models`, `search_models`, `compare_models`, `preflight`, `team`, `report_error`, `create_session`, `send_input`, `get_output`, `cancel_session`, `list_sessions`, `get_diagnostics`, `capture_session`, and `resize_session`.
**Check which tool group is active:**
```bash
CLAUDISH_MCP_TOOLS=session OPENROUTER_API_KEY=sk-or-v1-... claudish --mcp
-# [claudish] MCP server started (tools: session, 7 tools)
+# [claudish] MCP server started (tools: session, 8 tools)
```
**Check magmux** (needed by `team` and sessions):
diff --git a/packages/cli/src/mcp-server.ts b/packages/cli/src/mcp-server.ts
index 48e5936b..2c9fc139 100644
--- a/packages/cli/src/mcp-server.ts
+++ b/packages/cli/src/mcp-server.ts
@@ -79,6 +79,7 @@ import {
preflightTeamRun,
readTeamInputFile,
readTeamStatus,
+ resizeTeamSlot,
setupSession,
shutdownAllTeamRuns,
startModels,
@@ -138,7 +139,7 @@ Each session is an interactive Claude Code running the model in its own headless
3. send_input may be called at any time; it is queued until the session is idle.
4. COMPLETED: call get_output for the answer.
5. FAILED or TIMEOUT — or COMPLETED with an empty or surprising answer — call get_diagnostics. It returns the child's final screen, the upstream error bodies, the recent state records, the resolved model chain and the paths to the full records. It needs no re-run and no debug flag.
-6. capture_session reads a session's current screen; cancel_session stops it. Nothing stops a session for being idle: a child inside a long build is silent and working.
+6. capture_session reads a session's current screen; resize_session sets its terminal size (any time, mid-turn included); cancel_session stops it. Nothing stops a session for being idle: a child inside a long build is silent and working.
The session_id from create_session is the key for every session tool.`;
@@ -797,6 +798,17 @@ function optionalInteger(raw: unknown, name: string): number | undefined {
return raw;
}
+/** A required integer argument such as `cols`; absent or not an integer → `invalid_args`. */
+function requiredInteger(raw: unknown, name: string, mode?: string): number {
+ const n = optionalInteger(raw, name);
+ if (n === undefined)
+ throw new ContractErrorException(
+ "invalid_args",
+ `'${name}' is required${mode ? ` for mode '${mode}'` : ""}`
+ );
+ return n;
+}
+
/**
* `team(mode="status")` (§8 B): the legacy payload of the newest run at `path` plus
* `contract_version`, `capabilities` and `run`. Given a `run_id` that a newer run at the
@@ -838,9 +850,12 @@ export function teamStatusAnswer(path: string, runId?: string): Record<string, u
});
}
-/** `list` / `status` / `cancel` / `capture`: memory reads, JSON answers, ContractError errors. */
+/**
+ * `list` / `status` / `cancel` / `capture` / `resize`: memory reads and the two pane verbs,
+ * JSON answers, ContractError errors.
+ */
export async function teamContractVerb(
- mode: "list" | "status" | "cancel" | "capture",
+ mode: "list" | "status" | "cancel" | "capture" | "resize",
args: Record<string, unknown>
): Promise<ToolAnswer> {
try {
@@ -852,6 +867,8 @@ export async function teamContractVerb(
const slot = optionalString(args.slot, "slot");
const since = optionalInteger(args.since_seq, "since_seq");
const spans = optionalBoolean(args.spans, "spans");
+ const cols = mode === "resize" ? requiredInteger(args.cols, "cols", mode) : undefined;
+ const rows = mode === "resize" ? requiredInteger(args.rows, "rows", mode) : undefined;
switch (mode) {
case "status":
return contractAnswer(teamStatusAnswer(path, runId));
@@ -862,6 +879,13 @@ export async function teamContractVerb(
throw new ContractErrorException("invalid_args", "'slot' is required for mode 'capture'");
return contractAnswer(captureTeamSlot(path, slot, since, spans, runId));
}
+ case "resize": {
+ if (slot === undefined)
+ throw new ContractErrorException("invalid_args", "'slot' is required for mode 'resize'");
+ return contractAnswer(
+ await resizeTeamSlot(path, slot, cols as number, rows as number, runId)
+ );
+ }
}
} catch (e) {
return contractErrorAnswer(e);
@@ -1412,8 +1436,8 @@ function defineTools(sessionManager: SessionManager, nested: boolean): ToolDefin
"slot is an interactive Claude Code session in its own headless magmux pane. " +
"Modes: 'run' (START the models and return once each has taken its prompt — it does " +
"NOT wait for answers), 'status' (per-slot state; read `run.slots`), 'list' (every " +
- "run this server holds), 'capture' (one slot's screen), 'cancel' (stop one slot or " +
- "the whole run), 'judge' (blind-vote on existing outputs), 'run-and-judge' (the " +
+ "run this server holds), 'capture' (one slot's screen), 'resize' (set one slot's " +
+ "terminal size), 'cancel' (stop one slot or the whole run), 'judge'(blind-vote on existing outputs), 'run-and-judge' (the " +
"blocking pipeline). Poll 'status' (read run.slots) or 'list'. " +
"NO SLOT IS EVER KILLED ON A TIMER once its prompt is accepted. A team slot is a full " +
"Claude Code session and may work for a long time; a slot inside a build or test " +
@@ -1430,21 +1454,21 @@ function defineTools(sessionManager: SessionManager, nested: boolean): ToolDefin
properties: {
mode: {
type: "string",
- enum: ["run", "judge", "run-and-judge", "status", "cancel", "list", "capture"],
+ enum: ["run", "judge", "run-and-judge", "status", "cancel", "list", "capture", "resize"],
description:
"Operation mode. 'run' STARTS the models and returns once every slot has taken " +
"its prompt (or failed to) — it does not wait for answers. Poll 'status' (read " +
"`run.slots`) or 'list' for progress, then 'judge' once the slots have " +
- "finished. 'capture' returns one slot's screen. 'run-and-judge' is the blocking " +
- "pipeline and holds the call open for the whole run. 'cancel' stops one slot or " +
+ "finished. 'capture' returns one slot's screen; 'resize' sets its terminal size. " +
+ "'run-and-judge' is the blocking pipeline and holds the call open for the whole run. 'cancel' stops one slot or " +
"the whole run.",
},
slot: {
type: "string",
description:
- "For 'cancel' and 'capture': the anonymised slot id (e.g. '02') from the slot " +
- "map 'run' returned. 'capture' requires it; for 'cancel', omit it to stop every " +
- "slot in the run.",
+ "For 'cancel', 'capture' and 'resize': the anonymised slot id (e.g. '02') from the " +
+ "slot map 'run' returned. 'capture' and 'resize' require it; for 'cancel', omit it " +
+ "to stop every slot in the run.",
},
path: {
type: "string",
@@ -1455,7 +1479,8 @@ function defineTools(sessionManager: SessionManager, nested: boolean): ToolDefin
run_id: {
type: "string",
description:
- "For 'status', 'cancel' and 'capture': the run_id a 'run' answer returned. It " +
+ "For 'status', 'cancel', 'capture' and 'resize': the run_id a 'run' answer " +
+ "returned. It " +
"addresses THAT run while this server retains it, even after a newer run reused " +
"the path. Omit it to address the newest run at 'path'.",
},
@@ -1469,6 +1494,16 @@ function defineTools(sessionManager: SessionManager, nested: boolean): ToolDefin
type: "boolean",
description: "For 'capture': also return the colour/attribute spans of each line.",
},
+ cols: {
+ type: "integer",
+ description:
+ "For 'resize' (required): the terminal width in columns, clamped to 80–500. The " +
+ "answer {run_id, path, slot, cols, rows, changed, seq} reports the size set.",
+ },
+ rows: {
+ type: "integer",
+ description: "For 'resize' (required): the terminal height in rows, clamped to 24–200.",
+ },
models: {
type: "array",
items: { type: "string" },
@@ -1561,7 +1596,13 @@ function defineTools(sessionManager: SessionManager, nested: boolean): ToolDefin
heartbeat: true,
handler: async (args, ctx) => {
const mode = args.mode as string;
- if (mode === "list" || mode === "status" || mode === "cancel" || mode === "capture") {
+ if (
+ mode === "list" ||
+ mode === "status" ||
+ mode === "cancel" ||
+ mode === "capture" ||
+ mode === "resize"
+ ) {
return teamContractVerb(mode, args);
}
try {
@@ -2225,7 +2266,7 @@ function defineTools(sessionManager: SessionManager, nested: boolean): ToolDefin
tools.push({
name: "capture_session",
description:
- "Read a session's current terminal screen (160×50): {seq, cols, rows, cursor, lines, final, " +
+ "Read a session's current terminal screen: {seq, cols, rows, cursor, lines, final, " +
"spans?}. A memory read, meant for polling about once per second. Pass the last `seq` as " +
"since_seq to get {unchanged:true, seq, final} while nothing changed. `final:true` is the " +
"last screen of a closed pane. Errors are a JSON ContractError.",
@@ -2259,6 +2300,41 @@ function defineTools(sessionManager: SessionManager, nested: boolean): ToolDefin
},
});
+ tools.push({
+ name: "resize_session",
+ description:
+ "Set a session's terminal size: the child gets a real SIGWINCH and Claude Code reflows. " +
+ "Allowed at any time, mid-turn included; the last call wins. The size is clamped to " +
+ "cols 80–500, rows 24–200 and the answer {session_id, cols, rows, changed, seq, pending?} " +
+ "reports the size set. `seq` is the screen's seq after the resize: the next capture_session " +
+ "shows the new cols/rows. `changed:false` = already that size. `pending:true` = the pane " +
+ "is starting or its socket is reconnecting; the size is applied then. A finished session " +
+ "answers its last size with changed:false. Errors are a JSON ContractError " +
+ "(`resize_unsupported` when the installed magmux has no resize op).",
+ inputSchema: {
+ type: "object",
+ properties: {
+ session_id: { type: "string", description: "Session ID from create_session" },
+ cols: { type: "integer", description: "Terminal width in columns (clamped to 80–500)" },
+ rows: { type: "integer", description: "Terminal height in rows (clamped to 24–200)" },
+ },
+ required: ["session_id", "cols", "rows"],
+ },
+ group: "session",
+ handler: async (args) => {
+ try {
+ const sessionId = optionalString(args.session_id, "session_id");
+ if (sessionId === undefined)
+ throw new ContractErrorException("invalid_args", "'session_id' is required");
+ const cols = requiredInteger(args.cols, "cols");
+ const rows = requiredInteger(args.rows, "rows");
+ return contractAnswer(await sessionManager.resizeSession(sessionId, cols, rows));
+ } catch (e) {
+ return contractErrorAnswer(e);
+ }
+ },
+ });
+
return tools;
}
diff --git a/packages/cli/src/mcp-session/session-manager.ts b/packages/cli/src/mcp-session/session-manager.ts
index 91ad27d6..f07aea87 100644
--- a/packages/cli/src/mcp-session/session-manager.ts
+++ b/packages/cli/src/mcp-session/session-manager.ts
@@ -43,13 +43,17 @@ import {
type CaptureResult,
type CaptureUnchanged,
ContractErrorException,
+ DEFAULT_PANE_COLS,
+ DEFAULT_PANE_ROWS,
FAILURE_REASONS,
type FailureReason,
type FinalVerdict,
type PaneBlock,
type PaneSession,
type PaneSessionOptions,
+ type PaneSize,
type PaneSnapshot,
+ type ResizeResult,
SLOT_STATES,
type SessionCancelResult,
type SessionRow,
@@ -57,6 +61,7 @@ import {
type SlotState,
assertMagmuxAvailable,
checkChildFlags,
+ clampPaneSize,
deliveryRefusal,
flagsRemoveRead,
isTerminalState,
@@ -224,6 +229,8 @@ interface SessionEntry {
lastLoggedTool: string | null;
assistantIdsLogged: number;
anomaliesLogged: Set<string>;
+ /** A size asked for while the pane was still starting (L2): its launch size, else applied once it started. */
+ requestedSize: PaneSize | null;
}
const DEFAULT_MAX_SESSIONS = 20;
@@ -610,10 +617,10 @@ function diskProseBytes(
function blankFinalCapture(): CaptureResult {
return {
seq: 0,
- cols: 160,
- rows: 50,
+ cols: DEFAULT_PANE_COLS,
+ rows: DEFAULT_PANE_ROWS,
cursor: { x: 0, y: 0 },
- lines: Array.from({ length: 50 }, () => ""),
+ lines: Array.from({ length: DEFAULT_PANE_ROWS }, () => ""),
final: true,
};
}
@@ -947,6 +954,7 @@ export class SessionManager {
lastLoggedTool: null,
assistantIdsLogged: 0,
anomaliesLogged: new Set(),
+ requestedSize: null,
};
}
@@ -957,6 +965,8 @@ export class SessionManager {
p: { flags: string[]; readAvailable: boolean; parentEnv: Record<string, string | undefined> }
): Promise<void> {
const info = entry.info;
+ // L2: a size asked for before this point is the pane's launch size
+ const launch = entry.requestedSize;
const paneOpts: PaneSessionOptions = {
kind: "s",
label: info.sessionId,
@@ -975,6 +985,7 @@ export class SessionManager {
},
shape: info.shape,
...(opts.prompt ? { initialPrompt: opts.prompt } : {}),
+ ...(launch ? { initialSize: launch } : {}),
readAvailable: p.readAvailable,
decide: (turn) => this.decide(entry, turn),
onBlocked: (b) => this.onBlocked(entry, b),
@@ -990,6 +1001,12 @@ export class SessionManager {
this.failNeverSpawned(entry, err);
throw err;
}
+ // a size asked for while the pane started (after its environment was built): apply it
+ // now; the pane's own worker answers any later resize
+ const asked = entry.requestedSize;
+ entry.requestedSize = null;
+ if (asked && (asked.cols !== launch?.cols || asked.rows !== launch?.rows))
+ entry.session.resize(asked.cols, asked.rows).catch(() => undefined);
if (!entry.ended) this.applySnapshot(entry, entry.session.snapshot());
}
@@ -1338,6 +1355,34 @@ export class SessionManager {
return { session_id: sessionId, state: r.state, changed: r.changed };
}
+ /**
+ * Set a session's terminal size (§8 F), clamped. Allowed in every live state, mid-turn
+ * included; last caller wins. A session whose pane is still starting stores the size and
+ * starts at it (L2), answering `changed:true, pending:true`; one whose pane never
+ * started answers the default size with `changed:false`. Throws
+ * `ContractErrorException`: `unknown_session`, `resize_unsupported`,
+ * `delivery_unavailable`.
+ */
+ async resizeSession(sessionId: string, cols: number, rows: number): Promise<ResizeResult> {
+ const entry = this.liveEntry(sessionId);
+ if (!entry) throw unknownSession(sessionId);
+ if (!entry.session) {
+ if (isTerminalState(entry.info.state))
+ return {
+ session_id: sessionId,
+ cols: DEFAULT_PANE_COLS,
+ rows: DEFAULT_PANE_ROWS,
+ changed: false,
+ seq: 0,
+ };
+ const size = clampPaneSize(cols, rows);
+ entry.requestedSize = size;
+ return { session_id: sessionId, ...size, changed: true, seq: 0, pending: true };
+ }
+ const r = await entry.session.resize(cols, rows);
+ return { session_id: sessionId, ...r };
+ }
+
/**
* The session's screen (§8 D): a memory read. `CaptureUnchanged` when `sinceSeq`
* equals the current seq. A session whose pane never started answers a blank final
diff --git a/packages/cli/src/pane/contract.ts b/packages/cli/src/pane/contract.ts
index 663154a9..05bd3dce 100644
--- a/packages/cli/src/pane/contract.ts
+++ b/packages/cli/src/pane/contract.ts
@@ -1,7 +1,7 @@
/**
* The frozen mod contract, version 1 — the single source of the wire types that the
- * peer's Claude Code mod reads from `team(mode="list"|"status"|"cancel"|"capture")`,
- * `list_sessions`, `cancel_session` and `capture_session`.
+ * peer's Claude Code mod reads from `team(mode="list"|"status"|"cancel"|"capture"|"resize")`,
+ * `list_sessions`, `cancel_session`, `capture_session` and `resize_session`.
*
* Pasted verbatim from the session architecture §8 (including CA-12 `contract_version`
* / `capabilities` and CA-13 `run_id`). Fields never change meaning or type within
@@ -240,11 +240,11 @@ export type SpanRun = [col: number, len: number, fg: number, bg: number, attr: n
/** D */
export interface CaptureResult {
/** claudish-owned. 0 = no frame received yet (lines all ""); ≥ 1 after the first frame; +1 per visible
- * change (text, colours, cursor, alt screen); never resets for a pane's life */
+ * change (text, colours, cursor, alt screen, size); never resets for a pane's life */
seq: number;
- /** 160 */
+ /** the pane's current width: 160 at launch, then whatever the last resize set */
cols: number;
- /** 50 */
+ /** the pane's current height: 50 at launch, then whatever the last resize set */
rows: number;
cursor: { x: number; y: number };
/** exactly `rows` entries, plain text, right-trimmed; Claude Code's screen (no scrollback) */
@@ -260,10 +260,43 @@ export interface CaptureUnchanged {
final: boolean;
}
-/** E */
+/**
+ * F — `resize_session`. `cols`/`rows` are the size SET (the request clamped to cols 80–500,
+ * rows 24–200); `changed` = the pane's size moved; `seq` = the screen's seq after the
+ * resize (the first capture at the new size once `changed`). `pending: true` = the socket
+ * is reconnecting (or the pane is still starting): the size is stored and applied on the
+ * reconnect (or at launch). A terminal session answers its last size with `changed:false`.
+ */
+export interface ResizeResult {
+ session_id: string;
+ cols: number;
+ rows: number;
+ changed: boolean;
+ seq: number;
+ pending?: true;
+}
+/** F — `team(mode="resize")`: the same answer, addressed by run and slot. */
+export interface TeamResizeResult {
+ run_id: string;
+ path: string;
+ slot: string;
+ cols: number;
+ rows: number;
+ changed: boolean;
+ seq: number;
+ pending?: true;
+}
+
+/** E. `resize_unsupported` and `delivery_unavailable` are emitted only by the resize verbs. */
export interface ContractError {
error: {
- code: "unknown_run" | "unknown_slot" | "unknown_session" | "invalid_args";
+ code:
+ | "unknown_run"
+ | "unknown_slot"
+ | "unknown_session"
+ | "invalid_args"
+ | "resize_unsupported"
+ | "delivery_unavailable";
message: string;
};
}
diff --git a/packages/cli/src/pane/index.ts b/packages/cli/src/pane/index.ts
index 14c1091a..3f8632e2 100644
--- a/packages/cli/src/pane/index.ts
+++ b/packages/cli/src/pane/index.ts
@@ -39,10 +39,22 @@ export {
type PaneBlock,
type PaneDiagnostics,
type PaneSession,
+ type PaneResizeOutcome,
type PaneSessionOptions,
PaneStartError,
type SendResult,
startPaneSession,
} from "./pane-session.js";
+export {
+ clampPaneSize,
+ DEFAULT_PANE_COLS,
+ DEFAULT_PANE_ROWS,
+ MAX_PANE_COLS,
+ MAX_PANE_ROWS,
+ MIN_PANE_COLS,
+ MIN_PANE_ROWS,
+ type PaneSize,
+ RESIZE_QUIET_MS,
+} from "./pane-size.js";
export type { FinalVerdict, PaneSnapshot, SettledTurn } from "./types.js";
export type { Phase } from "./slot-state.js";
diff --git a/packages/cli/src/pane/pane-launch.ts b/packages/cli/src/pane/pane-launch.ts
index db9935ce..e2e9b8f0 100644
--- a/packages/cli/src/pane/pane-launch.ts
+++ b/packages/cli/src/pane/pane-launch.ts
@@ -31,6 +31,7 @@ import { findMagmuxBinaryOrNull } from "../launcher/magmux-binary.js";
import { STRIPPED_CHILD_VARS } from "../launcher/magmux-wrapper.js";
import { resolveClaudishSpawn } from "../spawn-claudish.js";
import { isPaneShellManagedKey } from "./child-env.js";
+import { DEFAULT_PANE_COLS, DEFAULT_PANE_ROWS } from "./pane-size.js";
import { type WatcherArgs, isValidPaneId, sockPathOf, watcherArgv } from "./process-identity.js";
/* ───────────────────────────── socket root ───────────────────────────── */
@@ -182,6 +183,9 @@ export interface PaneEnvInput {
/** the control directory holding `sh-shim` */
ctlDir: string;
platform?: NodeJS.Platform;
+ /** the pane's size at launch (already clamped); DEFAULT_PANE_COLS × DEFAULT_PANE_ROWS when absent */
+ cols?: number;
+ rows?: number;
}
/**
@@ -195,8 +199,8 @@ export function buildPaneEnv(input: PaneEnvInput): { magmuxEnv: Record<string, s
if (v === undefined || isStrippedFromChildEnv(k)) continue;
env[k] = v;
}
- env.COLUMNS = "160";
- env.LINES = "50";
+ env.COLUMNS = String(input.cols ?? DEFAULT_PANE_COLS);
+ env.LINES = String(input.rows ?? DEFAULT_PANE_ROWS);
if (input.parentEnv.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC === undefined)
env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = "1";
Object.assign(env, input.slotEnv);
diff --git a/packages/cli/src/pane/pane-session.ts b/packages/cli/src/pane/pane-session.ts
index 6a4b858c..5505e77a 100644
--- a/packages/cli/src/pane/pane-session.ts
+++ b/packages/cli/src/pane/pane-session.ts
@@ -23,7 +23,13 @@ import { join } from "node:path";
import { claudeConfigDir } from "../mcp-session/parent-session.js";
import { waitForExit } from "../process-tree.js";
import { redactSecrets } from "../redact.js";
-import type { CaptureResult, CaptureUnchanged, FailureReason, SlotState } from "./contract.js";
+import {
+ type CaptureResult,
+ type CaptureUnchanged,
+ ContractErrorException,
+ type FailureReason,
+ type SlotState,
+} from "./contract.js";
import { MagmuxClient, type MagmuxConnectError } from "./magmux-client.js";
import {
type ClaudishLaunch,
@@ -60,6 +66,14 @@ import {
updateRecord,
writeRecord,
} from "./pane-registry.js";
+import {
+ DEFAULT_PANE_COLS,
+ DEFAULT_PANE_ROWS,
+ type PaneSize,
+ RESIZE_QUIET_MS,
+ clampPaneSize,
+ samePaneSize,
+} from "./pane-size.js";
import {
type GroupSnapshot,
type PaneIdentity,
@@ -146,6 +160,9 @@ const WATCH_FPS = 4;
const POLL_BACKSTOP_MS = 1_000;
/** R3-M4: a `finishing` turn with a static screen for this many secondary windows. */
const TURN_END_MISSING_FACTOR = 3;
+/** A resize reply, and the screen showing the new size after it. */
+const RESIZE_REPLY_MS = 10_000;
+const RESIZE_SCREEN_MS = 1_000;
/** The session registry is re-read at most this often (telemetry only). */
const REGISTRY_READ_MS = 250;
/** A registry/screen disagreement must hold this long before it is counted. */
@@ -176,6 +193,8 @@ export interface PaneSessionOptions {
shape: "one-shot" | "interactive";
/** enqueued before boot; delivered on boot_ready */
initialPrompt?: string;
+ /** the pane's size at launch, clamped here; DEFAULT_PANE_COLS × DEFAULT_PANE_ROWS when absent */
+ initialSize?: PaneSize;
/** false when callerFlags remove Read (§2.3 rule 4) */
readAvailable: boolean;
decide: (turn: SettledTurn) => FinalVerdict | "continue";
@@ -206,6 +225,18 @@ export interface PaneSessionOptions {
};
}
+/**
+ * What `resize` answers: the size SET, whether the pane's size moved, and the screen's
+ * seq after it. `pending` = the socket is reconnecting; the size is applied on the redial.
+ */
+export interface PaneResizeOutcome {
+ cols: number;
+ rows: number;
+ changed: boolean;
+ seq: number;
+ pending?: true;
+}
+
export type SendResult =
| { ok: true; queued: number }
| { ok: false; reason: "terminal" | "delivery_unavailable" | "unsupported_command" };
@@ -236,6 +267,12 @@ export interface PaneSession {
snapshot(): PaneSnapshot;
capture(sinceSeq?: number, opts?: { spans?: boolean }): CaptureResult | CaptureUnchanged;
send(text: string): SendResult;
+ /**
+ * Set the terminal size (clamped). Allowed in every live state; a terminal session
+ * answers its last size with `changed:false`. Throws `ContractErrorException` with
+ * `resize_unsupported` (magmux lacks the op) or `delivery_unavailable`.
+ */
+ resize(cols: number, rows: number): Promise<PaneResizeOutcome>;
turnAnswer(index: number): string;
/** main-chain assistant message ids the transcript has shown, first-seen order, each once */
assistantMessageIds(): readonly string[];
@@ -258,6 +295,12 @@ interface Admission {
degraded: boolean;
}
+/** A `resize` call waiting for the drain worker's send that carries its size (or a later one). */
+interface ResizeWaiter {
+ resolve: (r: PaneResizeOutcome) => void;
+ reject: (e: unknown) => void;
+}
+
interface ScreenTurn {
echo: string;
acceptedAt: number;
@@ -319,7 +362,7 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
private initialPending: boolean;
private shape: "one-shot" | "interactive";
private queue: string[] = [];
- private screen: ScreenState = emptyScreen(160, 50);
+ private screen: ScreenState;
private final = false;
private turnIndex = 0;
private admission: Admission | null = null;
@@ -358,6 +401,19 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
private exitScrollback = "";
private exitLastLine = "";
+ /** the size the viewer asked for last (clamped); the drain worker always sends THIS one */
+ private desiredSize: PaneSize;
+ /** the pane's size as magmux last confirmed it; null = unknown (a lost or timed-out reply) */
+ private appliedSize: PaneSize | null;
+ /** `capabilities.verbs` contains "resize", as of the latest attach */
+ private supportsResize = false;
+ private resizeWaiters: ResizeWaiter[] = [];
+ private resizeDraining = false;
+ /** when the last resize request was sent (or confirmed changed); 0 = never */
+ private lastResizeAt = 0;
+ /** the last screen change that is activity, i.e. not a resize redraw (M4) */
+ private activityChangedAt = 0;
+
private bootKind: string | null = null;
private bootKindSince = 0;
@@ -396,6 +452,11 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
this.turnDir = ids.turnDir;
this.identity = { paneId: ids.paneId, sessionUuid: o.sessionUuid, ctlDir: ids.ctlDir };
this.shape = o.shape;
+ const size = launchSize(o);
+ this.desiredSize = size;
+ // magmux sizes the pane from COLUMNS/LINES at launch, so the launch size is applied
+ this.appliedSize = { ...size };
+ this.screen = emptyScreen(size.cols, size.rows);
this.initialPending = !!o.initialPrompt;
if (o.initialPrompt) this.queue.push(o.initialPrompt);
this.secondaryQuietMs = o.timings?.secondaryQuietMs ?? SECONDARY_QUIET_MS;
@@ -510,7 +571,6 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
client.close();
return;
}
- this.client = client;
client.on("snapshot", (e) => this.onSnapshot(e));
client.on("frame", (f: MagmuxFrame) => this.onFrame(f));
client.on("exit", (e) => void this.onPaneExit(e));
@@ -518,9 +578,16 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
if (e?.pane === 0) this.paneClosed = true;
});
client.on("disconnected", () => this.onDisconnected(client));
- const caps = await client.request<{ version?: string; protocol?: number }>({
+ const caps = await client.request<{ version?: string; protocol?: number; verbs?: unknown }>({
type: "capabilities",
});
+ // The resize flag is set BEFORE this.client: a resize arriving in between sees a
+ // disconnected session (stored, pending), never a connected one without the op.
+ this.supportsResize =
+ caps.ok && Array.isArray(caps.result.verbs) && caps.result.verbs.includes("resize");
+ // dropped while asking: `disconnected` has already started the redial
+ if (client.isClosed) return;
+ this.client = client;
if (caps.ok) {
const v = String(caps.result.version ?? "");
if (caps.result.protocol !== 1 || !versionAtLeast(v, MIN_MAGMUX_VERSION)) {
@@ -532,6 +599,8 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
return;
}
}
+ // a size set while disconnected, or one whose reply was lost, is applied now
+ if (this.supportsResize && !samePaneSize(this.appliedSize, this.desiredSize)) this.kickResize();
await client.request({ type: "watch", pane: 0, mode: "frames", fps: WATCH_FPS });
// An `exit` pushed before this connection subscribed (a child that dies in its first
// milliseconds, or one that exited in a reconnect gap) is only visible in `list`.
@@ -566,7 +635,10 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
private onFrame(f: MagmuxFrame): void {
if (f.pane !== undefined && f.pane !== 0) return;
+ const seq = this.screen.seq;
this.screen = applyFrame(this.screen, f);
+ if (this.screen.seq !== seq && !this.inResizeQuiet(this.screen.changedAt))
+ this.activityChangedAt = this.screen.changedAt;
this.framePending = true;
if (!this.claudeCodeVersion) {
const m = this.screen.lines.join("\n").match(/Claude Code v(\d+\.\d+\.\d+)/);
@@ -1180,7 +1252,11 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
if (!box || box.text !== "") return;
const line = adm.plan.mode === "control" || adm.plan.mode === "refused" ? "" : adm.plan.line;
const echo = this.screen.lines.some((l) => l.startsWith(`❯ ${line.slice(0, 40)}`));
- const changed = adm.deliveredAt !== null && this.screen.aboveBoxChangedAt > adm.deliveredAt;
+ // H2: a resize redraws everything above the box; within its quiet window only the echo counts
+ const changed =
+ adm.deliveredAt !== null &&
+ this.screen.aboveBoxChangedAt > adm.deliveredAt &&
+ !this.inResizeQuiet(this.screen.aboveBoxChangedAt);
if (!echo && !changed) return;
this.turnSource = "screen";
this.anomaly("degraded_mode");
@@ -1565,7 +1641,8 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
snapshot(): PaneSnapshot {
const view = this.follower.view();
const terminal = isTerminalPhase(this.phase);
- const lastAct = Math.max(this.screen.changedAt, view.lastAppendAt ?? 0);
+ // M4: a resize redraw is not activity, so it never resets idle_seconds
+ const lastAct = Math.max(this.activityChangedAt, view.lastAppendAt ?? 0);
const cur = view.current;
const hasTranscript =
view.availability === "ok" && view.usage.tokensIn + view.usage.tokensOut > 0;
@@ -1656,6 +1733,145 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
return { ok: true, queued: this.queue.length };
}
+ async resize(cols: number, rows: number): Promise<PaneResizeOutcome> {
+ const size = clampPaneSize(cols, rows);
+ if (isTerminalPhase(this.phase)) return this.lastSizeOutcome();
+ if (!this.supportsResize)
+ throw new ContractErrorException(
+ "resize_unsupported",
+ 'this magmux has no resize op (capabilities.verbs lacks "resize"); a newer magmux is needed'
+ );
+ if (!this.client) return this.pendingOutcome(size);
+ // Same size and nothing in flight: no request. Otherwise magmux's `changed` decides.
+ if (
+ samePaneSize(this.appliedSize, size) &&
+ samePaneSize(this.desiredSize, size) &&
+ !this.resizeDraining
+ )
+ return { ...size, changed: false, seq: this.screen.seq };
+ this.desiredSize = size;
+ return new Promise<PaneResizeOutcome>((resolve, reject) => {
+ this.resizeWaiters.push({ resolve, reject });
+ this.kickResize();
+ });
+ }
+
+ /** Store the size for the redial (`attach` applies it) and answer it as pending. */
+ private pendingOutcome(size: PaneSize): PaneResizeOutcome {
+ this.desiredSize = { ...size };
+ return { ...size, changed: true, seq: this.screen.seq, pending: true };
+ }
+
+ /** A terminal pane's answer: the size of its last screen, unchanged. */
+ private lastSizeOutcome(): PaneResizeOutcome {
+ return { cols: this.screen.cols, rows: this.screen.rows, changed: false, seq: this.screen.seq };
+ }
+
+ /** A screen change at `at` falls within RESIZE_QUIET_MS after the last resize. */
+ private inResizeQuiet(at: number): boolean {
+ return (
+ this.lastResizeAt > 0 && at >= this.lastResizeAt && at - this.lastResizeAt < RESIZE_QUIET_MS
+ );
+ }
+
+ /** Start the per-pane drain worker unless it runs already. */
+ private kickResize(): void {
+ if (this.resizeDraining) return;
+ this.resizeDraining = true;
+ void this.drainResize().finally(() => {
+ this.resizeDraining = false;
+ // a waiter that arrived after the loop's last check
+ if (this.resizeWaiters.length > 0) this.kickResize();
+ });
+ }
+
+ /**
+ * The single resize worker of this pane (H3, M3): one request at a time, always the
+ * LATEST desired size, so the sizes of a drag coalesce. Each send answers every waiter
+ * queued before it; a waiter that arrives during it gets the next send. With no waiter
+ * it runs once: `attach` re-applying the size after a redial. The phase is re-checked
+ * after every await: a terminal pane answers its last size, `changed:false`.
+ */
+ private async drainResize(): Promise<void> {
+ let first = true;
+ while (first || this.resizeWaiters.length > 0) {
+ first = false;
+ const batch = this.resizeWaiters.splice(0);
+ const answer = (r: PaneResizeOutcome) => {
+ for (const w of batch) w.resolve(r);
+ };
+ const fail = (e: ContractErrorException) => {
+ for (const w of batch) w.reject(e);
+ };
+ if (isTerminalPhase(this.phase)) {
+ answer(this.lastSizeOutcome());
+ continue;
+ }
+ const want = { ...this.desiredSize };
+ const c = this.client;
+ if (!c) {
+ answer(this.pendingOutcome(want));
+ continue;
+ }
+ if (!this.supportsResize) {
+ fail(new ContractErrorException("resize_unsupported", "this magmux has no resize op"));
+ continue;
+ }
+ // stamped before the send: the child's SIGWINCH redraw can arrive before the reply
+ const before = this.lastResizeAt;
+ this.lastResizeAt = Date.now();
+ const r = await c.request<{ cols?: number; rows?: number; changed?: boolean }>(
+ { type: "resize", pane: 0, cols: want.cols, rows: want.rows },
+ RESIZE_REPLY_MS
+ );
+ if (isTerminalPhase(this.phase)) {
+ answer(this.lastSizeOutcome());
+ continue;
+ }
+ if (!r.ok) {
+ // magmux may have applied a request whose reply was lost: the size is unknown
+ if (r.code === "client_lost" || r.code === "client_timeout") this.appliedSize = null;
+ // the connection is gone: the redial's attach re-applies desiredSize
+ if (r.code === "client_lost" || r.code === "client_closed") {
+ answer(this.pendingOutcome(this.desiredSize));
+ continue;
+ }
+ this.lastResizeAt = before;
+ fail(
+ new ContractErrorException(
+ "delivery_unavailable",
+ `magmux did not resize the pane: ${r.code}${r.error ? `: ${r.error}` : ""}`
+ )
+ );
+ continue;
+ }
+ const set = {
+ cols: typeof r.result.cols === "number" ? r.result.cols : want.cols,
+ rows: typeof r.result.rows === "number" ? r.result.rows : want.rows,
+ };
+ this.appliedSize = set;
+ if (r.result.changed !== true) {
+ // no reflow, no keyframe: nothing to keep quiet
+ this.lastResizeAt = before;
+ answer({ ...set, changed: false, seq: this.screen.seq });
+ continue;
+ }
+ this.lastResizeAt = Date.now();
+ // H4: the answer's seq is the first screen at the new size (magmux's forced keyframe)
+ await this.waitFor(
+ () =>
+ isTerminalPhase(this.phase) ||
+ (this.screen.cols === set.cols && this.screen.rows === set.rows),
+ RESIZE_SCREEN_MS
+ );
+ if (isTerminalPhase(this.phase)) {
+ answer(this.lastSizeOutcome());
+ continue;
+ }
+ answer({ ...set, changed: true, seq: this.screen.seq });
+ }
+ }
+
turnAnswer(index: number): string {
const done = this.answers.get(index);
if (done !== undefined) return done;
@@ -1864,6 +2080,13 @@ function signalQuietly(target: number, sig: NodeJS.Signals): void {
}
}
+/** The pane's size at launch: the owner's initial size, clamped, else the default. */
+function launchSize(o: PaneSessionOptions): PaneSize {
+ return o.initialSize
+ ? clampPaneSize(o.initialSize.cols, o.initialSize.rows)
+ : { cols: DEFAULT_PANE_COLS, rows: DEFAULT_PANE_ROWS };
+}
+
function isControl(text: string): boolean {
const t = text.trim();
return t === "/exit" || t === "/quit";
@@ -1917,7 +2140,13 @@ function preparePane(
dirs = createLaunchDirs(root);
const argv = buildClaudishPaneArgv(o.spawnModel, o.sessionUuid, dirs.turnDir, o.callerFlags);
writeLauncherFiles(dirs.ctlDir, launcherScript(cwd, launch, argv));
- const { magmuxEnv } = buildPaneEnv({ parentEnv, slotEnv: o.slotEnv, cwd, ctlDir: dirs.ctlDir });
+ const { magmuxEnv } = buildPaneEnv({
+ parentEnv,
+ slotEnv: o.slotEnv,
+ cwd,
+ ctlDir: dirs.ctlDir,
+ ...launchSize(o),
+ });
return { paneId, sockPath, cwd, ...dirs, magmuxEnv };
} catch (e) {
for (const d of dirs ? [dirs.ctlDir, dirs.turnDir] : [])
diff --git a/packages/cli/src/pane/pane-size.ts b/packages/cli/src/pane/pane-size.ts
new file mode 100644
index 00000000..f3df04d0
--- /dev/null
+++ b/packages/cli/src/pane/pane-size.ts
@@ -0,0 +1,50 @@
+/**
+ * A pane's terminal size: the launch default, the bounds a resize is clamped to, and the
+ * quiet window after a resize.
+ *
+ * The size belongs to the viewer: a pane is born `DEFAULT_PANE_COLS × DEFAULT_PANE_ROWS`
+ * (`COLUMNS`/`LINES` in magmux's environment) and `resize_session` / `team(mode:"resize")`
+ * may change it at any time. magmux refuses a size outside its own limits (< 20 × 3, a side
+ * over 10 000, over 4 M cells); claudish CLAMPS instead and reports the size it set.
+ *
+ * The bounds are tighter than magmux's on purpose (plan review H1, L4): at 80 columns every
+ * closed-list dialog marker the classifier matches still fits one row, and 24 rows hold a
+ * whole permission or trust dialog. A smaller screen would turn a dialog into "no input box,
+ * no dialog" — an honest unknown that never settles.
+ */
+
+export const DEFAULT_PANE_COLS = 160;
+export const DEFAULT_PANE_ROWS = 50;
+
+export const MIN_PANE_COLS = 80;
+export const MAX_PANE_COLS = 500;
+export const MIN_PANE_ROWS = 24;
+export const MAX_PANE_ROWS = 200;
+
+/**
+ * After a resize the child redraws everything it shows (SIGWINCH reflow). For this long
+ * that redraw is not evidence: degraded admission ignores a change above the box (H2), and
+ * the activity timestamp behind `idle_seconds` / `last_activity_at` skips its frames (M4).
+ */
+export const RESIZE_QUIET_MS = 2_000;
+
+export interface PaneSize {
+ cols: number;
+ rows: number;
+}
+
+function clamp(n: number, lo: number, hi: number): number {
+ return Math.min(hi, Math.max(lo, Math.trunc(n)));
+}
+
+/** The size claudish sets for a requested one: each side clamped into its bounds. */
+export function clampPaneSize(cols: number, rows: number): PaneSize {
+ return {
+ cols: clamp(cols, MIN_PANE_COLS, MAX_PANE_COLS),
+ rows: clamp(rows, MIN_PANE_ROWS, MAX_PANE_ROWS),
+ };
+}
+
+export function samePaneSize(a: PaneSize | null, b: PaneSize | null): boolean {
+ return !!a && !!b && a.cols === b.cols && a.rows === b.rows;
+}
diff --git a/packages/cli/src/pane/screen-model.ts b/packages/cli/src/pane/screen-model.ts
index fd14ab76..fcabd08c 100644
--- a/packages/cli/src/pane/screen-model.ts
+++ b/packages/cli/src/pane/screen-model.ts
@@ -15,6 +15,7 @@
*/
import type { SpanRun } from "./contract.js";
+import { DEFAULT_PANE_COLS } from "./pane-size.js";
export interface ScreenState {
seq: number;
@@ -70,10 +71,14 @@ export function emptyScreen(cols: number, rows: number): ScreenState {
* A full-width box rule: `─`, at least 20 cells and at least cols−1 wide. Under `--agent`,
* Claude Code writes the agent's name into the top rule's right end (`──── dev:reviewer ─`),
* so one ` label ─` tail is part of the rule.
+ *
+ * The width floor is capped at the launch width: every capture this rule was measured on
+ * is 160 columns wide, and whether Claude Code draws the rule edge to edge on a much wider
+ * screen is not yet captured. On a narrower screen the floor is `cols − 1`.
*/
export function isBoxRule(line: string | undefined, cols: number): boolean {
if (!line || !/^─+(?: [^─]+ ─+)?$/.test(line)) return false;
- return line.length >= Math.max(20, Math.min(cols, 160) - 1);
+ return line.length >= Math.max(20, Math.min(cols, DEFAULT_PANE_COLS) - 1);
}
/**
diff --git a/packages/cli/src/team-orchestrator.ts b/packages/cli/src/team-orchestrator.ts
index 4458b781..66d3b807 100644
--- a/packages/cli/src/team-orchestrator.ts
+++ b/packages/cli/src/team-orchestrator.ts
@@ -9,6 +9,8 @@ import {
type CaptureResult,
type CaptureUnchanged,
ContractErrorException,
+ DEFAULT_PANE_COLS,
+ DEFAULT_PANE_ROWS,
type FailureReason,
type FinalVerdict,
MAX_LIVE_PANES,
@@ -23,6 +25,7 @@ import {
TERMINAL_STATES,
type TeamCancelResult,
type TeamListResult,
+ type TeamResizeResult,
type TeamRunRow,
assertMagmuxAvailable,
checkChildFlags,
@@ -651,10 +654,10 @@ export async function cancelTeamRun(
function neverSpawnedCapture(): CaptureResult {
return {
seq: 0,
- cols: 160,
- rows: 50,
+ cols: DEFAULT_PANE_COLS,
+ rows: DEFAULT_PANE_ROWS,
cursor: { x: 0, y: 0 },
- lines: Array.from({ length: 50 }, () => ""),
+ lines: Array.from({ length: DEFAULT_PANE_ROWS }, () => ""),
final: true,
};
}
@@ -682,6 +685,33 @@ export function captureTeamSlot(
return e.session.capture(sinceSeq, { spans: spans === true });
}
+/**
+ * Contract F: set one slot's terminal size (clamped), in any state, mid-turn included.
+ * A slot whose pane never spawned answers the default size with `changed:false`; a
+ * terminal one its last size. Throws `ContractErrorException`: `unknown_run`,
+ * `unknown_slot`, `resize_unsupported`, `delivery_unavailable`.
+ */
+export async function resizeTeamSlot(
+ path: string | undefined,
+ slot: string,
+ cols: number,
+ rows: number,
+ runId?: string
+): Promise<TeamResizeResult> {
+ const run = addressRun(path, runId);
+ if (!run) throw unknownRun(path, runId);
+ const e = run.slots.get(slot);
+ if (!e)
+ throw new ContractErrorException(
+ "unknown_slot",
+ `run ${run.runId} has no slot ${JSON.stringify(slot)}`
+ );
+ const where = { run_id: run.runId, path: run.path, slot };
+ if (!e.session)
+ return { ...where, cols: DEFAULT_PANE_COLS, rows: DEFAULT_PANE_ROWS, changed: false, seq: 0 };
+ return { ...where, ...(await e.session.resize(cols, rows)) };
+}
+
/**
* Per-slot maps the legacy `status` payload carries beside `run` (§4.1), derived from
* the live rows: idle seconds and activity of every non-terminal slot, and the answer