# Command sessions

| Family | Tools | Whose process |
| --- | --- | --- |
| Agent commands | `bash`, `write_stdin` | The agent. Results reach only the agent. |
| Terminal panel | `terminal_use` | A terminal tab, opened by the agent (`terminal-resource:` id) or the user |

The split follows risk: a user's tab holds sign-ins and running work. The model follows Codex's `exec_command` / `write_stdin` and Claude Code's background-task notice; Codex reaches the user's terminal only read-only, and Claude Code has `Bash` plus panel tools.

## bash

`bash(command, workdir, yield_time_ms, tty, description)`

1. `prepare_command` resolves `workdir` (worktree, sandbox checks, remote `cd` guard).
2. `session.run` checks the session cap, and `processes.start` launches the command under a detached supervisor and returns when the supervisor's one line on its stdout says the record runs.
3. `collect` reads unread output into a 1 MiB head and tail buffer each time the supervisor rings ([wake-ups](#wakeups)), until the command ends or the yield time passes.
4. Ended: `Process exited with code N` plus output, and the record is removed. Running: the record gets `background=True` and the reply is `Process running with session ID <id>`.

**Reply and edge cases**

| Case | Result |
| --- | --- |
| Header | `Wall time`, exit or session line, `Output:`, plus `cwd=` and a non-local `backend=`. stdout and stderr are one stream. |
| Nonzero exit, supervisor failure | Error result; a running session is not |
| `is_sandbox_denial` matches a sandboxed command's output | Sandbox explanation appended |
| Turn cancelled during the first wait | Stops the command (`check_cancelled`). A background session ignores later cancellations. |
| No trusted conversation (a script or test) | Runs once through `backend.run` with a ten-minute limit and the `exit_code=` format |

## write_stdin

`write_stdin(session_id, chars, yield_time_ms)` finds the session in the conversation (same `session_id`, or an execution in its scope).

| `chars` | tty | pipe |
| --- | --- | --- |
| empty | poll | poll |
| `"\x03"` | written to the terminal; line discipline sends SIGINT | `interrupt` command: SIGINT to the process group |
| other | `write` command, raw bytes | refused: stdin is closed |

| Call | Yield, ms |
| --- | --- |
| `bash` | default 30000, 250–30000 |
| `write_stdin`, writing | default 250, 250–30000 |
| `write_stdin`, empty poll | 5000–300000 |

A reply that shows the exit marks the record `reported`.

## Wake-ups

Nothing in a running command wakes on a tick. `processes.db` holds everything (output, status, stop and stdin rows); a wake-up only says "look now".

| Who waits | Woken by |
| --- | --- |
| Supervisor's control loop | The command's end: `SIGCHLD` from its group leader through `signal.set_wakeup_fd` (POSIX); the job's I/O completion port, followed by one thread (Windows). A stop, interrupt or stdin row: its writer connects to the doorbell after inserting it. A stdin pipe with room again (POSIX) or the writer thread finishing (Windows). One deadline: a stop's 5 s grace before SIGKILL |
| `collect` | The supervisor's ring after each output chunk and status write; its connection closing (the supervisor ended: a record still live turns `unknown` and the call returns); a stop fired for the turn (`cancellation.on_cancel`); the yield time; a 10 s resync |
| `control` waiting for an acknowledgement | The ring after the supervisor applies it; 8 s for a stop, 3 s otherwise |
| `processes.start` | The supervisor's `ready` line on its inherited stdout, or that pipe closing; at most 10 s |
| `group_guard` after the command's shell ends | Every other member of its group held by the operating system (kqueue `NOTE_EXIT`, a pidfd) and waited on; then the group is listed again, since a member may have started another. Listed every 0.1 s only where neither exists |

The doorbell (`channel.py`) is a loopback TCP port each supervisor listens on, recorded with a random token in its private record. A connection without the token is dropped.

A waiter connects before it reads, sending the token; the supervisor sends it one byte after every write. A writer connects after inserting its row; its token line wakes the supervisor to read its commands.

| Option | Why not |
| --- | --- |
| File events on `processes.db` | Reach only the Worker (not `--print` or a script) and arrive after `watchfiles`' debounce, about 0.7 s: every quick command would wait that long. They stay for windows and the exit-notice loop |
| Unix socket or FIFO | No `AF_UNIX` in Python on Windows, a 104-byte path limit on macOS; a FIFO is POSIX only |
| A thread in `waitpid` | `SIGCHLD` into the loop's own socket needs no thread; on Windows the completion port also counts members that outlive the leader, which a process handle does not |

## Session cap

64 live sessions per conversation. At the cap, the least recently used session outside the eight most recent is stopped and marked `reported`, and the new reply names it. There is no idle timeout.

## Exit notices

`run_exit_notices` runs in the worker. It sweeps when the process records change, at most every 2 s while output streams in, and, while a notice waits for a busy conversation, when that conversation may have gone quiet.

1. `unreported_exits()`: `background`, not `reported`, status `exited` or `failed`. A `stopped` command sends nothing.
2. Skip while the conversation has a running turn or nonterminal execution; retried after it.
3. Clone the newest chat request, set `source="process_exit"`, a fresh user message id and the notice text (command, exit code, duration, last 2000 characters), and admit with key `process_exit:<id>`. No chat execution: marked reported without a notice.
4. The user node is `display="runtime"`, and memory skips it.

## Approvals

|  |  |
| --- | --- |
| `write_stdin`, empty or `"\x03"` | No decision (`SESSION_POLL`); `bash` already approved the command |
| `write_stdin`, other input | Follows the mode, as `bash`. Counts as a risky tool in Auto, MCP and delegated constraints and dangerous allow rules. |
| `terminal_use` `input`, `interrupt`, `close` | Follows the mode on any tab. The card (`TerminalApproval`) names the tab, its directory, whether a command is running, unfinished human input and the exact input with control characters spelled out. |

**Processes layer**

| Part | Behaviour |
| --- | --- |
| `group_guard`, pipe | Runs the command with stdin `/dev/null` |
| `group_guard`, tty | Opens a pty as the controlling terminal of its own session, foregrounds its group, sets 30×120 and pumps master and supervisor pipes. Stops reading once its group and every other group of its session (a `set -m` job, a setpgid child) are empty, at most two seconds after the group: on macOS no end of output arrives while it holds the terminal, and a fully closed pty drops unread output |
| `group_guard`, signals | Ignores SIGINT and SIGTERM, so an interrupt reaches the command |
| Supervisor | `write` adds no newline; `interrupt` sends SIGINT to the group (Windows: terminates the tree). Records its doorbell's port and token (never in `public_record`) with `running` |
| `ProcessStore` | Records `tty`, `sandboxed`, `background`, `reported`, `last_used`. `take()` returns unread output and bytes dropped before reading. |
| tty support | Local backend on macOS or Linux |

## Interface

|  |  |
| --- | --- |
| Activity | Background sessions only; a command in its first wait is an active tool call |
| Resources | Running background sessions in the Terminal group as Background terminal; retained output read-only in xterm with Stop; refreshes when the process records change (the `processes` change frame) |
| Tool rows | `write_stdin`: "Waited for output", "Interrupted", "Typed". `terminal_use` input: "Typed in terminal". |

## Implementation status

Implemented as described. Not adopted from Codex: zsh fork, shell snapshots, the `shell`, `login` and `max_output_tokens` parameters, and stdin approval on policy drift.
