# Persistent terminal tools

Senpi's `bash` tool is backed by a real PTY, and ships four companion tools for
long-lived, interactive shell sessions. This is the built-in `terminal` extension,
powered by the in-house `@earendil-works/pi-pty` native module (with a
`child_process` pipe fallback when no native prebuild is available for your
platform/runtime).

## Tools

| Tool | Purpose |
|------|---------|
| `bash` | Run a command in a PTY. `run_in_background: true` starts a persistent session and returns a `bash_id` immediately. Foreground `timeout` (seconds) is a kill deadline. |
| `bash_output` | Peek at a session without blocking: new output since the last read, or the status line. `filter` regex-filters lines; `view: "screen"` returns the rendered xterm grid. |
| `monitor` | Watch a change and inject it as coalesced events, passing exactly one source - `command`, `path` or `target`: a long-running command (`description`, `command`, `filter?`, `timeout_ms?`, `persistent?`) injects matching PTY output lines, a file (`description`, `path`, `event?`, `persistent?`) fires once natively, and sessions (`type: "rpc"`, `target`, `events?`, `exclude?`, `filter?`, `persistent?`) report status changes, effect receipts and, opted in, content from every RPC host and terminal. Every call returns a stable `mon_` id (with the runtime `bash_N` handle as `details.bash_id`); either id addresses the watch. While watches are live, the interactive footer shows a brief `watching …` status (descriptions, count, paused markers). |
| `bash_input` | Search-exposed: activates on its first call. Send stdin (`input`) or named keys (`keys: ["ctrl+c"]`, `["enter"]`, `["up"]`) to steer a REPL or interrupt a process. |
| `bash_resize` | Search-exposed: activates on its first call. Resize a session's PTY (`cols`, `rows`) so full-screen TUIs reflow. |
| `kill_bash` | Tree-kill one session (`bash_id`) or all (`all: true`), leaving no orphans. |

Background sessions are NEVER killed by `timeout` (they live until they exit or you
call `kill_bash`), even though the bash-timeout extension injects a default `timeout`
into every `bash` call. Foreground calls behave like the classic `bash` tool.

### Long-running background sessions

A background session that is still running (started with `run_in_background`, or a
foreground command that auto-detached) is reported once it has run 10 minutes, then
every 30 minutes after that (10, 40, 70, ... minutes). Each report names the session's
`bash_id` and its command or label, says how long it has been running, and gives the
call that stops it (`kill_bash({ bash_id })`). It reaches the agent like a completion
notice (subject to `notify`), shows in the TUI, and goes to RPC clients as the
`terminal_background_age` event ([RPC](rpc.md#background-session-age)). A report that came
due while the machine slept is sent once, not once per missed interval.

Nothing is stopped automatically by default. To stop long sessions at a set age, opt in
with the `terminal.backgroundAutoReapMinutes` setting, or per call with the `bash`
parameter `auto_reap_minutes` (which wins over the setting; `0` turns it off for that
call). At that age the session is stopped the way `kill_bash` stops it (TERM to its
process group, then KILL after a grace), its completion notice says it was stopped
automatically, and a `terminal_background_age` event with `kind: "reaped"` is sent.
It counts as reaped only once that stop has really ended the session. If the stop fails
or the session survives it, one notice (and a `kind: "reap_failed"` event) says
auto-reap failed and why; the session keeps running, its age reports go on, and the
auto-reap does not retry.

Background sessions and monitors also survive a session reload (`/reload`): existing
`bash_N` ids stay addressable, watchers keep injecting events, and completion
notifications keep arriving. Quitting or switching sessions still tears everything down.

## Standing watches (`persistent: true`)

`persistent: true` turns a monitor into a standing watch: no `timeout_ms` deadline, and it
survives a full session restart, not just a `/reload`. On the next start of the same session:

- a **command** watch is re-run exactly once, in its original working directory, under the
  same `mon_` id. Nothing the previous PTY printed is replayed — output is never persisted,
  so a restored watch starts from an empty buffer;
- a **file** watch is re-registered under its original `mon_` id and its saved checkpoint
  (device, inode, size, mtime, content digest) is compared once against the file as it is now.
  A change that happened while senpi was gone is reported as exactly one line — `created`,
  `replaced`, or `modified` — and nothing is reported when the file is byte-identical. A file
  that has since been deleted, or is no longer a regular file, is reported lost instead.

Whatever it finds is summarized in **one** line on session start, e.g.
`Terminal state after restart: restored 2 (dev server ready, app error watch); lost 1 (PR checks).`
Expired watches (`expired N`) and watches still muted by the wake budget (`N still muted`) are
counted in that same line, which follows the `notify` setting like any other reminder; a
watch muted before the restart comes back muted, so `monitor({ action: "rearm", bash_id })`
is what un-mutes it. Ephemeral (non-persistent) monitors and background `bash` sessions are
never restored, and are reported as lost.

Standing watches are bounded: at most **5** per session (a sixth `persistent` create is
refused, with nothing spawned), and each **expires 7 days after it was created** — a deadline
neither a restore nor a rearm extends. Stop one early with `kill_bash`. If the same session is
already live in another process, that process keeps the watches and this one restores nothing
and says so.

Typical flow: start with `run_in_background: true`, watch for patterns with `monitor`,
peek with `bash_output`, steer with `bash_input`, then `kill_bash` when done. Completion
arrives as a notification carrying the exit code and output tail, so a follow-up
`bash_output` read is only needed when the tail is not enough.

## Monitor recipes

Each recipe shapes the command so the interesting moment becomes one clean,
newline-terminated line. Sleep loops live inside the monitored command.

### Dev-server readiness gate

```js
monitor({ description: "dev server ready",
  command: "until curl -fsS http://localhost:3000/health; do sleep 1; done; printf 'READY\n'",
  filter: "^READY$" })
```

Expected event: one `READY` line, then the exit summary. Follow-up: hit the
server. Nothing outlives the watch, so no cleanup.

### Long test or build with a pass/fail sentinel

```js
monitor({ description: "full test suite",
  command: "if bunx vitest run; then printf 'OK\n'; else code=$?; printf 'FAILED_%s\n' \"$code\"; exit \"$code\"; fi",
  filter: "^(OK|FAILED_)" })
```

Expected event: `OK` or `FAILED_<code>` plus the exit summary. On `FAILED_`,
read the tail with `bash_output` and fix; on `OK`, move on.

### QA error stream from a log

```js
monitor({ description: "app error watch",
  command: "tail -n 0 -F app.log | grep --line-buffered -E 'ERROR|FATAL'",
  persistent: true })
```

Expected events: each new ERROR/FATAL line as it lands. Follow-up: investigate
the failure it names. `tail -F` never exits, so `kill_bash` the `bash_id` when
the QA pass ends.

### CI / PR check watch

```js
monitor({ description: "PR checks",
  command: "gh pr checks 1052 --watch 2>&1",
  filter: "fail|pass|All checks" })
```

Expected event: the verdict line when checks settle, then the summary. Merge on
pass, pull the failing job's log on fail. The command exits by itself.

### File transition (native file branch)

```js
monitor({ description: "artifact written",
  path: "dist/app.tar.gz",
  event: "create" })
```

One file, watched natively — no shell, no poll loop. `create` (the default)
fires only when the file appears after registration; to watch a file that
already exists, pass `event: "modify"`. Registration needs the parent directory
(`dist/` here) to exist already, and the target must be a regular file, not a
symlink — when the build creates the directory too, keep a command poll loop
like the port recipe below. This branch is one source of three and takes no
`filter`. Expected event: one hit when the file lands, then the watch is done.
Consume the artifact. Add `persistent: true` to make it a standing watch that
survives a restart and reports a change it missed while detached.

### Port transition

```js
monitor({ description: "postgres up",
  command: "until nc -z localhost 5432; do sleep 1; done; printf 'READY\n'",
  filter: "^READY$" })
```

A port has no native watch, so the sleep loop belongs inside the command.
Expected event: `READY`, then exit. Connect.

### Child-agent sentinel watch

```js
monitor({ description: "subtask done",
  command: "until grep -q '^status=done$' /tmp/task.status 2>/dev/null; do sleep 5; done; printf 'READY\n'",
  filter: "^READY$" })
```

Expected event: `READY` once the child flips its status file. Read the child's
results and integrate. Exits on its own; no cleanup.

### Session status (rpc branch)

```ts
monitor({ type: "rpc", target: "children", description: "children status" })
```

The result lists every matched session (`<label> <status> (<n> attached, model <id>)`); after that each
status change arrives as `rpc <label> status <from> -> <to> (<cause>, by <by>) seq=<n>` and each effect
receipt as `rpc <label> effect <kind> <id tail> <state> (<disposition|reason>)`. `target` is
`"children"` (matched by the host, so children spawned after arming appear), `"all"` (every session of
every host and terminal endpoint you run) or one session id, path or `st_` task id; a session on another
device is `<device>/<session>` (e.g. `"laptop/abc123"`). `events` names any
RPC record kinds (default `["session_status"]`, children add `"effect_status"`); `"all"` adds content,
with streaming collapsed to `rpc <label> streaming +<n> deltas (last: "...")` per session per 2 s and
`exclude` dropping kinds. Content is a `mirror` opt-in: the monitor never attaches, so the session's
`attachments` count does not change. `persistent: true` survives a restart and reports what moved while
detached (`changed while detached`, `closed (gone while detached)`, `host ... restarted (generation a -> b)`).

A session on another device is `<device>/<session>` (or `<device>/*` for every session there) when an
extension registered a remote source with `pi.registerRpcRemoteSource`; without one such a target is
refused. Its lines read exactly like local ones. A lost device is said once
(`rpc device <device> unreachable (<reason>); re-watching`), the resync after the gap reports each change
once, each settled turn the resync names is reported once (`rpc <label> turn <id> settled while detached`)
while a live turn end is rendered as it arrives, and an
access that ended for good settles the watch (`rpc <device>/<session> access ended (<reason>)`).

### Anti-patterns

| Anti-pattern | Do instead |
|---|---|
| Sleeping in your own turn between polls | Put the sleep loop inside the monitor command |
| Spinning on `bash_output` reads | Register a monitor; peek only to steer |
| Filterless watch on a chatty command | Shape output at the source, then narrow with `filter` |
| Expecting `filter` to stop the command | `filter` gates events only; make the command exit on the condition |
| `persistent: true` with `timeout_ms` | A standing watch has no deadline; the timeout is ignored |
| Re-registering a standing watch after a restart | It is already back under the same `mon_` id; read the restart line first |
| Holding more than 5 standing watches per session | The sixth is refused; `kill_bash` one you no longer need |
| Sentinel printed without a trailing newline | Sentinels must be newline-terminated: `printf 'READY\n'` |
| Polling `test -f` in a command to await one file | Use the file branch: `monitor({ description, path, event? })` |
| `event: "create"` on a file that already exists | `create` fires only on appearance; use `event: "modify"` |
| `path` whose parent directory the build has yet to create | Registration fails; poll for it with a `command` watch instead |
| Passing two of `command`, `path`, `target` in one call | One source per call; pick the branch that matches what you await |
| Monitoring sub-minute deterministic work | Run it directly in the foreground |
| Rearming a monitor that was never paused | Rearm only a `bash_id` named in a pause notice |

## Mutual exclusion with native Anthropic bash

When `PI_ANTHROPIC_BASH` is enabled and the active model uses the
`anthropic-messages` API, senpi injects Anthropic's native, stateless `bash` tool.
In that mode the four persistent companions step aside (they are deactivated so none
dangle without a usable persistent `bash`), and a one-line notice is shown. Disable
`PI_ANTHROPIC_BASH` or switch to a non-Anthropic model to re-enable persistent
sessions.

## Settings

Configure the suite under `terminal` in `settings.json` (global
`~/.senpi/agent/settings.json` or project `.senpi/settings.json`):

```json
{
  "terminal": {
    "defaultCols": 120,
    "defaultRows": 40,
    "scrollback": 10000,
    "maxSessions": 32,
    "timeoutAction": "background",
    "notify": "wake",
    "backgroundAutoReapMinutes": 120
  }
}
```

- `defaultCols` / `defaultRows` — PTY size for new sessions (default 120 x 40).
- `scrollback` — xterm scrollback lines per session (default 10000).
- `maxSessions` — concurrent sessions before least-recently-used exited sessions are pruned (default 32).
- `timeoutAction` — fate of a foreground timeout (default `background`).
- `backgroundAutoReapMinutes` — stop a background session once it has run this many minutes (default unset: never). A whole number of minutes of at least 1 turns it on; `0` or any other value leaves it off. The `bash` parameter `auto_reap_minutes` overrides it per call.
- `notify` — async completion behavior: `wake` (wake an idle interactive agent once), `next-turn`, or `off` (default `wake`). Non-interactive `-p` / `--print` / `--mode json` runs never wake.
- `killGuard` — `on` (default) or `off`, read from the global settings file only (a project value is ignored). While on, an agent command or eval cell that would signal every process (`kill -1`, a `pkill` pattern such as `a||b`, `.*` or one letter), a protected process (pid 1, the agent, its ancestors, the user's service manager) or a process group holding one is refused before it runs with a `[senpi:kill-guard]` message naming the rule and a narrow alternative. Narrow kills by pid, exact name (`pkill -x`) or anchored pattern run as before. Values only known when a command runs (`pkill -f "$P"`, `xargs kill`, a script's `kill $PID`) are judged then: on macOS and Linux every agent shell, monitor and eval kernel gets `kill`, `pkill` and `killall` shims first on `PATH` (in `<agent dir>/kill-guard/<version>/`) and a `BASH_ENV` that wraps bash's builtin `kill`, chaining any `BASH_ENV` you already set; an interactive bash the agent starts gets the same wrapper from a `PROMPT_COMMAND` hook before its first prompt, after your startup files, and your own `PROMPT_COMMAND` still runs after it; a refused command exits 126 with the same message. This also judges what the agent types into a running shell with `bash_input` (edited, recalled or history-expanded lines included), because the shell judges the line it actually runs. Builtin `kill` in dash or zsh, in `bash --posix -c` and in `bash -i -c`, in an interactive bash whose startup files replace `PROMPT_COMMAND`, and a `kill` named by absolute path, are judged only from the command text. A command you type yourself with `!` is never judged and gets no shims. `off` restores the unguarded behavior (no shims, no `BASH_ENV`, `PROMPT_COMMAND` left as you set it) and shows one notice per session.

## Windows

The PTY runs natively on Windows via ConPTY. Shell resolution:

- Set `SENPI_GIT_BASH_PATH` to point at a specific `bash.exe` — it wins over the
  Git Bash auto-detection.
- An explicit shell path (`shellPath` in settings, or `SENPI_GIT_BASH_PATH`) is
  resolved by kind: `cmd.exe` uses `/c`, PowerShell/`pwsh` use `-NoProfile -Command`,
  and bash/sh use `-c` (or WSL bash `-s` via stdin).

No shell is bundled; install Git for Windows or point senpi at your shell.
