# RPC Mode

### Recovery after shared output overflow

The unattached shared output lane is bounded to 4096 records / 64 MiB. Overflow
seals the routing handle; its retained runtime may still be open, but its lost
output cannot be replayed. Reattaching with `open_session` is refused with
`error: "session_output_overflow"`, `errorCode: "session_output_overflow"` and
`errorData: { sessionId, sessionPath, action: "unload_and_reopen" }`. Session
commands on that still-open handle return the same error code and action rather
than silently dropping their replies.

Recover using `unload_session { sessionId }`, then `open_session { sessionPath }`
to obtain a fresh handle. Unload keeps its ordinary active-work, child-task and
other-client protections: inspect a refused unload's reason/action rather than
automatically forcing it. The overflow seal and capacity limits remain in force
until the old runtime is disposed.

RPC mode enables headless operation of the coding agent via a JSON protocol over stdin/stdout. This is useful for embedding the agent in other applications, IDEs, or custom UIs.

**Note for Node.js/TypeScript users**: If you're building a Node.js application, consider using `AgentSession` directly from `@code-yeongyu/senpi` instead of spawning a subprocess. See [`src/core/agent-session.ts`](../src/core/agent-session.ts) for the API. For a subprocess-based TypeScript client, see [`src/modes/rpc/rpc-client.ts`](../src/modes/rpc/rpc-client.ts).

## Unattended opens and Resume

`open_session` accepts optional `"attended": false` (other supplied values are
rejected with `invalid_launch_profile`). A host handover reopen always sets it;
CLI commands reopening parked paths, including `host session state`, `read`,
and `wait`, also set it. Engine-originated wakes make zero provider calls while
held. Attaching a client does not release the hold.

Real prompt, steer, follow-up, or question input releases it. The user's message
starts one turn with the latest coalesced non-goal context before that message;
the goal revalidates and may continue afterwards. A message another session sent
(`admit_external_message`, `pi.session.admitExternalMessage`) that would start a turn
releases an `unattended` hold the same way and answers `started` (senpi#6490). It does
not release a person's Stop, the hold after an interrupted run or a parent's run hold:
those need the person, so the delivery is kept as a held notice and answers `held`.

#### resume_session

An explicit Resume (the user's Resume action) instead is:

```json
{"id":"resume","type":"resume_session","sessionId":"rpc-1"}
```

```json
{"id":"resume","type":"response","command":"resume_session","success":true}
```

It runs at most one turn per held source, sequentially through `agent_end`,
regardless of follow-up queue mode, with the current goal last. Held counts and
latest payloads survive another restart. Each wake has a persisted `session-notice`
entry (`noticeId`, `producer`, `pauseSeq`, `at`, source payload, `heldCount`,
`text`, and `action: "resume_session"`). Delivery coalesces
by source; it never drains a backlog. `session-notices-consumed` atomically records
the held-to-released transition by notice ID at final provider admission.
Repeated releases and restart replay cannot deliver an already released ID.
`session-hold` entries record hold additions and releases. Refused admission
retains notice custody; an admitted turn is never replayed, even if later aborted.
Acknowledgements list only the notice IDs present in the delivered snapshot.
Wakes arriving during unattended Resume delivery remain in custody for the next
release. Human input establishes attendance immediately, including during a
release turn; subsequent wakes keep normal attended delivery and never re-hold.
A refused released wake stays solely in notice custody, not also in the native
steering or follow-up queue.

The command response acknowledges release admission, not completion of all turns.
Observe session events for progress and `agent_idle` for settlement. Hosts advertise
`resume_session` and `attended` in `get_protocol_info.capabilities`; classic RPC
advertises `resume_session` only because it does not accept `open_session`.

After a user Stop (senpi#3811) Resume runs one turn instead: held human input first, then the held notices, then a
hidden note that the interrupted tool calls were not re-run. The response still acknowledges release admission; the
turn runs after it. Every field below is optional, so the bare form keeps working:

```json
{"type":"resume_session","expectedSeq":3,"mode":"continue","message":"Use staging","effectId":"resume-7"}
```

`expectedSeq` is the `pauseSeq` the client rendered; a different current seq answers `resumed: false, reason:
"stale"` and changes nothing. `mode: "release"` releases the Stop and an `unattended` hold without starting a turn
(the notices ride the next human message). `message` is delivered first in the resumed turn. The answer comes once the
resumed turn has started, or with `turnStarted: false` once it is clear no turn starts (for example a newer Stop landed
while the turn was admitted); held input and notices stay held until a turn that no newer Stop aborted delivers them.
A repeated `effectId` answers the recorded outcome with `replayed: true` and resumes nothing again, also after a
reopen. A session with nothing held answers
`not_paused`; a task child held only for its parent's run answers `resume_through_parent` with `parentSessionId`.

`unlessStopped: true` is for a resume another session or a tool asks for, not a person (senpi#7016): while a person's
Stop or a parent's run hold is live it answers `resumed: false, reason: "stopped"` and releases nothing, so only the
person resumes their Stop. Otherwise it resumes exactly as the bare form does. This is the sanctioned remote resume of
a session reopened after an interrupted run: open it (`open_session`), then send
`{"type":"resume_session","sessionId":"...","expectedSeq":<pauseSeq from open_session.state>,"unlessStopped":true}`.

A reopened session is held as interrupted only when its file shows a run that was still in flight: a run recorded
active whose transcript does not end in an assistant answer that asks for no tool call (a tool call without its result,
a tool result, or input after the answer). A run whose answer was written ends there, even when its process was killed
(SIGKILL included) before the idle record cleared `runActive`, so it reopens without the interrupted-run hold.

```json
{"type":"response","command":"resume_session","success":true,"data":{"resumed":true,"pauseSeq":3,"turnStarted":true,"deliveredNotices":2,"deliveredHeldInputs":1}}
```

`get_state` and `open_session.state` include:

```typescript
paused: boolean;
pausedNoticeCount: number;
holds: { kind: HoldKind; key: string; since: string; data?: unknown; sourceCounts: Record<string, number> }[];
// HoldKind = "unattended" | "session_hold" | "run_fence" | "inherited_hold" (senpi#3811)
```

`since` is an ISO timestamp. This is the shared engine hold ledger; this release
keys each record by `key` (defaulting to its kind) and preserves opaque `data`
through a restart. Persisted additions carry `key`/`data`, and release entries list `keys`. It
implements only `unattended`. Consumers must distinguish kinds rather than infer
them from the notification text. Every hold that pauses the session emits `session_paused` with `kind`,
`pauseSeq`, `at`, `noticeCount`, and `persisted`, including a hold added while the session is already paused
(a second Stop, a re-armed hold), so the last `pauseSeq` a client saw is always the one `resume_session`
accepts as `expectedSeq`. The release that ends the pause emits
`session_resumed { cause: "input" | "resume_session", pauseSeq, at }` once; a run fence alone pauses nothing and
emits neither.
The ordinary extension UI `notify` event shows the paused count and Resume
instruction too. Attachment lifecycle extension events remain distinct from
these engine pause events: attachment never releases any ledger hold.
Notices name the held sources and are suppressed after human input releases them.
Pause and resume wire events go only to connections attached to that session.

`open_session.context.task_status`, updated through `set_session_context`, is the task owner's lifecycle label.
Handover parks with `completed`, `cancelled`, `error`, `failed`, `lost`, or
`interrupted` are removed with a stderr diagnostic instead of being reopened.
Other context keys remain opaque.

Automatic turn admission is also bounded independently of the hold. On unattended resume,
`engineTurns.maxPerResumeWindow` defaults to 8, counting engine starts in loaded
history since the last real input. A real input ends that resume window. The
normal `engineTurns.maxPerUserInput` defaults to 0 (off). Only admitted new engine
turns count, not wakes steered into running work or pending compaction; a limit emits the existing engine-paused
notice and record. Setting either cap to 0 disables that particular cap.

When the last client disconnects from a retained in-process session, extensions receive
`session_parked`; the first reattachment to that still-open session emits
`session_resumed`. File-monitor polling and prompt-cache keepalive pause between these
events. Active turns and idle eviction keep their existing behavior. These extension
hooks are not the `session_parked` wire record emitted when eviction or handoff releases
a runtime. Worker-runtime sessions currently do not dispatch the extension hooks.

The shared Unix socket host keeps its ownership state in a PER-SOCKET daemon directory, `<agentDir>/rpc-host-daemon/<sha256(canonical socket)[:16]>/` (see [Daemon state directory](#daemon-state-directory-layout-2)). Clients attach to a compatible existing host regardless of which client surface started it; only incompatible unmanaged owners are refused.

## Session lifecycle

The `session_lifecycle` capability advertises one engine-owned root-work state.
`get_state.lifecycle` returns it; `{ type: "session_lifecycle", sessionId, lifecycle }`
publishes changes on the ordered session stream. Shared hosts broadcast the event
to observers and replay only the latest lifecycle snapshot on attachment.

The shared `SessionLifecycle` type is exported by `@code-yeongyu/senpi`:

- `state`: `running`, `waiting_children`, `waiting_background`, `waiting_human`,
  `paused`, `held`, `done`, `failed`, or `cancelled`.
- `seq`, `epoch`, `epochOrigin` (`human` or `automatic`), `humanInputRevision`,
  `selfSettleEligible`, `restoring`, `persisted`, `runPaused`, and `since` (ISO time).
- `role` (`root` or `child`), `rootSessionId`, and optional `parentSessionId` and `taskId`.
- Optional `runId` identifies the current or most recent engine run, matching that run's
  `agent_start.runId` and lifecycle readback (`get_state.lifecycle`, including the shared
  `open_session` state projection). Every new run gets a new ID even within the same epoch.
  Snapshots published while idle retain the preceding run's ID; before the first run it is
  absent. Restore preserves the recorded ID. Compare IDs for equality, never sort them.
  A snapshot may arrive before its own `agent_start`; associate it only with the turn whose
  start carries the same ID, not the next observed start. This field is additive and optional:
  older clients ignore it, and clients talking to older engines without it keep their existing
  association behavior.
- Optional `waitingOn`: `{ children, background, human, childSources?, childReports?, childReportsOmitted? }`.
  `children` and each source's `activeCount` are the authoritative counts; every named list below is
  supplemental and may be incomplete, so never derive a count from a list's length. `children` is the
  larger of the nonterminal child reports and the summed `childSources` counts.
  Background entries carry `source`, `activeCount`, optional `items`, optional `omittedItems`, and
  optional `retryAtMs`. `childSources` entries carry `source`, `activeCount`, optional `items`, and
  optional `omittedItems`. Each item is `{ id, label?, startedAt? }` (`startedAt` is ISO time), taken
  from the producer's `wake_source_state` snapshot: its `items`, or the legacy `monitors` list when
  `items` is missing or null. Terminal monitors are named by their stable `mon_` id. Each list is a
  snapshot: entries whose `id` is not a non-blank string are dropped, duplicates collapse to one entry
  per `id`, the list is sorted by `id`, and at most 32 entries are kept. `omittedItems` is the
  producer's own omitted count plus any valid items cut at 32; it is not `activeCount` minus the list
  length. Invalid detail drops only the detail, never the count.
  `childReports` lists nonterminal reports from `reportChild` as
  `{ taskId, childSessionId, runEpoch, state, label?, since? }`, excluding reports about the session
  itself, sorted by `taskId` and capped at 32; `childReportsOmitted` counts the reports cut by that cap.
  Human entries carry `kind`,
  `originSessionId`, `requestId`, `revision`, `since`, and optional child identity/label.
  Human kinds are `question`, `approval`, `goal_blocked`, `goal_paused`, `stalled`,
  and `interrupted_run`; attention remains visible even when a hold wins precedence.
- Optional `holds`: `{ kind, since }[]` from the shared hold ledger, where `kind` is
  `session_hold`, `inherited_hold`, `run_fence`, or `unattended`.
- On a sealed epoch, `completionId` is `<sessionId>:<epoch>`, the session's own id (for a root
  this equals `rootSessionId`), so a child's terminal never shares its root's id. A `done` also carries
  `completion: { kind: "goal" | "run" | "agent" | "reply", at, goalId?, runId? }`.
  A `failed` carries `failure: { reason, message?, retryAtMs?, taskId?, runEpoch? }`,
  with reason `provider_error`, `tool_error`, `task_error`, `lost`, or `interrupted`.
- A standing agent self-settle intent adds `settleDecision: { decisionId }` to the
  persisted `done` seal, independently of the completion label.
- Optional `lastStop: { cause, runId, at, epoch, deadline?, guard?, todo?, abortSource?, persisted? }`
  says why the run `runId` stopped. `cause` is `deadline`, `goal_guard`, `todo_guard`, `aborted`,
  or `no_wake`; `deadline` is `inactivity` or `max_runtime`, `guard` is the goal guard reason as
  recorded, `todo` is `cap`, and `abortSource` is `user`, `system`, or `provider`. `persisted: false`
  appears only when the deadline-stop entry could not be written and is independent of the
  snapshot's `persisted`. `lastStop` describes the last run's historical stop, so a `no_wake`
  stop remains even if a wake source later appears. It is cleared when the next run starts
  and never names a later run. A fact refresh with no bound turn end never sets `lastStop`;
  between runs, a refresh while the last end is still bound may set or update that run's stop.
  Goal guards are captured during their bound end's own processing, never inherited from
  another run. Provider errors and policy rejections carry no `lastStop`, even if a deadline fired.
- Wire-only `observedAt` is the host's ISO wall-clock time when it serializes or enqueues
  that lifecycle delivery: push, `get_state`, `open_session`, classic stdio, worker-host,
  TUI-control, and attach replay. Replay re-stamps a wire copy at send time. It is never
  persisted and never changes `activityRevision.instanceId`, activity revision, `seq`, `epoch`,
  `since`, completion identity, or activity content. Forwarding preserves the engine owner's
  activity key, including absent activity; inspecting or replaying never mints a revision.
  It is not a heartbeat or proof of liveness.
- Optional `activity` is present only while `state` is `running` and a live activity is known:
  `{ kind: "tool", toolName, toolCallId, since, outstanding }` represents the oldest outstanding
  top-level tool operation, including preparation, approval and dependency waits. Nested calls
  do not count. `{ kind: "model", since }` covers only an assistant stream from its start to its
  message end, not the first-token wait or prepared messages. `since` is the time the session
  observed the start boundary, not a timestamp carried by the core event, so it approximates the
  real start; it stays stable while selected. Compaction, retry waits, queued work and other
  unknown intervals omit activity.
- Optional `activityRevision: { instanceId, revision }` orders activity separately from durable
  lifecycle state. New writers include it even when activity is absent. The engine owner allocates
  a fresh opaque `instanceId` on reconstruction or rebinding; delivery and reconnect do not change it.
  An activity-only change keeps lifecycle `seq`, increments `revision`, and appends no durable record,
  also while a failed custody write leaves `persisted` false.
  An independently required lifecycle write retains append-before-publish and resets revision to zero
  at its new `seq`, carrying the current activity once. Token deltas and tool progress change neither
  ordering number. Both activity fields are wire-only and ignored on restoration; restored activity
  is absent under a fresh instance with revision zero. `persisted` still describes durable lifecycle
  state, not activity persistence.

The activity ordering key is `(session, instanceId, lifecycle seq, revision)`. Separate durable
lifecycle equivalence (including `lastStop`) from complete activity-projection equivalence: absence,
kind, tool identity, `since`, and `outstanding`. Thus `start(A), start(B), end(B)` delivers counts
`1, 2, 1` under three distinct activity ordering keys without advancing lifecycle `seq`.

Clients keep ordinary state and completion effects ordered by session and lifecycle `seq`.
An equal lifecycle `seq` may refresh receipt information and, under the activity ordering rule, the
activity projection. It never re-runs ordinary state or completion effects. Activity revisions and
`observedAt` never authorize replacing ordinary lifecycle content at an equal or older lifecycle `seq`.
Establish the activity owner only from an authoritative initial/open/get_state snapshot or directly
bound TUI snapshot, fenced by the current binding/resync generation. An arbitrary event or cached
replay cannot switch owners; an unfamiliar event instance requires authoritative synchronization,
without dropping an independently newer ordinary lifecycle update while synchronizing.

Within the authorized instance, compare `(seq, revision)` lexicographically. Higher revision at equal
`seq` replaces only activity and its ordering metadata, including explicit absence as a clear.
An equal activity key is a replay; lower revisions and older lifecycle sequences cannot replace activity.
On reconnect to the same instance retain the high-water mark. A different authoritative instance
invalidates old activity and establishes a baseline only if its lifecycle `seq` is not older than
retained state. Retired instances and late responses cannot switch it back. Never reset lifecycle or
completion high-water marks or sort instance identifiers. Legacy snapshots without `activityRevision`
follow lifecycle-sequence ordering; at equal `seq` they cannot overwrite versioned activity or clear it.

Clients must not notify or settle while `restoring` is true or `persisted` is false.
Use `completionId` to deduplicate root completion/failure, not `agent_settled` or
`agent_idle`: a queued result or background source can still own unfinished work.
An ordinary reply completing is not itself a request to mark a thread Done.

Clients order lifecycle content by session + `seq`, never by wall clock. An equal lifecycle
`seq` may refresh receipt information and, under the activity ordering rule, the activity projection.
It never re-runs ordinary state or completion effects. Activity revisions and `observedAt` never
authorize replacing ordinary lifecycle content at an equal or older lifecycle `seq`.
An older `seq` never replaces a newer one. Measure "last seen" age on the client's own receipt clock,
not from `observedAt`. A disconnect never infers a terminal state and never erases a known
`done`, `failed`, or `cancelled`. An old `running` means "last known running".

Terminal child `lost` means the runner's FINAL loss of custody or contact for that reported
run. It is not proof that the work or its side effects stopped. A transient transport failure
must not publish terminal `lost`. Revival uses a higher `runEpoch`; a late same-epoch report
never reopens a terminal. These delivery rules change no lifecycle transition.

#### request_self_settle

Records an agent intent for the current root epoch:

```json
{"id":"settle","type":"request_self_settle"}
```

The successful response's `data` is `{ recorded, epoch, humanInputRevision, reason? }`.
Refusal reasons are `not_eligible`, `held`, and `no_epoch`. Subsequent human input,
a hold/fence, or a failed seal invalidates the intent. Unsealed intents fail closed
on restart; sealed decisions retain their identity. Human revisions count only
the shared human-admission hook, including connections that declared
`interactive_user` in their first `set_client_info`, never automatic extension input.

`open_session.spawnedBy` is `{ parentSessionId, rootSessionId, taskId }`, with three
nonempty strings, persisted in the new session header. It identifies execution
children; `parentSession` remains fork/transcript ancestry and does not make a child.
A malformed `spawnedBy` is refused with the error `invalid_spawned_by`.

## Eval cell control

`eval_cells.list`, `eval_cells.peek`, and `eval_cells.stop` are session-scoped
control commands, not model tools. On a shared host include the same `sessionId`
routing handle used for other session commands. They use the session's current
codemode detached-cell manager, the same one used by the eval tool's
`list`/`peek`/`stop` actions. They do not execute a tool, add model context, or
append session history. Stopping a detached cell still delivers the ordinary
`senpi-codemode:notification` completion message to the agent, exactly once.

Both classic and shared hosts advertise the host capability `eval_cells` in
the `data.capabilities` array of a `get_protocol_info` response. It indicates
protocol support, not that codemode is loaded in every session. A session without
the extension returns `errorCode: "eval_cells_unavailable"`.

On shared hosts, the three named commands bypass the foreign-session-holder
guard as explicit reads/cancellation controls. They only touch this host's
manager for the routed session, never the foreign process's cells. List and
peek are observations and do not renew an otherwise idle detached session;
stop counts as activity. Cancelling an already-admitted detached cell may
persist its ordinary completion notification, like the existing abort control.

### eval_cells.list

```json
{"id":"cells","type":"eval_cells.list"}
```

```json
{"id":"cells","type":"response","command":"eval_cells.list","success":true,"data":[{"cellId":"cell_1","language":"js","state":"detached","startedAtMs":1720000000000,"summary":"Read the input files"}]}
```

The array contains live and recently settled cells, in the eval tool's existing
list order. `language` is `js`, `py`, `rb`, or `jl`; `state` is `queued`,
`running`, `detached`, `completed`, `failed`, or `cancelled`. `summary` is
optional, and a queued cell can include `queuedBehind: string[]`. A detached
queued cell has state `detached` and its predecessors in `queuedBehind`.
An empty or not-yet-started manager returns `[]`. Recent snapshots have the
manager's existing retention limits; a removed snapshot is no longer addressable.

### eval_cells.peek

```json
{"id":"tail","type":"eval_cells.peek","cellId":"cell_1","tailBytes":8192}
```

```json
{"id":"tail","type":"response","command":"eval_cells.peek","success":true,"data":{"cellId":"cell_1","language":"js","state":"detached","startedAtMs":1720000000000,"summary":"Read the input files","outputTail":"Read 12 files\n"}}
```

The text-only snapshot includes the list metadata and `outputTail`, taken from
the manager's buffered output. `tailBytes` defaults to 8192, is capped at 65536,
and must be a non-negative safe integer. Zero returns an empty tail. A partial
leading UTF-8 character is dropped, so the returned text never exceeds the byte
budget. Full result bodies, source code, and inline images are not duplicated
in this control response. Available snapshots also include `stateRetained`,
`interruptNote`, `hardLimitSeconds`, and `runBudgetSeconds` when defined.

### eval_cells.stop

```json
{"id":"stop","type":"eval_cells.stop","cellId":"cell_1"}
```

```json
{"id":"stop","type":"response","command":"eval_cells.stop","success":true,"data":{"cellId":"cell_1","language":"js","state":"cancelled","startedAtMs":1720000000000,"summary":"Read the input files","outputTail":"Read 12 files\n","stateRetained":true}}
```

The response waits for interrupt completion and confirms the terminal state,
including whether kernel state was retained. Its output tail uses the default
8192-byte budget. If the cell ended between list and stop, the response succeeds
with its existing `completed`, `failed`, or `cancelled` snapshot: no second
interrupt or completion notification is sent.

Unknown IDs, including IDs owned only by another session, fail with
`errorCode: "eval_cell_not_found"`. A malformed `cellId` or `tailBytes` fails with
`errorCode: "invalid_eval_cell_request"`. Clients must inspect the code or the
returned `state`, not match error text.

The extension handlers are also reachable through
`extension_request {name: "eval_cells.peek", data: {cellId, tailBytes?}}`
(likewise list/stop). Those aliases preserve the same eval error codes.
Use the named commands for shared-host observation/control admission:
generic `extension_request` remains conservatively session-writing.

`RpcClient` exposes `listEvalCells()`, `peekEvalCell(cellId, tailBytes?)`, and
`stopEvalCell(cellId)` with exported `RpcEvalCell` / `RpcEvalCellSnapshot` types.
Failed commands reject with `RpcCommandError.errorCode`.

### Eval liveness event

The existing `wake_source_state` snapshot already reaches RPC clients that
advertise the `extension_events` capability. Codemode publishes it on session
start and each detached-cell transition, including a zero-count snapshot on
settlement. It travels in the normal extension-event envelope, tagged with the
owning routing `sessionId` on a shared host:

```json
{"type":"extension_event","name":"wake_source_state","sessionId":"session_1","data":{"source":"senpi-codemode","activeCount":1,"items":[{"id":"cell_1","description":"Read the input files","startedAtMs":1720000000000}]}}
```

Each event is a full per-source snapshot, not a delta. Filter
`data.source === "senpi-codemode"` and replace the previous detached-cell
liveness set. `items` carry `id`, `description`, and epoch `startedAtMs`.
Use `eval_cells.list` to load initial state after attaching and peek on demand
for output; transitions need no polling. The liveness event itself adds no
model context or history.

## Account display names

`get_provider_accounts` returns secret-free descriptors containing `name`, `source`, `blocked`, `pinned`, and optional `displayName`. Render a named account as `displayName (name)`; keep using the immutable `name` for `account_pin`, `account_remove`, and comparisons. Legacy accounts omit `displayName`.

ChatGPT Subscription OAuth accounts also report `route: "siwc" | "legacy"`, optional `planUsageEnabled`, and `signedOut: true` when the registration is retained without session tokens. These are the same fields `/gpt-account` renders. An explicit `planUsageEnabled: false` means "plan usage not enabled: enable it or use an API key"; an absent flag is not an assertion that permission is enabled. Link usage and limit information to [ChatGPT Settings > Usage](https://chatgpt.com/settings/usage). The shared provider login prompt offers **Continue with ChatGPT** first and keeps **Legacy sign-in (existing users)** available.

`logout` deletes the provider's stored credential. For Anthropic Subscription it first signs every Claude CLI account out of the Claude CLI by its config dir (the same removal as `account_remove`), and its `data` is absent unless one could not be signed out cleanly, in which case it is `{ "notices": string[] }`, one user-facing sentence per account, as for `account_remove`.

`account_remove` answers `success: true` once the account is gone. Its `data` is absent unless something could not be cleaned up, in which case it is `{ "notice": string }`, a user-facing sentence a client should show: a Claude CLI account whose `claude auth logout` could not run or failed (the account and its config dir are removed anyway, but the CLI's stored sign-in may remain), or whose stored account dir is missing, malformed, or a link or file (removed without a sign-out, and a link or file is left untouched).

A blocked account also says why: `blockedReason` is `auth_error` (the provider rejected the key; it is skipped until one request re-probes it at `blockedUntil`, or until a re-login when `blockedUntil` is absent), `rate_limit` (a cooldown that ends at `blockedUntil`) or `disabled` (no end time; replace the credential). Both fields appear only while `blocked` is true, and `blockedReason` is absent when the stored block names no reason. A client choosing an account for a new request should skip `auth_error` accounts rather than send a request that will fail with 401.

Use `/account <provider> rename <id> <display name...>` or the corresponding `/gpt-account` and `/claude-account` commands to name saved accounts; `clear-name <id>` removes only the label. `/gpt-account add` offers optional naming after login is saved, and only when Senpi generated the account ID itself; the Claude lane names accounts through its own login prompt and never asks twice. Blank input or cancellation keeps that login usable. Environment accounts cannot be renamed.

A label is stored NFC-normalized with internal whitespace collapsed, must contain at least one visible character, and may not exceed 32 terminal columns (measured in grapheme clusters, so CJK and emoji count two columns each). Uniqueness within a provider folds case, Unicode compatibility forms, invisible code points, and Cyrillic lookalikes, so two labels that render identically are refused.

`active: true` identifies the account actually selected for this session's last stored-account attempt, including failover. Before an attempt there is no active account to report; neither list position nor a pin proves activity. Signed-out, paused, blocked and unused accounts never report active.

A structured SIWC subscription usage limit reports `paused: true` and `usageUrl: "https://chatgpt.com/settings/usage"` for the originating account. Its internal retry probe deadline is not a provider reset time, so `blockedUntil` is omitted for this pause, even after a probe becomes due. A successful probe or changed credentials clears the pause. `/gpt-account` renders the same paused state and Usage link.

## Account order

By default a provider's accounts are picked per session by rendezvous hashing, and a failed account fails over in that hash order. A user order replaces that ranking: requests try the pinned account first, then the first unblocked account in the order, then the accounts the order does not name, in hash order. On the Claude subscription lane, a session keeps the account its conversation already lives on while that account can serve, ahead of the order, so setting an order does not move running conversations.

`get_provider_accounts` lists the accounts the order names first, in that order, then the rest in stored order (the hash ranking is per session, so a listing cannot show it). It reports `ordered: true` while a stored order names at least one listed account. A pinned account serves first wherever it is listed; read its `pinned` flag. Every lane that picks an account honors the order: the generic credential pool, the Claude subscription lane and the Cursor CLI lane.

#### account_order

Set the order, or clear it with `names: null`:

```json
{"id": "o1", "type": "account_order", "provider": "openai", "names": ["work", "default"]}
```

```json
{"id": "o1", "type": "response", "command": "account_order", "success": true}
```

`names` may name a subset; accounts it leaves out come after it. The command fails without changing anything when a name is not one of the provider's accounts, appears twice, or the list is empty, and when the provider has no stored credential (the order is kept beside the pin in `auth.json`). Removing an account drops it from the order. Success emits `auth_accounts_changed`. Only account names cross RPC, never credential material.

#### account_reset

Unblock one account using its immutable name. Hosts that answer it advertise `account_reset` in `get_protocol_info`.

```json
{"id": "reset1", "type": "account_reset", "provider": "openai", "name": "work"}
```

```json
{"id": "reset1", "type": "response", "command": "account_reset", "success": true}
```

The response is correlated by `id` and sent only after the engine operation settles.
Success reuses `auth_accounts_changed { provider }`; reread `get_provider_accounts` for
the authoritative state. This uses the same full reset as `/account <provider> reset <name>`:
the named account's pool sidecar health, provider-stored `blockReason`, `blockedUntil`,
`modelBlocks` and `slotState` are cleared. Credentials, names, display names, pins,
ordering and all unrelated accounts are preserved. Stored and environment account
selectors match the listing. It clears local health state, not a provider limit or
rejected sign-in; the next request may block the account again.

An unknown name returns `success: false` with `errorCode: "account_not_found"` and
does not mutate accounts or publish a change notice. Invalid selector types return
`invalid_argument`. A failed write returns `account_reset_failed` with a credential-free
message, never a success notice. The two
health stores are written sequentially, not as a cross-file transaction.
`RpcClient.resetProviderAccount(provider, name)` awaits acknowledgement and rejects
with `RpcCommandError` on failure.

This command is additive. Older hosts do not advertise `account_reset` and reject it as unknown; the typed client rejects
that response rather than reporting success. Existing account listings without
optional block reason or expiry fields remain readable.

#### test_provider_account

Re-run the sign-in connection test on one Claude subscription account, for example to retry a failed `check`. Hosts that answer it advertise `provider_account_test` in `get_protocol_info`.

```json
{"id": "t1", "type": "test_provider_account", "provider": "anthropic-subscription", "name": "work"}
```

```json
{"id": "t1", "type": "response", "command": "test_provider_account", "success": true, "data": {"check": {"model": "claude-opus-5-5", "outcome": "ok", "at": 1793000000000}}}
```

The test is one "Reply with OK" turn pinned to that account with account fallback off, on the model the settings' default resolves for `anthropic-subscription` (the default model when the default provider is `anthropic-subscription`, else that provider's default model). The turn runs on that account even while it is blocked (the block is the question the test answers); no other account is tried or re-probed, and the test stores and clears no block, pin or order. Its result is stored as the account's `check` (the same field `get_provider_accounts` reports) and returned; like any turn, it also saves the account's profile when Claude Code reports a changed one. A failed turn answers `success: true` with `outcome: "failed"` and a short `reason` kind such as `auth_error`, `billing` or `timeout`. The command writes `auth.json` and spends one model turn, so like `account_pin` and `account_remove` it needs the session attached and is refused while another client holds it.

Errors: `unsupported_provider` for any provider other than `anthropic-subscription`, `unknown_account` when no stored account has that name, `unsupported_account` for an account that is not a Claude CLI sign-in (an environment token account), and `needs_sign_in` for an account that must sign in again (`signIn: "needs_sign_in"` in `get_provider_accounts`); no turn runs for any of them.

## Starting RPC Mode

### Attach the TUI to an RPC endpoint

```bash
senpi --attach /path/to/endpoint.sock --session <ref>
senpi --attach unix:///path/to/endpoint.sock --session <ref>
```

On Windows, pass the endpoint's logical filesystem path, not the derived pipe name.
The existing socket transport derives the named pipe and reads its secret file.
POSIX host endpoints use the existing challenge-response authentication; terminal
control endpoints use their adjacent secret file. `SENPI_RPC_KEY_ROOT` selects a
host credential root without changing the attached session's configuration.

Both stdin and stdout must be terminals. `--attach` cannot be combined with
`--mode rpc`, `--mode json`, `--print`, or session creation options.
The reference is an existing routing id, durable id, unambiguous durable-id prefix,
or listed session path. An absent session is refused, never created or resumed.

This presentation declares `interactive_user`, calls `attach_session`, reads
`get_state` and `get_entries {tail:100}`, and subscribes with `mirror:"all"`.
`/history` reads an earlier page with `before:next_before`. Enter sends a prompt,
or steers a running turn; `/steer <text>` explicitly steers. Escape or `/abort`
sends Stop. Inputs carry `clientMessageId`; dialog responses carry `answerId`.
The existing selector, text editor, and question UI collect permission and
question answers. No retry automatically repeats an unacknowledged mutation.

The presentation attaches only to a session no release of its own can end: its
`list_sessions` row must report `retain_on_disconnect: true` (a session opened with
`open_session {retain_on_disconnect: true}`, or a terminal's own session on its control
endpoint). Any other session is refused before `attach_session` with
`AttachRefusedError` code `session_not_retained`, because a non-retained session closes
when its last attachment leaves, and this view could be that attachment. Retention is
never revoked once granted, so the check holds for the whole attachment.

`/quit` or the configured exit shortcut releases only this presentation through
`release_attachment`. On a retained session that never closes the session or stops the
endpoint, and neither does a dropped connection. A disconnect leaves the last transcript
and state visible with a Disconnected status (and its reason when the endpoint sent a
record the view could not read). Exit and attach again to reconnect.

A dialog answer is tracked by its reply. When the endpoint refuses it (for example
`question_incomplete`, or `grant_answer_refused` from a connection that may not answer a
grant) or sends no acknowledgement in time, the dialog comes back with the reason. When
the endpoint no longer waits on it (`question_already_resolved`,
`unknown_extension_ui_request`), the dialog stays dismissed and the status says why. A
refused prompt or steer keeps its text in the editor. A width change sends
`set_client_info {width}`.

### Private secret input

`get_protocol_info.capabilities` advertises `secret_input_v1`. A presenter must
explicitly send `set_client_info` with both `secret_input_v1` and `interactive_user`
on its own connection, including classic stdio. Launch options and
`SENPI_RPC_CLIENT_CAPABILITIES` do not establish secret support.

```json
{"type":"set_client_info","width":80,"capabilities":["interactive_user","secret_input_v1"]}
{"type":"extension_ui_request","id":"request-id","method":"input","secret":true,"title":"Credential","timeout":1800000,"deadlineAtMs":1900000000000}
{"type":"extension_ui_response","id":"reply-id","uiRequestId":"request-id","answerId":"fresh-answer-id","secret":true,"value":"synthetic-example"}
```

Routed frames also carry `sessionId`. A cancellation replaces `value` with
`cancelled:true`. Exactly one is required, along with a nonempty opaque `answerId`;
`confirmed`, `answers`, `comment`, extra payload fields and progress updates are
refused. The pending host record determines sensitivity even if the incoming
`secret` marker is missing. Never put a value into an ID or send it as progress.

Requests belong to one immutable presenter and live session incarnation. The
initiating attached client must itself be eligible; it cannot borrow another
client's declaration. Background calls (no connection's command raised them)
choose an eligible attached presenter in registration order, but only a local
one: a connection that declared a delegation (`declare_delegation`) or a
`remoteOrigin` is never chosen, whatever it declares, and with no local
eligible presenter the call ends `secret_input_unavailable` (`no_presenter`). A
background request whose presenter later declares a `remoteOrigin` ends
`unavailable`. Unsupported presentation raises `secret_input_unavailable`
before emission. A secret raised by a remote device's own turn is presented only
on that device's connection; a relay forwarder never declares `secret_input_v1`
for it, so that secret ends `secret_input_unavailable` (`client_unsupported`)
with no prompt and no notice anywhere. Worker isolates negotiate
accepted/refused-with-reason with the parent before registering a request; a
refusal is not user cancellation.

The private transport bypasses replay, observer, transcript and trace-record
publication. Generic `get_state`/`get_snapshot` contain no secret prompt or
receipt. Another attached connection sees only that a secret is pending, and
only when its `set_client_info` declared `raiser_notice_v1`:

```json
{"type":"secret_input_notice","sessionId":"session-id","uiRequestId":"request-id","title":"Credential","deadlineAtMs":1900000000000,"raisedBy":"socket-1"}
{"type":"secret_input_notice_settled","sessionId":"session-id","uiRequestId":"request-id","outcome":"answered"}
```

`raisedBy` is the raising connection, or `"agent"` for a background call;
`remoteOrigin` is present when the raising connection declared one. A notice
never carries a value, draft, `answerId` or receipt, it is not replayed, and it
grants no answering authority: an answer from that connection is still
`secret_answer_refused`. A connection without `raiser_notice_v1` receives
nothing, as before. The connection that raised the request is never a
recipient, including when its own lane was refused (`client_unsupported`,
`no_presenter`) and the request proceeds on the sealed route. The owner can
query its bounded, value-free `get_state.answeredUiRequests` receipts after
acknowledgement loss. Discard the
value instead of resending or saving it in a reconnect queue. A missing receipt
after eviction/restart means unknown outcome, not proof the callback did not run.

The owner receives `secret_input_settled` with `id` and
`outcome: answered | cancelled | timed_out | unavailable`. It must destroy its
field and editing buffers on that event, disconnect, or unmount. The original
`deadlineAtMs` is authoritative across resize, snapshots and attach re-offers.
Late or foreign answers are refused before human-input admission. Responses use
the existing `extension_ui_response` acknowledgement with fixed errors
`secret_answer_refused`, `invalid_secret_response` or
`unknown_extension_ui_request`, and metadata-only dispositions.

Clients must mask before rendering, retain values only in private live state,
and never record raw response frames, parser inputs, validation actuals or error
causes. A desktop integration needs its own authenticated, untraced transient
response route; ordinary persisted question-answer commands are not suitable.
Advertise the capability only after that route and the renderer support it.
Role-carrying automated/control connections must omit `secret_input_v1`.

#### Sealed holders (same-account presenters)

On an in-process host whose embedding distribution injected an account authority that can mint host tokens, a
secret prompt can also be answered by a same-account presenter, sealed end to end (D11 secret phase). A sealed
holder is a current MCP presenter grant whose principal enrolled by same-account attestation (never the inherited
launch principal), whose signed `mcp_presenter_acquire` listed `secret_input_v1` in `features`, whose
attestation has not lapsed, and whose session has a valid host token. Holders are snapshotted when the prompt is
created; a grant acquired later is not offered it.

- A prompt whose raiser route refuses (for example `no_presenter` for a background call) proceeds when it has at
  least one sealed holder; with none, the refusal is unchanged.
- Each holder receives one private `mcp_presenter_secret_request` on its presenter connection, never on an event,
  snapshot, mirror or replay lane: `{type, v: 1, sessionId, durableSessionId, uiRequestId, title, placeholder?,
  deadlineAtMs, hostInstance, hpkePk, hostPk, hostToken, sig}`. `hpkePk` is the prompt's own X25519 key and
  `hostPk` the host instance's Ed25519 key (both raw 32 bytes, unpadded base64url). `sig` is 128 lowercase hex
  characters: the host key's Ed25519 signature over `"omo-secret-request-v1\n" + JSON.stringify(B)`, with
  `B = ["omo-secret-binding-v1", hostInstance, hostJkt, durableSessionId, uiRequestId, deadlineAtMs, hpkePk,
  displayHash]`, `hostJkt` the RFC 7638 thumbprint of `hostPk` (equal to the host token's `cnf.jkt`), and
  `displayHash = b64url(SHA-256(JSON.stringify([title, placeholder ?? null])))`. These byte formats follow
  omo-relay-spec decision 0022.
- When the host token is re-minted, every holder of a pending prompt receives
  `{type: "mcp_presenter_secret_token", v: 1, hostInstance, durableSessionId, hostToken}`. `B` names the host
  key, not a token, so the prompt stays verifiable under the new token.
- These records reach only grants that negotiated `secret_input_v1`; any other client sees today's bytes.
- A prompt with sealed holders but no raiser route never writes a raiser lane, the sole stdio lane included, and
  never accepts an `extension_ui_response`. It stays pending while any holder's grant is current, through a raiser
  disconnect or capability change, and ends `unavailable` when the last holder's grant goes.
- An attached connection that declared `raiser_notice_v1` and is not a sealed holder keeps receiving
  `secret_input_notice`; a holder receives the request instead.
- A holder answers on its presenter connection with `mcp_presenter_secret_answer`. A value answer is
  `{type, id, v: 1, grantId, uiRequestId, answerId, stepup, enc, ct, sig}`; a cancel is
  `{type, id, v: 1, grantId, uiRequestId, answerId, cancelled: true, sig}`. `id` is 1-128 characters and
  `answerId` 1-256. `enc` (32 bytes) and `ct` (HPKE base mode, DHKEM(X25519, HKDF-SHA256) / HKDF-SHA256 /
  AES-256-GCM, at most 64 KiB + 16 bytes) are unpadded base64url. `sig` is the installation key's Ed25519 signature,
  verified strictly (canonical points, no small-order or non-prime-order key, `S < L`).
- The host checks, in order:
  1. the exact shape;
  2. that the sender holds a grant in the prompt's sealed snapshot that is still eligible;
  3. for a prompt that has already settled, the receipt: `replay` for the same `answerId` and principal, else
     `already_answered`;
  4. the envelope signature;
  5. for a value, the issuer step-up token through the injected authority (its account, device, host device, request
     binding and expiry no later than the deadline);
  6. at the latch, synchronously and in this order: the prompt is still pending; the step-up `jti` is unused in this
     host incarnation, and it is spent here; the prompt is before its deadline; the grant is current; the
     ciphertext opens to a canonical padded value. A claim refused after the `jti` check has used up that token.

  A value answer that loses the race is never decrypted, and a ciphertext that does not open leaves the prompt open.
- The answer is acknowledged on the sender's connection only:
  `{type: "mcp_presenter_secret_reply", id, disposition: "applied" | "replay"}` or
  `{type: "mcp_presenter_secret_reply", id, error}`, where `error` is `invalid_secret_response`,
  `secret_answer_refused`, `secret_stepup_refused`, `already_answered` or `unknown_extension_ui_request`.
- When the prompt ends, every holder that received its request receives the value-free
  `{type: "mcp_presenter_secret_settled", v: 1, uiRequestId, outcome, elsewhere}`, with `elsewhere: false` only for
  the holder whose answer won. A raiser connection still receives `secret_input_settled` with unchanged bytes, and
  `answeredUiRequests` lists raiser-route receipts only.
  If the prompt ends before its asynchronous request key is ready, no request or settled frame reaches holders.
  Key-generation failure ends the prompt as `unavailable`.
- Worker sessions (the worker runtime) behave the same for clients.
  - The host selects holders, signs the request and authenticates an answer: shape, sender, envelope signature and
    step-up token.
  - The session's isolate keeps the per-request key, the receipts and the step-up `jti` cache. It answers `replay`
    or `already_answered` for a settled request, then claims, opens and settles.
  - Answers for one request are forwarded one at a time with at most four queued; a further answer is
    `secret_answer_refused`.
  - For a settled request, the host's token checks run before the isolate's receipt lookup. A replayed answer whose
    step-up token has since expired is therefore `secret_stepup_refused` on a worker session, where an in-process
    session answers `replay`.
- A terminal (TUI) session that runs a control endpoint with an account authority offers its own secret prompts to its
  sealed holders, the same-account presenters attached over the control socket:
  - they receive `mcp_presenter_secret_request` on their control connection and answer there with
    `mcp_presenter_secret_answer`;
  - the terminal's own input and the sealed answers race one latch, the first answer wins, and the losing side is
    dismissed;
  - a rejected local input cancels the pending latch immediately, dismissing the input and settling offered holders
    with `outcome: "cancelled"` without forwarding the error;
  - holders receive `mcp_presenter_secret_settled` as above, `elsewhere: true` when the terminal answered;
  - without a sealed holder the terminal's prompt is unchanged.

### RPC client lifecycle

`RpcClient` accepts an `onDisconnect` callback for an established socket and rejects subsequent transport operations with the typed `RpcTransportGoneError` (also detectable with `isTransportGoneError`). Callers should use the callback to begin recovery and keep the error text out of user-facing output.

Prompt acceptance can require compaction before the host emits its response. After observing
`compaction_start` for its session, `RpcClient` gives pending and subsequent prompts a bounded
45-minute-and-30-second acknowledgement budget: up to 15 minutes of remote compaction, a
30-minute maximum local-summary override, and the ordinary response allowance. A matching
`compaction_end` restores the 30-second response deadline. Each compaction operation is tracked by
its operation ID (older hosts that omit IDs remain supported), so a stale or overlapping start never
hides another operation's end, and a start whose end never arrives stops counting once it is older
than that budget. However many compactions start and end while a prompt waits, it never waits more
than 46 minutes from when it was sent. Outstanding prompts retain their originating session, so
another lease's compaction does not change their deadlines. Other commands retain their normal
deadlines, and a disconnected transport still rejects immediately. Compaction events do not
themselves acknowledge a prompt: its actual response determines success and disposition.
A timeout does not establish that the host rejected the input, so do not automatically resend it.

```bash
senpi --mode rpc [options]
```

Common options:
- `--provider <name>`: Set the LLM provider (anthropic, openai, google, etc.)
- `--model <pattern>`: Model pattern or ID (supports `provider/id` and optional `:<thinking>`)
- `--name <name>` / `-n <name>`: Set the session display name at startup
- `--no-session`: Disable session persistence
- `--session-dir <path>`: Custom session storage directory

### Client capabilities

Optional additive records are enabled through the comma-separated
`SENPI_RPC_CLIENT_CAPABILITIES` environment variable:

```bash
SENPI_RPC_CLIENT_CAPABILITIES=extension_events senpi --mode rpc
```

Rebranded distributions read the equivalent variable under their configured environment prefix
(for example `OMO_RPC_CLIENT_CAPABILITIES`). Unknown capability names are ignored. Advertising
`extension_events` opts the client into generic extension-owned event records; clients that omit it
retain the previous wire stream unchanged.

#### grant_select

Advertise `grant_select` in the connection's `set_client_info` (or the client
capabilities environment variable for classic stdio RPC) only when the client
renders `extension_ui_request` with `method:"select"` and returns the selected
option through `extension_ui_response`. The unrelated `question` capability
does not authorize these dialogs.

Project skill MCP environment decisions are select requests with
`grantSelect:true` and `timeout:120000`. Only the selected capable connection
may answer. Only **Grant and save permanently** persists the names for that
declaration; **Start without them**, cancellation, disconnect and timeout save
nothing. A client that never answers reaches the deadline and the server starts
filtered. A headless or question-only client receives no grant dialog.

Without a raising connection that declares `grant_select`, the dialog goes to the
first attached local connection that does; a connection that declared a
delegation or a `remoteOrigin` is never that fallback, and is never registered as
an in-process grant presentation. With no local candidate the decision ends at
once with nothing saved. The other attached connections that declared
`raiser_notice_v1` receive
`{type:"grant_select_notice", sessionId, uiRequestId, title}` and, when the
dialog ends, `{type:"grant_select_notice_settled", sessionId, uiRequestId}`;
an answer from them is still `grant_answer_refused`.

Sessions retain skill-link and withheld-environment warnings. Every attached
RPC connection receives the current snapshot as warning `notify` requests on
attach and each changed generation. A late attachment receives the same
reasons; another presentation cannot consume them on its behalf. This also
applies when the shared host runs the session in a worker.

#### event_resync

A socket client may advertise `event_resync` in its connection-scoped `set_client_info`.
This opts that connection into same-connection recovery instead of an event-queue overflow
or stall disconnect. An old client that omits the capability keeps the legacy `overflow`
record and disconnect behavior. Ordinary supersession remains lossless in both modes.
A later `set_client_info` replaces the capability list: omitting `event_resync` revokes
recovery for future pressure. An already pending gap is still reported when the socket
drains; the legacy stall policy applies if it does not drain.

The host immediately sends `{"type":"rpc_ping"}`. The client answers by sending
`set_client_info` without a request id, repeating its complete capability list, and repeats
that heartbeat every 10 seconds until the socket closes. The existing connection-scoped
handler acknowledges liveness; no session command or session attachment is needed.
Each id-less heartbeat produces the id-less response
`{"type":"response","command":"set_client_info","success":true}`; clients consume it
as a heartbeat acknowledgement, not as a response to an outstanding request.
Heartbeat pulses travel in the opposite direction from event traffic, so a blocked event
reader can still prove it is alive. The host retains at most one buffered ping during a gap.
An event stall still starts at 30 seconds of host loop-served time, but it sheds the queue
rather than closing. A subsequent served budget without a heartbeat closes the peer.
The host's loop-blocked-time credit also applies to that liveness deadline.

On overflow or stall, the host drops buffered events and stops accumulating new events until
transport drain. Correlated replies that fit within the queue's byte bound are retained and
sent first; a reply that cannot fit has an unknown outcome. Every gap sends an untagged
connection-level marker, including when the connection has no attached sessions. Its
`replyLost` flag says whether a correlated reply was discarded. It then sends a snapshot for every affected
session attached to that connection:

```json
{"type":"resync_required","reason":"stall","replyLost":false}
{"type":"resync_required","reason":"stall","sessionId":"rpc-1","message":{"role":"assistant","content":[{"type":"text","text":"The complete partial reply"}]}}
```

`reason` is `stall` or `overflow`. A session's `message` is the complete current in-progress
message, or `null` when none exists. If a handle was detached during the gap, its record also
has `"closed":true`; retire that handle through the normal session-close path without closing
the socket. The affected handle set is remembered when shedding begins, so losing a close
event cannot silently leave a client attached to a nonexistent handle.
Only the handle set is frozen at shed start. Message snapshots are read at drain time,
in the same synchronous step that reopens admission, and delivered before subsequent
deltas. They replace the client's partial-message
baseline; they are not text to append a second time. Media placeholders still apply.

With compact socket updates enabled, a snapshot's tool calls carry only their parsed
`arguments`, never the raw argument text streamed so far. For every tool call still open
in the snapshot, the session's `resync_required` record is followed by a
`message_tool_arguments_reset` record. That reset comes before any later `toolcall_delta`
of that call. A tool call that had already ended at the cut gets no reset.

```json
{"type":"message_tool_arguments_reset","sessionId":"rpc-1","contentIndex":1,"rawArgumentPrefix":"","parsedThrough":0}
{"type":"message_update","sessionId":"rpc-1","usage":{...},"assistantMessageEvent":{"type":"toolcall_delta","contentIndex":1,"delta":"{\"command\":\"ec"}}
```

| Field | Meaning |
|-------|---------|
| `contentIndex` | The tool call's block index in the snapshot's `content` |
| `rawArgumentPrefix` | The raw argument text that replaces the client's buffer; `""` at a cut |
| `parsedThrough` | How much of `rawArgumentPrefix` has been parsed into `arguments`; `0` at a cut |

Replace that call's buffered raw arguments with `rawArgumentPrefix` and keep its parsed
`arguments` from the snapshot. The call's next `toolcall_delta` starts at offset 0 and
carries the whole raw prefix accumulated before the cut. Later deltas append to it as usual,
and `toolcall_end.toolCall` stays authoritative. A client that renders tool arguments only
from `toolcall_end` may ignore the reset. None of the in-repo clients advertises `event_resync`
yet; handling the reset before one does is tracked in senpi#5300.

Every untagged marker requires connection-wide reconciliation: unsubscribe the previous
`subscribe_sessions` subscription and subscribe again, replacing the status snapshot and
restarting its sequence at zero; re-read `list_sessions` and lifecycle state; and re-read
each live session's `get_state.pendingDialogs` to restore pending select, confirm, input
and editor requests. These dialogs are distinct from `pendingQuestions`. Discard obsolete
status sequence expectations and dialogs absent from the authoritative state.

If `replyLost` is true (or absent on an earlier host), outstanding requests may have lost
their answers: settle them as **outcome unknown**, not success, and never automatically
replay a mutation. When it is false, keep outstanding requests intact. Keep the socket,
its epoch and its session handles. For each tagged marker, refresh that session with
`get_state` and the existing paginated `get_entries` path, reconcile pending questions and
run state, and replace its streaming preview from `message`. A read-only request may be
retried. A closed-handle snapshot retires that session, not the connection.
Another overflow during recovery produces another gap and a newer snapshot.

#### Compact recovery state limits

Behind `SENPI_ENGINE_SOCKET_COMPACT_UPDATES` (off by default), the host also keeps a compact recovery state for
each session. It has one protocol depth limit, `COMPACT_PROTOCOL_MAX_DEPTH` = 1,024 nested arrays or objects
(`[[1]]` is 2 deep; the record object itself is the first level), set well below the native JSON limits of Node 24
(about 6,185 levels) and Bun 1.4 (40,000). A record nested deeper is refused before any compact fold clones or
serializes it (its canonical projection, its call or component fold, the settled terminal of a `message_end`), with
`CompactWriteError` reason `unsupported_value` carrying `limit: 1024`. The refusal costs only that session event's
compact fold, both projections of it: the session's compact state stays available, the legacy record is still
delivered, the refusal is counted once per session event in the lane's `refusedRecords` status (however many of
the event's projections exceed the limit) and the host reports it once on stderr as
`senpi rpc acceptance: compact record refused: unsupported_value (depth above 1024)`. Any other loss of a record
still ends that session epoch's compact state. Every refused record of the session is counted the same way whether
or not the compact state is still live: after such a loss, refusals on either projection keep counting.

The legacy JSONL stream has no protocol depth limit: a record deeper than 1,024 levels is delivered unchanged to a
legacy client. This holds whether or not the client advertises `media_placeholders`: the placeholder transform
walks a record without recursion. Serialization has no depth limit either (senpi#5702): the writer uses the
runtime's native `JSON.stringify`, and where that overflows its own stack (about 3,000 chained `get_tree` entries
on Node 24, 18,000-20,000 on Bun 1.4, fewer when a value uses `toJSON`) an explicit-stack writer with the same
semantics writes the same bytes. A `get_tree` answer for a 10,000-entry session therefore arrives whole, in its
usual shape `{ tree, leafId }`, on the in-process host and in a worker session alike.

A reply (`type: "response"`) that still cannot be written, for any method and any reason (a `BigInt` or a cycle
in its value, a `toJSON` that throws), is never dropped: the caller receives, for the same `id`,

```json
{"id":"<request id>","type":"response","command":"<command>","success":false,"error":"<command> response could not be written: <cause>","errorCode":"response_unwritable"}
```

and the session keeps serving later requests. The host reports it once on stderr as
`senpi rpc host: <command> response unwritable (<cause>); answered response_unwritable (session <id>)` and counts
it with the writer's refusals. This supersedes RULING-68's "refused, never delivered" for replies. A non-reply
record whose path still overflows the stack outside the writer is refused as before, as the typed
`LegacyRecordDepthError`, reported as
`senpi rpc host: legacy record refused: <type> nests deeper than this runtime's JSON engine limit (session <id>)`,
and the session keeps running.
A worker session sends a record deeper than 1,024 levels to the host as JSON text, so the host's structured-clone
reader (which stops near 4,000 levels on Node) never drops it.

#### get_recovery_page

Behind the same flag, one bounded page of a frozen checkpoint component, through the recovery-token owner
(senpi#4272, R4.B3). The command is additive: with the flag off it answers the typed refusal `{"success": false, "error": "feature_disabled", "errorCode": "feature_disabled", "errorData": {"feature": "compact_updates"}}` (plus `sessionId` when the request named one), as does the classic single-session handler, which has no compact transport; with `SENPI_RPC_REQUIRE_ATTACH=1`, an unattached caller of a session-addressed request gets the attachment gate's `session_not_attached` first.

Compact generations are allocated per durable session, not per socket or accepted-state epoch (RULING-99).
A reconnect receives a higher generation; a host restart resumes above the persisted reservation ceiling in
the agent directory. Generations may have gaps. The engine reserves ranges asynchronously before synchronous
cut issuance; no token, manifest or event can name an unreserved generation. Exhaustion or storage failure
refuses a new cut as `storage_unavailable`, never by resetting the counter. A concurrent owner cannot reserve
the same session while its kernel ownership lock is held. Materializers continue to refuse lower generations
as `stale_generation`.
On new-session, switch and fork replacements, the owner rebinds before publishing the replacement's first cut.
Its new range starts above both the lane's previous reservation ceiling and the target session's persisted floor;
synchronous cut requests refuse while that asynchronous reservation is pending.

```json
{"type": "get_recovery_page", "sessionId": "rpc-1", "token": "socket-3:7", "admissionId": "attach-9",
 "componentRef": "c-0000000000000007:003", "requestId": "r-12", "cursor": "p1:1:131072:..."}
```

- `token` and `admissionId` name a checkpoint this connection holds (its manifest's `token` and `admissionId`);
  `componentRef` is a catalog ref under that token; `requestId` is the client's own bounded id for this request;
  `cursor` continues a component from the previous answer and is omitted for a component's first page. Every field
  is an opaque bounded protocol id (ASCII `[A-Za-z0-9][A-Za-z0-9:_-]*`, at most 128 bytes), parsed before any use.
- The answer's `data` is `{requestId, token, generation, componentRef, ordinal, offset, length, digest, bytes,
  cursor, complete, repair}`: `bytes` is the base64 of exactly `length` raw stored bytes of the component at raw byte
  `offset` (the component's stored UTF-16LE bytes, the representation the catalog's lengths and `leaf` digests
  describe); `digest` is the catalog's `fragment`-domain SHA-256 over those raw bytes, so a client verifies it
  AFTER base64 decoding, never over the base64 text; `cursor` is the opaque cursor of the next page or `null` once
  `complete`. The page budget is `FRAGMENT_MAX_BYTES` = 131,072 raw bytes; its base64 envelope is
  `FRAGMENT_ENVELOPE_MAX_BYTES` = 174,764 bytes (derived: four characters per three raw bytes), the one page the
  worker transport's initial credit is also sized from.
- `ordinal` advances by one per page served under a token, whichever component is paged, and never wraps: at the
  53-bit bound the request is refused `recovery_ordinal_exhausted` (re-admit for a new token). One request is active
  per token at a time; a second concurrent one is refused `recovery_busy` (`hint: "retry"`), takes no slot and
  keeps no memory, and that includes a request whose component is still being verified. At most 8 page requests are
  outstanding on one socket across its tokens; the ninth is refused `recovery_request_limit`. A connection that
  closes while a component is still being verified for it stops that verification at the next stored leaf: its slot
  and its token are freed then, not when the verification would have ended, and nothing is kept.
- An exact retry (same `requestId`, `token`, `componentRef` and `cursor`) of the token's current page answers the
  identical bytes from the one page the host keeps per token, without a read; that page is freed when the next
  request advances the token or the token ends. A different request under the same `requestId` is refused
  `recovery_request_mismatch`. A `requestId` used before the token advanced is a new request only when it carries
  no `cursor` (a component's first page); with a cursor behind the token's current ordinal it is refused
  `recovery_cursor_out_of_range`, never served as a fresh page.
- A cursor is bound to the peer, routing session, token, generation and component it was minted for and
  authenticated under a per-process key. It has exactly one encoding (its numbers carry no leading zero), so any
  re-encoding is an altered cursor. Presented by another connection or session, altered, or minted by a previous
  host process, it is refused `recovery_invalid_cursor` with `hint: "restart_from_catalog"`; an authentic cursor
  whose ordinal is not the token's current one is refused `recovery_cursor_out_of_range` with the same hint. A token
  minted for another connection, session or admission is `recovery_repair_needed` with `reason: "unknown_token"`
  and nothing else. A token superseded by a newer admission of its stream answers `recovery_repair_needed` with
  `reason: "superseded_token"` and `newerGeneration` while an operation still holds it, and `unknown_token` once
  it is reclaimed. The owner's other typed failures arrive as `recovery_repair_needed` or
  `recovery_storage_unavailable` with `errorData` carrying the failure. Every refusal happens before any byte is read.
- The loaded transcript base (the entries a session was opened with, named by the catalog's `transcript/base`,
  `opaque/base` and `source/base` members as `{source: "file", first: 0, count, idFingerprint}`) is paged under the
  reserved ref `<catalogRoot>:base` (the manifest's `catalogRoot` with the `base` step; it is cut-scoped like every
  ref, and it is pages only, never a catalog node or component read). Its bytes are one stamped row per base entry in
  file order,
  `{index, id, source: "file", parentId, kind, family}` followed by a newline, UTF-16LE like every component, so a
  page of it is verified exactly like any other page. A client anchors the join to the catalog: the SHA-256 over
  `kind NUL id LF` of every row, in order, is the catalog's `idFingerprint`. A line the loader parsed that is no
  session entry is a row too (never dropped): its `kind` and `id` are the string forms of its `type` and `id`
  (`"undefined"` when absent), its `parentId` null unless a string, and its `family` that of its kind. The host opens
  the session file only for this route, asynchronously, verifies its identity, count, `idFingerprint` and a content
  fingerprint the load took over the lines it read before the first page, and re-checks the identity and every row a
  page re-derives against that open. Any change to the base since the load (replaced, truncated, missing, or any
  edit to its lines, ids or content, before or after the first page) is `recovery_storage_unavailable` with `reason`
  `base_file_replaced`, `base_file_truncated`, `base_file_missing` or `base_fingerprint_mismatch`, never stale rows. With a base present, the transcript, opaque and source families are
  complete: their members are the catalog's rows of this epoch plus the base stream's rows of their family.

**Recovery manifest (`componentRef: "manifest"`, senpi#5397, RULING-128).** Paged under a token with
`componentRef: "manifest"` (one page), the manifest is one JSON object `{format: "senpi-recovery-manifest", version: 1, socketEpoch, admissionId, routeKind, session,
sessionEpoch, generation, sequence, historyVersion, token, leaf, activeMessage, turn, checkpointDigest, catalogRoot,
catalogRootLength, requiredKinds}`. `checkpointDigest` is the `root`-domain digest of the catalog root node that
`catalogRoot` names. `requiredKinds` is the sorted (code-unit order), de-duplicated list of the catalog families this
cut's root requires: its `complete` families only; a family the engine produced only partially for this cut (an
unavailable transcript leaves `transcript`, `opaque` and `source` partial, a refused client correlation leaves
`identity` partial) is left out. The cut's `families/families` registry component carries the same list as its own
`requiredKinds`, so the list is part of the content `checkpointDigest` covers; a client that reads the registry can
compare the two. The field exists only in this flag-on compact manifest; legacy and flag-off output is unchanged.
A client:

- reads `requiredKinds` verbatim and opens exactly those families, never deriving the list from a built-in family
  list or `CATALOG_FAMILIES`;
- refuses a manifest without `requiredKinds` (an older engine) as `manifest_missing_required_kinds`, with no
  fallback to a built-in list;
- refuses a manifest naming a kind it does not know as `manifest_unknown_required_kind`, never ignoring it, so a
  family a newer engine adds cannot leave a root half opened;
- refuses a manifest whose `requiredKinds` differs in any way (a kind added, dropped, repeated or reordered) from the
  complete families of the cut's `families/families` registry component, read and verified against the root entry
  `checkpointDigest` covers, as `manifest_required_kinds_mismatch`. The digest covers that component, not the
  manifest field, so this comparison is what binds the list to the cut. senpi's reference reader is
  `readRequiredKinds` (`compact-recovery-manifest-kinds.ts`).

The golden `docs/engine-socket/fixtures/recovery-manifest/` is a manifest with one partial family excluded.

**S14 repair policy (RULING-84 and RULING-87).** Success carries `data.repair`; a typed recovery failure carries
`errorData.repair`, using the same `RecoveryRepairAdviceSchema` as the client package's
`RecoveryRepairController`. Advice contains `state` (`ok`, `repair_needed`, or `storage_unavailable`),
`healthRevision` (a persisted decimal counter), `source` (`sessionEpoch`, accepted `sequence`),
`hint: "restart_from_catalog"` and `retryAfterMs` (100 to 2,000 ms, jittered, or zero on success).
An unknown or foreign token receives null revision and source, never another admission's state.
Storage unavailability ends only the recovery attempt, not the connection, and does not resubmit a prompt or
fall back to current-root content. For storage failures, repair restarts at the catalog with a fresh cut after
the backoff and only when either health revision or accepted-source identity changes.
An `unknown_token` or `released` refusal instead requests one immediate catalog restart, even with unchanged
or null revision/source. The driver supplies `observe(advice, now, { token, reason })`, using the refused request's
token ID (or event lease ID) and `errorData.reason`; these are request context, not extra advice fields.
A token receives at most one restart from this controller. If the fresh cut's token is also refused immediately,
the controller waits for the bounded backoff before restarting it, without requiring a health/source change.
Repeated observations of an already restarted token wait and cannot spin; a successful page ends the consecutive
gone-token chain. Other repair reasons and calls without gone-token context retain the change-gated policy.
A freeze never advances health revision;
a successful write/fsync or completed repair after a storage failure does, durably before publication.
The controller implements this policy without transport wiring; S15a owns the blocking end-to-end test
`the in-repo client honours the hint end to end`. The compact delta flag remains OFF by default until S15a
lands; S14's crash reclaim is also a prerequisite for default-on (RULING-79).

At compact-host startup the producer classifies direct transcript, settled, current and event spool children
of its own temporary base. Each new spool has an atomically published 0600 marker with scratch/live kind,
boot-session identity and process start identity. Only a scratch owner proven dead is reclaimed. Live,
unmarked, unreadable, foreign and linked roots survive; unknown roots are counted with age and size (null
when unreadable), and failed removals remain reported debt. Accepted engine content is ephemeral scratch,
not evidence of desktop SQL/replay commitment. Windows startup reclaim is a reported no-op because this
implementation cannot prove POSIX ownership and no-follow traversal there.

**Event leases (senpi#4272, S13).** Behind the same flag, a connection that sends `compact_events` in its
`set_client_info` capabilities (an internal opt-in, not advertised; the public selection comes later) receives a
session record larger than F = 262,144 bytes (newline included) as an envelope
`{"type": <the record's type>, "sessionId", "eventLease": {"kind": "event", "id", "admissionId", "sessionEpoch",
"sequence", "componentRef": "record", "length", "digest"}}`. `sequence` is the record's accepted sequence in
`sessionEpoch`; no recovery generation changes. Other connections still receive the complete record. The lease's
one component, `record`, is the record's exact JSON line without its newline, paged as its stored UTF-16LE bytes
(`length`, `leaf` digest `digest`) through this command with `lease` in place of `token`:

```json
{"type": "get_recovery_page", "sessionId": "rpc-1", "lease": {"kind": "event", "id": "event:socket-3:4"},
 "admissionId": "attach-9", "componentRef": "record", "requestId": "r-13"}
```

The answer's `data` carries `lease` in place of `token` and `generation`; ordinals, the active request, the
socket's eight outstanding requests, retries and cursors follow the rules above. A lease is scoped like a token: one
minted for another connection, session or admission is `unknown_token` with nothing else. A connection holds at
most 32 live event leases; past that it receives `{"type": "event_lease_refused", "sessionId", "reason":
"lease_limit"}` and is closed, and a record the host cannot stage is refused the same way with
`"storage_unavailable"`. Its end releases every lease it holds. Leases are released only by `release_recovery`.

**Live message identity (senpi#5331, RULING-120).** A session record never carries its recovery identity as a
property: legacy connections, and every connection with the flag off, receive exactly the bytes they always did.
The one exception is the copy a `compact_events` connection receives behind the flag, so it can join a live record to
the settled overlay it pages after a reconnect or a recovery cut without a second derivation of its own:

- `message_end` gains `messageId` and `terminalSequence`: the `messageId` and `terminalSequence` of the message's
  settled row, which a pending or failed terminal pages as the `settled` member `message-<terminalSequence>`
  (sixteen digits) and a joined message pages as the `messageId` of its `identity` member `join-<n>`.
- `entry_appended` carries the entry's ownership as a tri-state (senpi#5337, RULING-122):
  - `owningMessageId` present: the entry joined a message, and this is that join member's `messageId`. The owner is
    captured when the append is applied and kept for that entry, so transcript batches applied before its
    `entry_appended` cannot drop it.
  - `ownerUnknown: true`: the host cannot vouch for the entry's ownership. An owned entry the settled store never
    joined (the epoch's transcript component was unavailable, or the store refused the join) carries it. At most 1,024
    joins wait for their `entry_appended` at once; a join dropped at that bound is remembered by entry id. Both kinds
    share one memory (up to 4,096 ids per epoch), and once that memory itself overflows, every entry of the epoch with
    no join carries `ownerUnknown` until the next bootstrap, including entries no message owns (conservative by
    design: never a false "not owned"). Resolve a dropped join through recovery's `identity` member `join-<n>` for
    that entry id; an entry the store never joined has no such member.
  - both absent: the entry is not message-owned, never a lost or pending join. This absence is normative only because
    the host marks every entry it cannot vouch for with `ownerUnknown`.

  The lane's status counts dropped joins (`ownerJoinsEvicted`) and ids dropped from that memory
  (`ownerJoinsOverflowed`), and the host writes one stderr line at an epoch's first overflow. An `entry_appended`
  carries its tri-state even when the host refused its canonical record at the protocol depth limit: the record is
  still delivered, and it takes its entry's join like any other.
- `transcript_write_failed` gains `messageId`: the failed terminal row's `messageId`.

The host appends the fields after the record's own (`{"type": "message_end", ..., "sessionId": "rpc-1", "messageId":
"...", "terminalSequence": 12}`; a leased record carries them inside its `record` component). They come from the
settled store that writes those rows, not a parallel derivation. `messageId` is an opaque id with no message content,
the same live and after recovery for the message's lifetime, and never reused in the session; `terminalSequence` is
the record's accepted sequence in its `sessionEpoch`. A record with no settled row (an end the store refused, an entry
no message owns) carries none of them; an entry whose ownership the host cannot vouch for carries `ownerUnknown: true`
instead.

**Live call identity (senpi#5346, RULING-123).** The same compact copy of a live call record names the call it
belongs to, so a client can join it to that call's snapshot entry after a reconnect or a recovery cut. This covers
`message_update` records whose `assistantMessageEvent` is `toolcall_start`, `toolcall_delta` or `toolcall_end`, and
`tool_execution_start`, `tool_execution_update`, `tool_execution_end` and `tool_hook_status`:

- `runtimeItemKey`: the key of the outstanding call the host changed with this record, the same key the call's
  `calls` member and, once it settles, its terminal row and call projection carry. A `toolcall_*` update names the call
  that owns the streamed block. The key is opaque, fixed for the call's lifetime (live and after recovery), and never
  reused in the session, so it tells apart calls that share a `toolCallId` (providers reuse them across turns). It is
  unique on its own; no `turnId` is needed beside it.
- `callUnknown: true`: the host changed no call with this record, so it cannot vouch for one. Every `tool_hook_status`
  names a `toolCallId` (there are no session-level hook records), but a hook can run for a call the session never
  announced, such as a nested call inside another tool; that record, a record for a call that already ended, a record
  refused at the protocol depth limit, and a record arriving while the epoch's compact state is unavailable all carry
  `callUnknown: true`. So does an execution or hook record (`tool_execution_*`, `tool_hook_status`) whose
  `toolCallId` more than one call inside one assistant message took: those records name only the `toolCallId`, so the
  host cannot tell which of those calls a record is about, and it never picks one by order. The mark lasts while any
  call of that message and id is live. A `toolcall_*` update names its block by `contentIndex`, so it keeps the exact
  key of its own call even then.

A compact live call record carries exactly one of the two fields, `runtimeItemKey` or `callUnknown: true`, never both
and never neither; that holds for its delta-only form too, when a newer `toolcall_delta` supersedes a queued one.

The snapshot follows the same rule (senpi#5348). While more than one call of one assistant message holds the same
`toolCallId`, each of those calls' `calls` members carries `callUnknown: true` beside its `runtimeItemKey`, and so does
the `settled` toolResult row each of them retires into, both on the row and on the call projection it carries
(`call.callUnknown`). The row's key still names that call, and its announcement fields (`owningMessageId`,
`contentIndex`, `requestedName`, `input.announced`, `raw`) are exact. But the host attributed the per-id records that
move a call (its `phase`, `startSequence`, `startedAtMs`, `input.started`, `input.prepared`, `hook`, `progress`,
`result`, `outcome`, its nested calls, and the toolResult carrier joined to it) to those calls oldest-first, so it cannot
vouch that they belong to this call rather than the other. Never present those fields of a marked row as that call's
state. The mark lasts as long as the live-record mark: from the moment a second call takes the id until the last of
those calls leaves the table. Where the field sits: a `calls` member carries it as its last field, a `settled` row
directly after `runtimeItemKey` (before `entryId`), and the call projection directly before `nestedCalls`. Every other
row, and every row with the flag off, carries no `callUnknown`.

A snapshot member's own key (`calls/call-<sequence>-<n>`, `settled/message-<sequence>`) is opaque and derived from the
session's record sequence. It is stable for the session's lifetime but not across engine versions: a change that emits
more or fewer records before a call moves it (senpi#5682 moved the `calls` keys of the admission golden
`k-same-message-reused-id.json` down by two). Do not pin these values; join a call by its `runtimeItemKey`.

The host appends the field after the record's own, like the message ids above (`{"type": "tool_execution_end", ...,
"sessionId": "rpc-1", "runtimeItemKey": "..."}`); legacy connections and every connection with the flag off receive
the same bytes as before.

**Key source (senpi#5374, RULING-126/127).** The producer mints the key, and the session file keeps it (see
[session-format.md](session-format.md)), so the live record, the snapshot rows and the persisted entry name one key. A
toolCall block's call is keyed `blk:<messageId>:<contentIndex>` from the block's own address, which the host's calls
table derives the same way, so nothing extra travels on the wire. A call whose execution started before its block
streamed (a bridge-started call) is keyed `exe:<uuid>`, minted with that start; the block that later joins it keeps that
key, and the session file persists it on the block. The first key a call ever carries is its key for its lifetime: the
host never re-keys a call. The host mints its own `<sessionEpoch>:<sequence>.<k>` key only for a call with no backing
block (a nested call, reported with `parentToolCallId`). The three forms are distinct namespaces, but a key stays
opaque: compare keys only for equality. A transcript entry a recovering compact peer reads carries the persisted keys as
the session file holds them (`runtimeItemKey` on a toolCall part, `runtimeItemKey` or `callUnknown: true` on a
toolResult entry), reused after a reload and never re-minted. `get_messages`, `get_entries`, attach replays and every
legacy or flag-off record never carry them. A session written before senpi#5374 has no persisted keys, and nothing mints
one for its parts when it loads: no host state is rebuilt from a loaded part, so such a key would have no reader.

#### release_recovery

Behind the same flag, the consumer's receipt for an event lease (senpi#4272, S13). Send it only once the leased
content is committed on the consumer's side (for the desktop: after its command transaction's dispatch succeeded);
decoding a page, queueing or staging it is not a release point.

```json
{"type": "release_recovery", "sessionId": "rpc-1", "lease": {"kind": "event", "id": "event:socket-3:4"},
 "admissionId": "attach-9"}
```

The answer's `data` is `{lease: {kind: "event", id}, outcome, remaining}`: `released` when this admission's
reference was the last (`remaining: 0`, the content goes once reads in flight unwind), `held` while another
admission still references it, and `duplicate` for a receipt this admission already gave, which changes nothing, so
a consumer may retry a receipt after a rollback. A lease of another connection or session, or an unknown one, is
`recovery_repair_needed` with `reason: "unknown_token"`; a malformed request is `recovery_malformed_request`.
With the flag off it answers the typed refusal `{"success": false, "error": "feature_disabled", "errorCode": "feature_disabled", "errorData": {"feature": "compact_updates"}}` (plus `sessionId` when the request named one), as does the classic single-session handler, which has no compact transport; with `SENPI_RPC_REQUIRE_ATTACH=1`, an unattached caller of a session-addressed request gets the attachment gate's `session_not_attached` first.

#### cancel_attempt

Behind `SENPI_ENGINE_SOCKET_COMPACT_UPDATES` (off by default), cancels this connection's pending admission attempt
(senpi#4272, S15a). The `admissionId` is the client's own id for an `open_session` or `subscribe_sessions` that
carried it, or (S17) an `attach_session` with an `admissionId`; the attempt belongs to the socket that sent it, so
another connection's id is never found.

```json
{"type": "cancel_attempt", "admissionId": "open-9"}
```

The host first checks the id against this connection's admissions: an id that is neither a pending attempt nor an
admission this connection currently holds (never used, already cancelled, or completed and released) is refused with
`unknown_admission`. Otherwise the answer's `data` is `{outcome}`: `cancelled` for a pending attempt (its late result
is never applied) and `already_complete` for an admission this connection holds (cancel does not undo it). Only a
socket connection has admissions, so on any other transport the id is unknown. A malformed `admissionId` is refused
with `admission_malformed_request`. With the flag off it answers the typed refusal `{"success": false, "error": "feature_disabled", "errorCode": "feature_disabled", "errorData": {"feature": "compact_updates"}}` (plus `sessionId` when the request named one), as does the classic single-session handler, which has no compact transport; with `SENPI_RPC_REQUIRE_ATTACH=1`, an unattached caller of a session-addressed request gets the attachment gate's `session_not_attached` first.

#### reset_stream

Behind the same flag, restarts the compact stream of an admission this connection already holds (senpi#4272,
S15a-1), when the client has lost its place in it. It operates on existing admission authority, never as a fresh
open or attachment: `admissionId` must name a completed admission of this socket for `sessionId`.

```json
{"type": "reset_stream", "sessionId": "rpc-1", "admissionId": "attach-9"}
```

The host freezes a new recovery checkpoint for that admission and answers it as the stream's new baseline:
`{"type": "response", "command": "reset_stream", "success": true, "sessionId", "admissionId", "generation",
"data": {"recovery": {"token", "componentRef": "manifest"}}}`, ordered before any later compact frame of the
admission. Read the checkpoint with `get_recovery_page`. An `admissionId` this connection does not hold is refused with
`unknown_admission` before the command runs. A held admission that is not
complete, not for `sessionId` or no longer on the session's stream is refused with `recovery_unknown_token` and
`errorData: {kind: "repair_needed", reason: "unknown_token"}`; a checkpoint that cannot be frozen is refused with
`recovery_<kind>` and that failure as `errorData`. With the flag off it answers the typed refusal `{"success": false, "error": "feature_disabled", "errorCode": "feature_disabled", "errorData": {"feature": "compact_updates"}}` (plus `sessionId` when the request named one), as does the classic single-session handler, which has no compact transport; with `SENPI_RPC_REQUIRE_ATTACH=1`, an unattached caller of a session-addressed request gets the attachment gate's `session_not_attached` first.

**Admission IDs per socket (senpi#5274, RULING-113, RULING-117 and RULING-118).** A socket's admissions are capped by what is
live, never by how many IDs it has used. At most 16 attempts run at once (`admission_admission_busy` past that). Running
attempts plus routed admissions share 127 rows (128 rows within 16 MiB of 131,584-byte rows); a fresh attempt past
them is refused `admission_admission_limit` (`errorData.reason: "admission_limit"`). A completed admission that no
longer routes a stream stays in a least-recently-used row: an exact retry of a recent ID (C4.4) answers its stored
result, opens nothing and replaces nothing, and an evicted ID answers `admission_admission_retired` (a 4,096-entry ring;
an unmarked ID older than that is indistinguishable from a fresh one, while a retry marked `retry: true` answers
`admission_admission_unknown`; see Admission retries below). A completed `open_session` or `attach_session` of a
session this socket already routes REPLACES that route: the earlier admission receives no record after the new
admission's baseline, its attachment is released, and `reset_stream` or `cancel_attempt` naming it answers
`unknown_admission`. An ordinary route has no separate end record; a record already queued for the earlier ID is
delivered whole. A re-open that is still pending, refused, cancelled or failed leaves the earlier route as it was.
A detach (`close_session`, `release_attachment`, `detach_connection`) also ends the route: when the detaching request
names the admission, its reply is tagged with that admission first and the route retires right after it, so the
records sealed before the reply (a final `session_closed`) keep the tag too; the peer then receives no further records
for that admission, and the admission no longer counts toward the cap. A route otherwise ends with its session or its
socket. Routed rows are therefore bounded by the pending attempts plus the distinct live sessions the socket still
holds, one row each however often it re-opens them: the 128th distinct held session on one socket is refused
`admission_admission_limit`, re-opens of a routed session never run out, and a socket that attaches to and detaches
from any number of distinct live sessions in turn is never refused.
Lifecycle broadcasts (`agent_start`, `agent_settled`, `agent_idle`, `session_opened`, `session_closed`,
`session_parked`, `session_lifecycle`) are socket-wide and untagged, and they continue regardless of attach or detach;
they are not route records. They reach every socket, except under I4: a worker session's (or an `attachedOnly` seal's)
`session_closed` and `session_parked` reach attached connections only.

**Route retirement (senpi#5274, RULING-119).** The engine never retires a delivering route silently: every retire is
either the direct result of a client action whose reply the client sees, or announced to that client by a typed record
before the route stops delivering. Per path:

- A completed re-open of the session by the same socket (RULING-117): a client action; the new open's reply.
- A detach (`close_session`, `release_attachment`, `reclaim_session`, `detach_connection`; RULING-118): a client action;
  the detach's reply.
- An accepted `open_session` or `attach_session` that ends without completing (cancelled, refused or failed after it
  was accepted, for example when its durable answer row cannot be written): announced by its own final reply,
  `attempt_cancelled` or the `admission_<reason>` refusal, which then carries `admissionId` and `generation`. That reply
  is the last record tagged with the admission; records the open delivered before it (`session_opened`, and a rolled-back
  open's `session_closed` with `reason: "error"`) keep the tag, and the route retires right after it.
- A mirror admission's route: retired only by `unsubscribe_sessions` or the subscribe's own `cancel_attempt` (client
  actions), by a subscribe refused before activation, or with the socket. Before activation no mirror record is
  delivered: the records wait in the subscription's pending buffer until the answer row is durable and activation runs
  as the last step (`compact-admission-settlement.ts`). A socket's connection is unregistered before its subscriptions
  drop, so that path retires no delivering route. A mirror therefore needs no end record of its own.
- A session's close or park: announced by `session_closed` or `session_parked`, tagged with every route the session had
  on the socket; the session's streams end with it.
- A socket's end: nothing can be delivered on it any more; its streams end with it.

**Admission retries (senpi#5285, RULING-125).** `open_session`, `attach_session` and `subscribe_sessions` accept an
optional `retry: true`. A compact client sends it on every C4.4 retry, that is, whenever it sends an `admissionId` again
on the same socket; the first send of an ID never carries it. The marker is not part of the request's identity: a
marked retry with otherwise identical fields matches the original row. The host answers by what this socket's admission
index holds for the ID:

| Request | ID state on this socket | Answer |
| --- | --- | --- |
| `retry: true` | done row (completed, cancelled or failed) | that row's stored result; nothing runs again |
| `retry: true` | live pending attempt | the existing in-flight admission's answer; no second admission |
| `retry: true` | unknown: evicted into the ring, forgotten after the ring overflowed, or never seen | `admission_admission_unknown` (`errorData.reason: "admission_unknown"`); nothing runs |
| no `retry` | retired (evicted, in the ring) | `admission_admission_retired`, as before |
| no `retry` | live (pending or done row) | the existing duplicate handling: join the pending attempt or answer the stored result |

`admission_admission_unknown` means the outcome is unconfirmed: the original send may have run (an evicted ID did), so
the client treats the request as possibly applied and never re-sends it as new. This closes the residual of RULING-114:
before the marker, a retry older than the 4,096-entry ring was indistinguishable from a fresh open and ran again,
possibly duplicating its effect. An unmarked request for a forgotten ID still runs as a fresh admission, which is why
clients must mark retries; `status().retiredOverflow` still counts ring drops. A marked request whose fields differ from
the stored row answers `admission_admission_conflict`, as an unmarked one does. With
`SENPI_ENGINE_SOCKET_COMPACT_UPDATES` off, and on a legacy (non-compact) request, the field is ignored. The in-repo
`RpcClient` marks every `openSession` that re-sends an `admissionId` the same client instance already sent, also
after a disconnect and reconnect: the typical C4.4 retry follows a reconnect, and the new socket does not know the ID,
so an unmarked re-send would open again. The client remembers the 4,096 most recently sent IDs (least recently sent
dropped first), so its memory stays bounded; a client must not reuse an `admissionId` for a different request. A
re-send of an ID older than that 4,096-entry window goes out unmarked. On the same socket the late-retry residual is
bounded by both windows (the client's 4,096 sent IDs and the engine's per-socket 4,096-entry ring plus 127 live rows);
after a reconnect the new socket knows no IDs, so only the client window bounds it. `RpcClient`'s window is fixed; a
custom client that retries older admissions keeps a larger window of its own.

**Engine-initiated socket close (senpi#5322, RULING-124).** With `SENPI_ENGINE_SOCKET_COMPACT_UPDATES` on, the engine
never closes a socket that selected compact events without saying why. Before every close the engine itself decides,
it stops the socket's record queue and writes one last record:

```json
{"type": "socket_closing", "code": "event_queue_failed", "retryable": true, "detail": "overflow"}
```

`detail` is optional. The engine then waits for that record to drain for at most 1 second and closes the socket
regardless. On a host shutdown each socket drains its own queue and then receives its record, so a
peer that stopped reading delays only itself. These waits, and the half-close that flushes the record, end at the
shutdown's deadline: 2 seconds after the shutdown starts, inside the supervisor's 5-second stop window, and a socket
still open then is destroyed. The deadline counts from the start of the shutdown, so it includes closing the host's
sessions, which is not bounded on POSIX (senpi#5398) and can still push a stop past the window. When the transport is already broken (the write fails, or the drain is refused) the socket closes at once
and the record may never arrive, so a client must not depend on it: a close with no `socket_closing` is handled as
`retryable: true`. A legacy socket, and every socket with the flag off, is closed exactly as before, with no new record.

`retryable` is fixed per code. `true`: the cause belongs to this connection (its queue, its lease budget, compact storage
that may recover), so reconnect with backoff and recover through the recovery commands (`reset_stream`, a re-open).
`false`: a new connection with the same selection gets the same answer, so reconnect without the compact selection, or
stop.
`host_shutdown` and `host_handoff` describe the socket, not a session: a client holding several sessions, or none, learns
from them that the host itself went away (shutdown) or handed its endpoint to a newer generation (reconnect to it).

| `code` | `retryable` | Sent when | `detail` |
|---|---|---|---|
| `checkpoint_unavailable` | `true` | A required or mirrored stream's checkpoint cannot be frozen | The refusal reason, for example `unavailable` |
| `event_queue_failed` | `true` | The socket's event queue failed; follows its `overflow` record when it has one | `overflow`, `stall` or `transport_error` |
| `event_lease_refused` | `true` | An event cannot be leased; follows its `event_lease_refused` record | `lease_limit` or `storage_unavailable` |
| `compact_endpoint_unsupported` | `false` | A compact mirror of a session served only on the legacy wire; follows its `compact_refused` record | none |
| `host_shutdown` | `true` | The host is shutting down; follows its sessions' `session_closed` records (`reason: "host_shutdown"`), or `session_parked { reason: "host_shutdown" }` for a retained session on a socket host | none |
| `host_handoff` | `true` | The host drains for a newer generation; follows its sessions' handoff park records | none |

#### interactive_user

A client that advertises `interactive_user` in `set_client_info` declares that the connection belongs to a person's
client. The role is the connection's authority over pausing: only such a connection may Stop a session (`intent:
"stop"`) or release a Stop with its input (senpi#3811). It does not change an input's origin: every `prompt`, `steer`
and `follow_up` is a person's input by its entry point, whatever the role. The role belongs to the connection, not to a session:
on a shared host every connection attached to a session keeps its own role, and a stdio host's one client is a
single connection. Only the client's own `set_client_info`
declares it (at connection level or for a session); the host's launch capabilities and
`SENPI_RPC_CLIENT_CAPABILITIES` never do. It is bound at the connection's first declaration; a later `set_client_info`
that adds or drops it is refused with `connection_role_fixed`, so the heartbeat must repeat the same list. A client that dispatches input on its own (for example a queued follow-up it sends later)
should use a second connection without the role.

#### media_placeholders

A client that advertises `media_placeholders` in `set_client_info` tells the host it does not want
inline media bytes on the wire. For that connection the host replaces every image block inside a
tool result (`ToolResultMessage.content` and `tool_execution_end.result.content`, including the
entries carried by `get_entries`, `get_messages`, `get_tree`, `open_session` state and attach-time
snapshot replay) with an `image_ref` placeholder:

```json
{
  "type": "image_ref",
  "mimeType": "image/png",
  "byteLength": 553000,
  "ref": {"toolCallId": "call_abc123", "contentIndex": 1}
}
```

`byteLength` is the decoded size of the omitted payload. The original block is fetched on demand with
[`get_media`](#get_media) using the `ref`. User-authored images (`prompt`/`steer`/`follow_up`
`images`) are never replaced.

A multi-session host also keeps each tool-result image on disk, so a client can render it from a
path without a round trip. The bytes are written atomically BEFORE the placeholder is emitted, and the
placeholder gains one of two fields:

```json
{"type": "image_ref", "mimeType": "image/png", "byteLength": 553000,
 "ref": {"toolCallId": "call_abc123", "contentIndex": 1},
 "path": "/home/me/.senpi/agent/sessions/--proj--/media/<durableSessionId>/<sha256(toolCallId)>/1-<sha256(bytes)>.png"}
```

`unavailableReason` replaces `path` when the image was not kept: `image_too_large` (over 20 MiB),
`session_limit` (the durable session already holds 256 MiB of images; new images are refused and
stored ones are never evicted) or `storage_error` (the write failed, the format is not PNG, JPEG,
GIF or WebP, or the bytes are not the format the tool claimed). A session with no session file has neither field. Files are immutable and private, live next to the session files and never under the
project, outlive disconnects, idle shutdown and generation handover, and are deleted with the session
(from the interactive session selector). `get_media` keeps working for every placeholder.

A connection that does not advertise the capability receives byte-identical output to before. The
capability is advertised by the host in `get_protocol_info.capabilities` in both classic and
multi-session mode, but the transform itself is applied only by the multi-session host: classic
single-connection stdio mode never rewrites its output, so a stdio client always receives inline
media even if it names the capability. `get_media` is answered in both modes.

## Multi-session mode (D1 wire protocol)

Multi-session mode lets one `senpi --mode rpc` process serve several independent conversations concurrently over the same stdio JSONL stream. Classic single-session mode is unchanged except for two additive behaviors: `get_protocol_info` is answered, and a resolved `extension_ui_response` is acknowledged under its frame `id` (see [Extension UI Responses](#extension-ui-responses-stdin)).

### Starting multi-session mode

```bash
# Shared JSONL over stdio (legacy multi-session host)
senpi --mode rpc --multi-session [options]

# One multi-session host over a local socket; each accepted connection has its own JSONL feed
senpi --mode rpc --listen unix:///tmp/senpi-rpc.sock [options]
senpi --mode rpc --listen /tmp/senpi-rpc.sock [options]
```

`--listen unix://` selects the default per-agent socket path. Unix abstract socket names may be supplied as
`unix://@name` where supported by the host platform. Socket mode accepts concurrent connections while retaining one
process-global session registry.

### Authentication

Public POSIX endpoints advertise `socket_auth` and prove possession of a fresh per-launch key.
This applies to ensured hosts, direct supervisors, and bare `--listen` hosts. Windows pipes keep
their existing raw `.secret` handshake. Terminal control sockets and tool-child channels are unchanged.

The host publishes `<agentDir>/rpc/keys/<launch_id>` before answering any connection. The agent
directory and `rpc` must be user-owned, non-symlink directories without group/other write
permission (0755 is supported). Only `rpc/keys` must be 0700. Before publication, the host
tightens an existing user-owned, non-symlink `rpc/keys` directory to 0700; clients refuse
unsafe modes rather than changing them.
The record is exclusively created with `O_NOFOLLOW`, fsynced, and checked to be a user-owned
regular file with mode 0600. Publication failure closes the endpoint with `key_publication_failed`.
A group- or other-writable agent directory or `rpc` (for example one created under umask 002) is such a
failure: the host exits, and its message names the directory and the fix, `chmod go-w <dir>`.
A supervised generation also publishes one record for its generation-private route endpoint (its
`endpoint` names that `route` socket), which a successor authenticates against (senpi#7098).
Each launch generates a new UUID and a new 32-byte key in memory. Hosts delete only their own
record; `senpi host gc` also collects records whose process is dead or whose PID has been reused.

The JSON record is
`{version:1, launch_id, key, pid, process_start, endpoint, created_at}`:
`key` is 64 lowercase hexadecimal characters, `process_start` is the process start identity
or `null`, and `created_at` is an ISO-8601 UTC timestamp. Never copy the record into logs.

The client's key root defaults to its own agent directory. `SENPI_RPC_KEY_ROOT`,
`senpi host ... --rpc-key-root <dir>`, and the `keyRoot` option on `RpcClient` and socket probes
select the host's credential directory without changing the client's models, settings, skills,
MCP environment, or other profile data. For example, a client using profile B can authenticate
to an endpoint launched by profile A by selecting A as its key root while keeping B active.

The exchange uses strict LF-delimited JSON:

1. Preserve the caller's own first `get_protocol_info` frame, including `observe` and
   `origin_host_instance`, and add top-level `auth: {client_nonce}`. A caller starting with
   another command first sends an observing protocol probe. Both nonces are 32 fresh random
   bytes encoded as 64 lowercase hex characters.
2. The normal response's **`data.auth`** contains `{launch_id, server_nonce, server_proof}`.
   Read and validate the named record, including `version === 1`, matching `launch_id`,
   a 32-byte key, directory ownership/modes, and an `O_NOFOLLOW` file open.
3. Verify the server proof, then send `{id, type:"authenticate", client_proof}`. Wait for
   its successful correlated response before sending any other command. Proofs are lowercase
   hex HMAC-SHA256 digests, compared as 32 raw bytes in constant time:

   ```js
   import { createHmac, timingSafeEqual } from "node:crypto";

   const key = Buffer.from(record.key, "hex");
   const serverProof = createHmac("sha256", key)
     .update(["senpi-rpc-server", launchId, clientNonce, serverNonce].join("\n"), "utf8")
     .digest();
   // Validate that the received proof is exactly 64 lowercase hex characters first.
   if (!timingSafeEqual(serverProof, Buffer.from(receivedServerProof, "hex")))
     throw new Error("host_identity_unproven");
   const clientProof = createHmac("sha256", key)
     .update(["senpi-rpc-client", launchId, serverNonce, clientNonce].join("\n"), "utf8")
     .digest("hex");
   ```

For third-party scripts, the shipped client implements the record checks and complete exchange:

```js
import { RpcClient } from "@code-yeongyu/senpi";

const client = new RpcClient({ socketPath: endpoint, keyRoot: hostAgentDirectory });
await client.start();
try {
  console.log(await client.listSessions());
} finally {
  await client.stop();
}
```

The raw key never crosses the socket. A wrong server proof closes the client with
`host_identity_unproven`; an unsafe record closes it with `unsafe_key_record`. Neither falls
back. A host's `auth_failed` triggers one fresh connection and credential lookup, not an
unauthenticated retry.

This release serves clients that never prove the key, with one stderr deprecation line per
connection and no limit beyond the normal JSONL ones, whatever the first frame (a long prompt or
an image included) and whether or not the client first received a challenge it could not answer.
A challenge in flight is not cut short: its `authenticate` may arrive after 2 seconds.
`SENPI_RPC_REQUIRE_TOKEN=1` enforces now: the first frame must be a `get_protocol_info` carrying
`auth.client_nonce`, and any other first frame, a keyless `get_protocol_info` included, receives
`auth_required`; a wrong proof receives `auth_failed`; either way the connection closes before any
later frame executes. Under enforcement, pre-authentication input is limited to 8 KiB and 2 seconds.

The host never drops an unauthenticated connection silently. Each drop writes one stderr line,
`senpi rpc host: dropped an unauthenticated connection on <endpoint>: <reason>`, where the reason
is `auth_required`, `auth_failed`, `pre-auth budget exceeded`, `pre-auth deadline`,
`first frame over the line limit` or `key publication failed`. The line carries no frame
content, nonce or key material.

A host is supervised only when it holds the internal key its supervisor hands it on stdin; the
supervisor-watch environment (`SENPI_RPC_HOST_WATCH_*` and its companions) never switches public
authentication off, and a host removes those variables once read, so nothing it starts
inherits them.
Clients accept pre-change hosts whose protocol answer has no `data.auth`. A missing record
is the one grace exception: the client logs the key-root remedy and continues without sending
`authenticate`; an enforcing host then refuses subsequent commands. Enforcement defaults and
refusal of legacy hosts are separate follow-ups.

Keep endpoints under the protected agent directory for the sandbox boundary. Choosing a `/tmp`
path or Linux abstract name permits a process that can later bind that name to pose as a legacy
host during the compatibility period. Challenge-response still prevents disclosure of the key
to a listener that cannot prove it.

### Session runtime (`--session-runtime in-process|worker`)

`--session-runtime` selects where a multi-session host runs its sessions:

- `in-process` - every session runs IN the host process, sharing its event loop. No worker isolate is allocated and
  no session cap applies (capacity is memory, never a refusal). This is the DEFAULT for a `--listen` socket host,
  i.e. for the multi-session host clients attach to.
- `worker` - every session owns a worker isolate, bounded by the worker capacity below. This is the DEFAULT for a
  stdio host (`--multi-session` without `--listen`, and `--listen stdio://`) and for embedders, and stays available
  for socket hosts that pass the flag explicitly.

An explicit flag wins over both defaults; any other value is a startup error. The flag changes only WHERE sessions
run - the wire protocol, attachment semantics and lifecycle windows are identical on both runtimes. An in-process
session is not isolated from the host: a session that blocks the event loop blocks every other session, and there is
no per-session opening deadline like the worker runtime's 30-second budget.

What an in-process session costs is memory and host accounting, never an admission decision - but that cost is
linear, not flat. Measured on one socket host with the default builtins: about **one OS thread, two file descriptors
and 5-8 MB of RSS per open session**, with no plateau. At 1,000 concurrent sessions on one host the process went
from 20 to 1,023 threads, 14 to 2,014 descriptors and 151 MB to 4.7 GB resident, with zero errors and no refusal.
The thread is not the session runtime - the in-process runtime allocates none - it is the `config-reload` builtin,
which lazily spawns one filesystem-watch Worker per session
([senpi#1794](https://github.com/code-yeongyu/senpi/issues/1794)); the same driver with that builtin disabled
measured 0 additional threads per session. Size a daemon from those numbers: it never refuses an `open_session` for
occupancy, so the ceiling is the machine's memory and its per-process thread and descriptor limits, not a session
count the host enforces.

### Tool runtime (`--tool-runtime in-process|child`)

`--tool-runtime` selects where a session's heavy tool work runs. `SENPI_TOOL_RUNTIME` is the fallback when the flag is
absent, and `in-process` is the default. Any other value, from either source, is a startup error.

- `in-process` - every tool runs on the host's own event loop, as it always has.
- `child` - each session gets its own tool child (senpi#3566): a separate process the engine starts by re-entering
  itself, on the first tool call routed to it, never earlier. No command the child runs starts before the host has
  recorded the launch. Today only an extension tool with `placement: "child"` and a `childModule` (`{ path, export }`,
  a file inside that extension's directory) runs there; every other tool still runs on the host.

The child's state is visible two ways:

- a `session_tool_child` record `{ state: "spawned" | "exited" | "respawned", generation, pid }` on the session's
  stream whenever it changes (a dead child is started again, as a new `generation`, by the next job routed to it);
- `tool_child: { state: "none" | "live" | "exited", generation?, pid? }` on every `list_sessions` row (`none` under
  `in-process`, and for sessions on the worker runtime).

A multi-session host and a single-session `--mode rpc` process each advertise their choice as one
`tool_runtime:in-process` or `tool_runtime:child` entry in `get_protocol_info.capabilities`. Under `child` they also
advertise one `placement:<name>` entry for each part of the tool child that has landed (`placement:launch-barrier`:
every command a child-run tool starts passes the execution barrier; `placement:job-policy`: per-kind deadlines,
liveness and the cancel ladder; `placement:hostcall`: a child-run tool body reaches the session over the reverse
bridge - `tool`, `completion`, `reserved`, `list_tools`, `authorize` and drain-before-release `lock_file`/`unlock_file`,
with large arguments and replies carried by acknowledged references). Both runtimes also advertise `offload_api`: an extension's
`ctx.offload` / `pi.registerChildModule` are available, running on the tool child under `child`
(`placement:offload`) and in the host process under `in-process`. A job worker cannot start worker threads of its
own (`tool_child_nested_worker_refused`), so no launch escapes the barrier that way.

### Session presence (headless engine)

A headless host built with a presence binding (no CLI flag selects one yet; every other host is unchanged) adds
`presence: { placement, state: "online" | "offline", paused, waitingOn: [{ machine, role: "owner" | "hand" }], held }`
to each `list_sessions` row and to the `open_session` answer. `placement` is the machine that owns the session and
`state` is its reachability. While the owner is offline every session pauses before its next provider request; while
a hand a session's tool calls run on is offline, that session's tool calls pause and other sessions keep running.
`held` counts the steps parked until the machines reconnect. Each pause and its resume are durable records, so a
reconnect resumes the session exactly once, also after a restart.

### Hand selection (headless engine)

A headless host built with a hand directory (no CLI flag selects one yet; every other host is unchanged) advertises
the capability `hand_selection` and answers `list_hands` and `select_hand`. A host without a directory refuses both
with `hand_selection_unsupported`.

#### list_hands

Lists the hands the engine can run a session's tools on. With `sessionId`, it also answers that session's recorded hand.

```json
{"id": "h1", "type": "list_hands", "sessionId": "rpc-1"}
```

Response:
```json
{"id": "h1", "type": "response", "command": "list_hands", "success": true, "data": {"hands": [{"device": "dev-a", "label": "Studio", "platform": "darwin", "reachable": true}], "selected": null}}
```

`hands` is every hand in the directory. `reachable: false` means the hand is listed but no carrier is up: it can be
shown, not chosen. `selected` is present only when the request named a session: that session's recorded hand, or
`null` when its tools run in this process.

Errors: `hand_selection_unsupported` (no hand directory), `unknown_session` (`sessionId` names no open session).

Who may call it: any connection. It changes nothing and is an observing read (method class `observe`), so like
`list_sessions` and `get_state` it is exempt from the attachment gate: a connection that is not attached to a session
may still read which hand it runs on.

#### select_hand

Records which hand runs a session's tools. `device` names a hand from `list_hands`; `null` gives the session back its
own ToolHost, so its tools run in this process again.

```json
{"id": "h2", "type": "select_hand", "sessionId": "rpc-1", "device": "dev-a"}
```

Response:
```json
{"id": "h2", "type": "response", "command": "select_hand", "success": true, "data": {"sessionId": "rpc-1", "selected": "dev-a"}}
```

The choice is written to the session file (a `custom` entry `hand_selection`) before it takes effect. The session's
next tool batch then runs on that hand through a remote ToolHost. Choosing the hand the session is already on changes
nothing. When the session opens again, the recorded hand is applied again. If it cannot be linked then, the session's
tool calls end as "The hand is unreachable" error results: a chosen hand never falls back to running the calls in this
process.

Errors. Each of these carries `errorData.device`, and nothing is recorded:

- `hand_not_listed`: the device is not in the hand directory.
- `hand_unreachable`: the hand is listed but no carrier is up, or its link cannot be made.
- `session_busy`: a turn is running. A running turn keeps the ToolHost it started with, so choose between turns.

`hand_selection_unsupported` (no hand directory), `unknown_session`, and `session_closing` (the session is already
ending, so a choice could not be kept) carry no `errorData`.

Who may call it: only a connection attached to the session. It moves where the session's tools run, which changes what
the agent can reach (method class `device_admin`), so the attachment gate applies to it: under enforcement
(`SENPI_RPC_REQUIRE_ATTACH=1`) an unattached connection is refused with `session_not_attached`. Until enforcement is
the default, the host logs such a call and serves it, as for every gated command.

### Host identity (`get_protocol_info`)

Supervised socket hosts additionally report `lifecycle: "ready" | "stopping"`.
The supervisor closes admission synchronously when shutdown or a drain begins,
including owner-expiry shutdown. It keeps answering protocol probes while waiting
for its child to exit, even if the child no longer responds. `senpi host status`
and `status --all` expose the same `lifecycle` field (`null` for an older or
unreachable host). Session counts during stopping are unobserved and represented
by the existing empty listing, not a claim that the child has already exited.
Shutdown signals the child immediately, then waits for its observed exit and any
pending startup publication before removing the generation's ownership state.

A ready probe does not reserve an open: a later `open_session` can fail with
`errorCode: "host_stopping"` and `errorData.instanceId`, including on a connection
that previously read ready. An open still pending when stopping begins receives
the same refusal rather than a late successful attachment. Existing admitted
sessions may finish a drain.

`ensureHost()` never adopts a stopping generation. Under the endpoint lock it
waits for that registered supervisor and its child to exit, without signalling
them, within the existing stop budget. `stoppingTimeoutMs` may shorten that wait;
expiry or an unprovable generation returns `HostEnsureRefusedError` with reason
`host_stopping`. A fresh ensure then performs ordinary discovery/startup.
`senpi host session open` retries a typed stopping refusal with its original
launch specification and a shared stop deadline. Socket-only `RpcClient` reports
the typed error to its caller; it cannot launch a successor without launch options.

Every `get_protocol_info` answer - classic and multi-session alike - carries the identity of the host that
answered it, so a client sharing one machine-wide host can tell hosts, builds and launches apart without
parsing a version string:

```json
{
  "protocolVersion": 1,
  "serverVersion": "2026.9.17",
  "capabilities": ["multi_session", "..."],
  "mode": "multi",
  "instanceId": "b46e6734-881f-493a-9bf5-705f9e15327a",
  "generation": 0,
  "engineVersion": "2026.9.17+1789656604.7b59713",
  "engineOrdinal": [2026, 9, 17, 0, 1789656604],
  "launch_profile": {
    "profile_id": "ca7a4943…",
    "core": { "extensions": [], "multi_session": true, "session_runtime": "in-process" }
  },
  "agentDir": "/home/me/.senpi/agent",
  "method_classes": {
    "version": 1,
    "digest": "71d68465…",
    "classes": { "get_state": "observe", "prompt": "dynamic", "...": "..." },
    "dynamic_versions": { "prompt": 1, "...": 1 }
  }
}
```

- `instanceId` - UUID minted when the host process booted. It is the only reliable "is this still the same
  host?" signal: it changes whenever the process does, including after a replacement.
- `generation` - which generation of its daemon directory this host is, handed to it at spawn time
  (`SENPI_RPC_HOST_GENERATION`). A host nobody ensured reports `0`.
- `engineVersion` - the build string: the engine's senpi CalVer version plus `+<buildEpoch>.<sha7>` when the binary
  was compiled with build metadata. A distribution compiled beside its own package.json (whose version is then
  `serverVersion`) defines `SENPI_ENGINE_VERSION` with the embedded senpi version, so this field and the ordinal
  stay senpi CalVer. Informational, like `serverVersion`.
- `engineOrdinal` - `[year, month, day, postRelease, buildEpoch]`, the ONLY ordering a client may use.
  `[y, m, d, n]` compares lexicographically, where `n` is the CalVer post-release increment (`2026.9.16-3`
  ships AFTER `2026.9.16`, the opposite of the semver reading of those strings). The build epoch breaks a tie
  only when BOTH sides carry one; otherwise the two builds are EQUAL, so a build whose age cannot be established
  never outranks one that can. Binaries built without git metadata report an epoch of `0`, which is exactly how a
  client reads "this build has no age": a non-zero epoch is comparable, `0` is not. Only two senpi CalVer
  ordinals (first part a year, 2000 or later) are ordered (senpi#7040): compiled omo builds through 5.1.78
  advertised their omo version (`[5, 1, 78, 0, 0]`), and a pair with such an ordinal is uncomparable.
- `launch_profile` - what the host was launched with: `core.session_runtime`, `core.multi_session` and
  `core.extensions` (absolute roots, deduplicated and sorted). `profile_id` is the sha256 of the canonical JSON
  of `core` with its keys in that sorted order (`extensions`, `multi_session`, `session_runtime`), so any client
  can recompute it and compare two hosts without comparing paths.
- `agentDir` - the absolute agent directory the host reads and writes. A generation handoff is refused
  `foreign_agent_dir` when it differs from the caller's own agent dir (see "Generation handoff"). Hosts
  released before the field omit it.
- `method_classes` - the inbound method-class table this engine runs: `version` is the class-meaning version
  and `digest` the sha256 (hex) of the table's sorted `type=class\n` lines (`type=dynamic@<n>` for a
  record-dependent entry). A client that classifies records with its own copy of the table uses that copy only
  while its digest equals this one, and otherwise treats every record as unclassified. `classes` is the whole
  table as data: each inbound type's class, or `dynamic` when the class depends on the record's fields, with that
  rule's version in `dynamic_versions` (the rules themselves are never shipped; ask `classify_record`, see
  "Delegated connections"). Hosts released before the field omit it; hosts released before `classes` send only
  `version` and `digest`.
- `memory_pressure` - multi-session hosts only: `true` while this host's memory sampler reads its memory footprint
  above `SENPI_RPC_HOST_RSS_WARN_MB`, else `false`. Not identity and never an admission signal; `senpi host status`
  reports it per endpoint. Classic hosts and hosts released before the field omit it.
- `path_identity_resolver` - multi-session hosts only: `{ state: "not_started" | "ready" | "unavailable", detail }`, the permission system's path identity worker. `not_started` means no worker has published its first mount snapshot yet (the first path request spawns it); `ready` means one has; `unavailable` names why it could not start; path rules for `read`/`edit`/`list`/`grep` then match by spelling only (a JS cell's own canonical path still decides exactly).

Compatibility is decided from `protocolVersion` + `capabilities`, and "is my build newer?" from `engineOrdinal`.
A `serverVersion` string comparison is never a compatibility test: two hosts with different version strings can
speak the same protocol, and a host whose ordinal is uncomparable is attached to, never replaced.

### Caller-owned hosts (`ensureHost`)

`ensureHost({ socket, agentDir, owner: "caller" })` opts an endpoint into the lifetime of
the process making that call. The public `EnsureHostOptions` export carries this option.
Omit `owner` for machine-wide hosts and desktop thread hosts; their existing idle policy
is unchanged. An owner that is alive also leaves the normal idle policy unchanged.

Fresh launches inherit a separate lifetime pipe on POSIX and Windows. The caller retains
its write end without keeping its own event loop alive; supervisor EOF proves owner death,
including SIGKILL and PID reuse. Releasing `EnsuredHost.release()` releases only the attach
hold, not ownership. The supervisor waits for two seconds of continuous quiescence after
confirmed death: no attached or unclassified public peers, no active runs, and a healthy
activity observer. Classification follows the normal idle policy: observe-only reads
(`senpi host status`, including repeated polls) and `warm` never reset the grace.
Attached-peer activity, run start, and observer loss reset it even between ticks.
A peer with no complete first request is unclassified and blocks exit, just as it does
under the normal idle policy. If it disconnects before classification, its unknown
admission breaks continuous quiescence and resets owner grace on disconnect; it is
not treated as a proven observing read or an attached client. This deferred reset
lets dropped connects restart the grace without letting status connections restart it.
After death is observed, the
existing one-second maximum lifecycle tick adds at most two ticks to window accounting,
then normal child shutdown applies (five-second graceful
stop before the existing escalation policy). A stalled child retains that policy's longer
bounded wait. No peer is drained and no active turn is interrupted by owner death.

Reusing a running supervisor cannot inherit another fd. A generation successor launched
by a process other than the owner also cannot inherit the owner's fd. These paths, and
launches where opening the inherited pipe fails, compare the recorded PID and OS process
start identity through the existing process reader. The supervisor also uses this check
when its current parent differs from the recorded owner, even if the inherited pipe
remains open without reporting EOF. Parent change alone never authorizes shutdown.
The reader uses `ps lstart` on POSIX and CIM creation
FILETIME on Windows. Both capture and probe pin `TZ=UTC` and `LC_ALL=C`; POSIX identities
carry an explicit UTC suffix. Parsed milliseconds are compared with the existing process-start
tolerance, never by raw timestamp spelling. Identity probes back off from one second to a
five-second maximum interval, with a one-second query budget. This adds at most that polling
interval before owner death can be observed; failed or unreadable observations never authorize shutdown.
Windows handoff remains unsupported, as before. A successor launched by the owner inherits
a fresh pipe. Ownership survives handoff independently of the attach hold.

Pipe-binding equality uses the exact parsed start instant; the liveness tolerance cannot
merge two different process incarnations into one pipe owner.

Each new generation records `owner.json` as `{ owner: { pid, startTime } }`, or
`{ owner: null }` when unowned. Unowned generations open no owner filesystem watcher.
A failed or exhausted watcher degrades to record polling without aborting startup; polling
also discovers a first owner claimed on a previously unowned generation.
An ensure may update only this ownership record under the
endpoint lock while holding an attachment. The same owner can ensure again; a new caller
may replace only a confirmed-dead owner (or claim an unowned host). A different live or
unknown owner is refused. An old host without an ownership record refuses an ownership
claim rather than pretending it can honor one. The record is removed with the generation,
before the registration pointer. Other daemon files retain their existing writer rules.

### Attach, start or refuse (`decideHostAction`)

A client that finds a host on the shared socket decides what to do with it through one exported function,
`decideHostAction(client, host, policy)`, so every client surface answers the question the same way. `host` is
the `get_protocol_info` answer (or `undefined` when nothing answered), and `policy` is `"never"` (attach only),
`"fallback"` (prefer no host over a mismatched one) or `"upgrade"` (a generation handoff is allowed). The result
is `{ action, reason, upgradeable, warning? }`.

A host is COMPATIBLE when it answers `protocolVersion: 1` and advertises every required capability -
`multi_session`, `extension_events`, `session_context`, `session_kind`. That is the whole test; the version
string takes no part in it.

| Situation | Action | Reason |
| --- | --- | --- |
| nothing answered on the socket | `start` | `no_host`, or `restart_own_host` when the pidfile is this process's |
| the host answers another protocol version | `refuse` | `protocol` |
| a required capability is missing | `refuse` (`fallback` under policy `fallback`) | `capability` |
| policy `fallback` and the host runs a different engine build | `fallback` | `engine_mismatch` |
| compatible, on win32 | `reuse`, `upgradeable: false` | `win32_attach_only` |
| compatible, host does not advertise `generation_handoff` | `reuse`, `upgradeable: false` | `handoff_unsupported` |
| compatible, policy `upgrade`, this build's ordinal is STRICTLY greater and its extensions cover the host's | `handoff` | `newer_engine` (`profile` when both are the same release and only the extensions grew) |
| compatible, anything else | `reuse` | `compatible` |

A `reuse` can carry a warning the caller should surface: `profile_narrower_attached` (this client would have
upgraded, but its extension set does NOT cover what the running host loaded, so upgrading would drop those
extensions) or `profile_mismatch_attached` (the launch profiles differ, or one of them is unknown - a client
without a launch spec can prove nothing about extensions and therefore never initiates a handoff).

Four invariants govern every client of a multi-session host, and every client is expected to keep all four. The first two
are what this decision encodes; the other two are what a client must not undo elsewhere:

- **I1 - never terminate, signal or replace a host this process did not start.** A missing capability or a
  foreign protocol version ends in `refuse`, never in a second host bound over an endpoint somebody else owns.
  `ensureHost` records a `writer: { pid, startTime }` stamp in its pidfile and stops the host it names only when
  that stamp is this process (the start time is what keeps a recycled pid from inheriting the right). A pidfile
  written by anyone else fails the ensure with `HostEnsureRefusedError { reason: "foreign_writer" }` and the host
  keeps running. That refusal is about signalling, so it holds only while something still accepts connections at
  the public path: a registration that names a live process whose entry is GONE (it was replaced by another socket
  and the replacement later exited) or whose entry nobody listens behind (a dead listener left it, a successor's
  rename never landed) describes a generation nobody can reach, and binding a fresh generation to the free path
  touches nothing of it. The ensure then starts one beside it, numbered after the stranded generation, which
  keeps its registration until it exits; refusing there locked every client out until that process happened to
  end (#1936). A named pipe has no entry to lose, so win32 keeps refusing.
  Neither replacement happens to a generation that is alive but stalled: when its own
  `generations/<instanceId>/host-stalled.json` records a loop stall younger than `SENPI_RPC_STALL_REFUSAL_MS`
  (default 120000), or its `host-alive.json` heartbeat stopped more than the loop-lag error threshold ago yet inside
  that window, while its process is alive, the ensure fails with `HostEnsureRefusedError { reason: "host_stalled" }`
  and sends no signal, starts no generation beside it and leaves its registration untouched - a stalled host is still
  serving its sessions.
  When no registration names the endpoint at all, yet something still accepts connections at the public path and did
  not answer `get_protocol_info`, the ensure fails with `HostEnsureRefusedError { reason: "endpoint_occupied" }` (exit 3)
  and leaves that process and its entry alone: a start there could only lose the bind and exit without a reason. An
  entry nobody listens behind is still free and is replaced by the start.
- **I2 - compatibility is protocol version + capabilities, never semver equality.** An ordinal that cannot be
  compared (a build without git metadata, a host that reports none) is EQUAL, and since a handoff requires
  STRICTLY greater, such a pair attaches instead of upgrading.
- **I3 - only the generation that owns the daemon state writes it; every other client reads.** A running host's
  pidfile, settings, reservations and socket belong to that generation. A client that cannot use what it finds
  fails CLOSED - it reports the refusal, or starts its own private host on its own endpoint - and never edits
  another generation's state files, unlinks its socket, or removes its pidfile to "clean up". A handoff is the one
  exception and it still writes only its OWN generation directory before repointing the pointer (see
  [Daemon state directory](#daemon-state-directory-layout-2)); the drained predecessor keeps its registration until
  it exits, because it is still serving. The one sanctioned cross-writer is the STOP INTENT: a process about to
  signal a generation (an ensure, `host stop`, a handoff abandoning its successor, the generation's own supervisor)
  first writes `generations/<instanceId>/stop-intent.json` `{ sender, targetPid, reason, signal, at }` into THAT
  generation's directory, because the target cannot know who is about to stop it; nothing ever reads or removes
  another generation's intent, and a drain writes none. The DRAIN REQUEST is the second sanctioned cross-writer:
  `host stop --drain` writes `generations/<instanceId>/drain-request.json` into the generation it asks (see
  [Asking a named generation to drain](#asking-a-named-generation-to-drain)). Caller-lifetime registration is the
  other explicit cross-writer: only `owner.json`, under the endpoint lock and attach hold described above.
- **I4 - machine-driven work is invisible by default.** A session opened with `kind: "worker"` is omitted from
  `list_sessions` unless the caller passes `include_workers: true`, its `context` is published on that listing only,
  and its `session_closed`/`session_parked` records reach only the connections attached to it. A client that never
  asked for worker sessions sees a daemon serving hundreds of them exactly as it saw an empty one, so a task runner
  fanning out children cannot flood a desktop's session list.

### Generation handoff (`handoffHost`, `probeHost`, `stopHost`)

An engine upgrade must not end the work the running daemon is doing: one machine-wide host holds every
client's sessions. A GENERATION HANDOFF replaces the process while its sessions keep running.

1. The successor is spawned with `--socket <public> --bind <public>.next-<generation>` and binds the BIND
   path. It never binds the live public path, and the bind path is refused before the bind when it would
   exceed the platform's 103-byte socket-path limit.
2. Once its host answers, the successor renames its own entry over the public path - but only while that
   path still refers to the exact socket the handoff was decided against (`--replace <dev>:<ino>`). A path
   taken over by anything else aborts the handoff: nothing is renamed, nothing is unlinked, and the
   running host keeps serving.
3. `handoffHost` then registers the successor (its own `generations/<instanceId>/host.pid`, the pointer
   moved onto it, and `settings.json { socket, generation }`) and sends
   the predecessor SIGUSR1 = DRAIN: stop accepting, announce `host_superseded` to every connection,
   park attached and unattached sessions as their turns and requests settle, then exit independently of
   connection occupancy. Clients see `session_closed { reason: "handoff_parked", sessionPath }` before
   their connection closes and reopen with `open_session { sessionPath }` on the successor. Losing
   ownership of the public socket triggers the same sequence even if SIGUSR1 never arrives.
   When both generations support routing, an `open_session { sessionPath }` on the successor attaches to
   the predecessor's existing writer while its turn runs. Use the returned `sessionId` on that connection:
   session commands and events follow the writer. After the park the same handle addresses the successor's
   local session; the routed client does not receive the predecessor's terminal record. `list_sessions`
   reports the writer's `generation` and `hostInstanceId` on the session row; a predecessor that does not answer
   that listing within the socket handshake budget (it exited mid-request, or it stalled) contributes no routed rows,
   and the listing still answers with the successor's own. A command sent on a routed handle while the session moves
   onto the successor waits at most the close grace window, then answers the retryable `generation_switch_pending`;
   if the move cannot finish (the successor began draining, the session file is gone) it answers that reason instead.
   Every other call the successor makes to its predecessor is bounded the same way: an answer later than the host's
   stall threshold (5 s) is followed by a liveness probe on that connection, and a predecessor that answers neither is
   cut, so the routed command or `open_session` answers `predecessor_request_timeout`. A long command on a live
   predecessor keeps waiting. A command already written to the predecessor is never replayed on the successor: when
   its connection is lost, even one cut by another request's deadline, it answers
   `predecessor_delivery_outcome_unknown`. A narrowing `set_client_info` or `declare_delegation` that a predecessor does not
   install is still acknowledged: that copy is cut and its session moves to the successor.
   An older predecessor without a route endpoint keeps its claim and the reopen returns the existing retryable
   `session_path_in_use`.
   While a predecessor still runs, new connections negotiate ordinary JSONL, not compact recovery:
   a compact checkpoint and its tokens belong to the physical writer's acceptance lane. The successor
   advertises compact recovery again once its predecessor scan finds no live predecessor.
   Each drain pass holds the automatic turns (goal continuation, monitor and codemode wakes) of every
   session, attached or not, exactly as an unattended reopen does: they wait as notices, its running turn is
   its last on this generation, and it parks once that turn settles. A person's input or `resume_session`
   releases the hold after the reopen. An attached client still steers or cancels the running turn and
   reopens the session on the successor after the park, so a session that keeps working never pins a
   superseded generation (senpi#7098).
   While the successor is still taking over (parks it has not reopened yet, or a predecessor that still runs),
   its `list_sessions` answer carries `handover: { pending, predecessor_draining }` beside `sessions`: the
   listing is not yet the endpoint's whole set, so a reader must not treat a missing session as gone. The field
   is absent once the takeover is done (senpi#7020).

Three guards decide whether a handoff is attempted at all, and all of them fail closed:

- The running host must advertise `generation_handoff`. SIGUSR1 TERMINATES a process that installed no
  handler for it, so a host from before the drain existed is never signalled - `handoffHost` answers
  `{ action: "refuse", reason: "handoff_unsupported" }` and `decideHostAction` reports `upgradeable: false`.
- The registration must prove which process serves the socket (pid + start time, and the record's `socket`
  must be this endpoint) before that process is signalled. Without such a registration a handoff never
  signals a stranger (I1): it refuses while that host holds a session, and replaces an idle one without
  a signal unless a flat pre-layout-2 record proves it (see "Daemon state directory (layout 2)").
- The running host must belong to the caller's agent dir. A client reads registrations under its OWN agent
  dir, so pointed at another agent dir's socket it would see no record there and read a live, registered host
  as an unregistered idle one. `handoffHost` therefore compares the host's advertised `agentDir` with its own
  (both canonicalized through `realpath`) and refuses `{ action: "refuse", reason: "foreign_agent_dir",
  upgradeable: false }` when they differ; `detail` names both directories. A host from before the field is placed
  by the layout: when the socket is `<dir>/rpc/rpc.sock` and a layout-2 registration under `<dir>` proves a live
  owner, the host belongs to `<dir>`. With neither, the handoff proceeds as before. Nothing is signalled.
- The successor must not run an OLDER engine than the running host (senpi#7018). `handoffHost` compares the
  successor's engine (this process's build, or the requester's `target_engine` in an idle handover) with the
  host's advertised `engineOrdinal` by `compareEngineOrdinal` (`[y, m, d, n]`, then the build epoch when both
  sides carry one; equal builds and builds uncomparable only for a missing epoch are not older; version strings
  are never compared) and refuses `{ action: "refuse", reason: "older_engine", upgradeable: false }` before
  spawning anything when the successor is strictly older, or when either ordinal is not senpi CalVer and the
  successor therefore cannot be proven not older (senpi#7040); `detail` names both engines. An `ensure` with the
  upgrade policy keeps such a host and writes one `engine order uncomparable` line to stderr. `allowDowngrade` (`host handoff --allow-downgrade`)
  is the caller's explicit consent and skips the check. A host that advertises no ordinal is not judged.
- Transition window: a host from before the `agentDir` field, serving a socket that is not another agent
  dir's default `<dir>/rpc/rpc.sock` (or whose layout-2 record there proves no live owner), cannot be
  placed and stays replaceable through the idle path above. Every host built with the field avoids it.

On win32 a named pipe cannot be renamed: `handoffHost` refuses with `upgrade_unsupported` and
`decideHostAction` never yields `handoff` there. Upgrades apply after `stopHost({ drain: true })` - which
reaches a win32 generation through its drain request, not a signal - or an idle exit.

`ensureHost` performs a handoff only when asked: `upgrade: "if-engine-differs"` (default `"never"`) makes it
run `decideHostAction` under policy `upgrade` with the launch profile its own `hostArgs` describe. A refused
handoff ATTACHES to the running host - an upgrade that cannot happen never becomes a stop.

`ensureHost` also takes `hostArgs` (CLI arguments forwarded through the supervisor to the host process) and
`env` (a `null` value removes an inherited variable) as public options.

A generation also drains WITHOUT being asked. The SIGUSR1 above can fail to arrive - an owner whose
registration cannot be proven is never signalled, a client that binds its own entry over the public path
sends nothing at all, and a wedged process can miss the signal it was sent - and the superseded generation
then holds its retained sessions and their path claims for as long as it lives, while no client can reach it
by path. So every generation checks, once a second, whether the public path still holds the entry it bound;
the moment it does not, it applies the same drain to itself: park each retained session with no attachment,
release its claims, and exit when it holds no attached session. Nothing else changes - a session mid-turn
still finishes, and a client still attached is still served.

That check separates a name that was TAKEN OVER from a name that is GONE, because the evidence differs in
strength. A different entry at the path proves supersession on sight and drains immediately. An absent entry
proves only that nobody is serving the name, so it has to be seen on several consecutive checks before it
counts, and a check that cannot answer resets the count rather than adding to it. Either way the outcome is
the same drain: an unlinked socket name can never accept a connection again, so the generation behind it is
unreachable no matter why the name went away.

An endpoint with no file identity - a win32 named pipe has no inode to compare - is checked on two POSITIVE
observations instead: the daemon pointer names another instance, and the public endpoint answers
`get_protocol_info` (an `observe` read, which never counts as activity) as that same instance. They must agree
on three consecutive checks; a missing pointer, an unanswered probe, an answer as this generation or as a third
instance each reset the count. Such an endpoint is never judged absent, and nothing is removed or reclaimed on
any observation: a confirmed loss only starts the same drain.

#### Asking a named generation to drain

`stopHost({ socket, agentDir, drain: true, instanceId?, waitMs? })` (CLI: `host stop --drain [--instance <id>]
[--wait-ms <n>]`) asks ONE generation to drain: the one the pointer names, or the one `instanceId` names - how a
client reaches a superseded generation that still holds its sessions' path claims. The target must be proven
first, exactly as for any signal: its `generations/<instanceId>/host.pid` names a live process by pid and start
time, about this endpoint; an unproven or unknown generation is refused `unknown_owner` and sent nothing.

The request needs no signal and is the same on every platform:

1. A supervisor reads drain requests once it is serving and says so in `generations/<instanceId>/drain-watch.json`
   `{ pid, at }`. The asker uses the request only when that marker names the very pid it just proved.
2. The asker writes `generations/<instanceId>/drain-request.json` `{ sender, reason, at, nonce }` by rename.
3. The supervisor polls that file once a second; each new `nonce` is one drain request. It runs the drain
   described under [Generation handoff](#generation-handoff-handoffhost-probehost-stophost): stop admitting, park each session as it
   settles, release its claims, exit once nothing is attached. It relays the drain to its host child through
   `generations/<instanceId>/host-drain-request.json`, which the child polls (on POSIX SIGUSR1 still follows as
   an immediate wake).

A generation without the marker - one from before the request existed - is drained by SIGUSR1 as before, and only
on POSIX, when the endpoint advertises `generation_handoff` AND answers as the named instance; otherwise the
answer is `drain_unsupported`. The answer is `{ action: "drained", pid, instanceId }`; with `waitMs` it also
carries `exited`, `true` once the generation's process is gone (or its pid names another process) within the
bound, `false` otherwise - an identity that cannot be read is not an exit. A client that did not wait learns the
same from `host status --json`: the drained generation leaves `generations` when it exits.

`stopHost({ socket, agentDir, drain?, force? })` ends a generation: `drain: true` is always permitted (it
ends no work, it only stops the host from taking new work), while a hard stop requires a host that reports
no open sessions, or `force: true`. A hard stop also drops that generation's registration (the pointer and
its `generations/<instanceId>/` directory); a draining host keeps its registration until it exits, because
it is still serving. `probeHost({ socket })` returns the running host's `get_protocol_info`
answer, or `undefined` when nothing is serving the endpoint.

A host that reports memory pressure (`SENPI_RPC_HOST_RSS_WARN_MB`, 4096 by default) while holding NO session
logs one line naming its RSS, and drains when it is also superseded: memory a daemon cannot attribute to a
session is memory nothing will return, and a generation nobody can reach is pure cost.

#### Runtime identity and the conditional idle handover

A version string cannot say which runtime a host loaded: a development checkout and a packaged install can
share one version, and a reinstall replaces a bundle at the same path. Every host therefore reports
`runtimeBuildId: "sha256:<64 hex>"` in `get_protocol_info`, computed ONCE at startup from the runtime it is
about to serve with: the runtime flavour (`compiled`, `packaged`, `dev`), platform and architecture, the engine
build text, the digests of the runtime files (`dist/bundle`, `dist`, `src`, or the compiled executable) sorted
by their relative path, one digest per launch-profile extension, and the profile's `multi_session` and
`session_runtime`. Absolute paths never enter it, so one build installed in two places has one id; dot-entries,
nested `node_modules`, `.d.ts`/`.map` files and the build/snapshot manifests are left out. A bundle replaced
after the host started leaves the host's id unchanged, while a client started from the new bundle computes a
different one. A host whose runtime cannot be read reports no id (unverified) and still starts.

`host ensure` and `host handoff` also print `clientRuntimeBuildId`: the id a host launched from that launch
spec by THIS client would report. A client compares it with `runtimeBuildId` to know whether the host serving
the socket runs its runtime.

A POSIX socket host with an id advertises `runtime_identity_handover` and accepts the conditional handover
`senpi host handoff --when idle --operation <id> --if-instance <instanceId> --if-generation <n>
--target-build <runtimeBuildId>`. The CLI refuses `target_build_mismatch` unless the target is its own
`clientRuntimeBuildId` (the successor runs the CLI's runtime), `stale_generation` unless the socket is served
by the named generation, `handover_unsupported` when the host does not advertise the capability, and
`foreign_agent_dir` when the host belongs to another agent dir (the same check as the generation handoff's,
`detail` naming both). It then sends the host `begin_handover`, carrying its own `agent_dir`, and the HOST
owns the operation:

1. a request naming another `agent_dir` than the host's own refuses `foreign_agent_dir` before anything else
   (a request without the field, from a CLI before it existed, is not checked); a request with an `operationId`
   it already holds answers with that operation when the terms match (and `operation_conflict` when they do
   not); a new operation is checked first against the named generation (`stale_generation`), then refuses
   `older_engine` when its `target_engine` (`{ text, ordinal }`, the requesting CLI's own engine, which the
   successor runs) is older than the host's engine by the generation handoff's rule. A request without
   `target_engine` comes from a CLI before senpi#7018, whose engine predates the guard, and is refused
   `older_engine` too. `allow_downgrade: true` (`--allow-downgrade`) skips the check;
2. it stops admitting new work: `prompt`, `steer`, `follow_up`, `send_custom_message`, `append_user_message`,
   `bash`, `compact`, `wake` and the two message edits answer `success: false` with an error starting
   `handover_pending:`. Running turns keep running and keep their control traffic (`abort` included);
3. it waits for its next safe idle point: no request in flight and no open session busy by the same activity
   judgement a drain parks by. A retained session with no work is idle. The wait has no deadline; a long turn
   delays the handover and is never aborted for it;
4. it hands the socket over through the generation handoff above, launched from the CLI's runtime with the
   CLI's daemon environment, and drains. The successor is told the target id and exits before it listens when
   its own runtime digests to another one (its files changed since the request). A successor that never
   answers is stopped, the host keeps serving and admits work again (`handover_blocked`).

The answer is exit 0 `{ action: "handover_completed" | "handover_pending", operationId, handover, ... }`: a host
idle at once hands over before answering, and a request whose target already serves the socket answers
`handover_completed` without touching anything. A repeated `operationId` answers with the operation that
already exists; another id for the same target joins the pending operation (the answer names its id), and
one for another target while one is pending refuses `handover_in_progress`. A
blocked operation refuses `handover_blocked` with the successor's failure in `detail`; a lost reply exits 1
`handover_reply_lost` after checking whether the target now serves the socket. `host status` shows the
operation as `handover: { operation_id, state, target_runtime_build_id, reason?, successor? }` with `state`
`handover_pending`, `handover_switching`, `handover_completed` or `handover_blocked`.

#### Daemon state directory (layout 2)

Every endpoint gets its own directory, named by the socket it serves, so two sockets in one agent
directory can never read each other's state:

```
<agentDir>/rpc-host-daemon/                    flat directory (shared; also a legacy host's own state)
  layout.json                                  { "layout": 2, "dir": "<sha256(canonical socket)[:16]>" }
  <sha256(canonical socket)[:16]>/             0700
    endpoint.json                              { layout: 2, registry_version: 1, endpoint_kind, socket,
                                                 created_at } - durable identity
    host.pid                                   POINTER: { layout, instance_id, generation_dir, writer }
    settings.json                              what the supervisor reads at boot
    daemon.lock  stderr.log
    generations/<instanceId>/                  one directory per generation
      host.pid                                 { pid, processStartTime, instance_id, generation,
                                                 engineVersion, engineOrdinal, launchProfileId,
                                                 socket, writer }
      settings.json  scratch/
    reservations/                              cross-generation session-path claims
```

Directories are `0700` and every state file is `0600`. The canonical socket is, on POSIX, the socket path
with its directory resolved through its deepest existing ancestor (`realpath`; a missing tail is kept
verbatim) - the same identity the ensure lock is keyed by - and on win32 the normalized lower-cased path, so
a client recomputes the directory name from the socket alone and every spelling of one socket (`/tmp` vs
`/private/tmp`, a path through a symlinked directory) shares one directory, one registration and one lock.
A socket already spelled canonically hashes exactly as it did when the name was taken from the spelling
itself, so an existing endpoint keeps its directory. A directory an older build named after a
non-canonical spelling is still listed by `status --all` and collected by `gc`, but new state goes to the
canonical directory. `generation_dir` is relative to the directory holding the pointer (`generations/<instanceId>`), and
`instance_id` is the same id the host reports as `instanceId` in `get_protocol_info` - so a pointer that
names a different id than the socket answers describes a generation that is no longer serving.

The flat directory is deliberately missing a flat `host.pid`: layout 2 writes `layout.json` there and
NOTHING else. A flat pidfile holding `{ pid, processStartTime }` is what arms every DEPLOYED client's kill
path (a desktop reader that finds one takes the host over; a `senpi` from before layout 2 stops it through
`stopManagedHost`), so writing one would let an un-updated client replace this daemon and end every other
client's sessions. Without it those clients fail CLOSED - they find no host of their own, refuse, and leave
the daemon alone. Nothing here ever writes a legacy-shaped file, and nothing here ever REMOVES one: a flat
`host.pid` that does exist belongs to a legacy host, is read-only to this build, and while the process it
names is alive an ensure never starts a second host beside it.

That record is still the proof that retires a legacy host (`host-legacy.ts`). It describes the endpoint it
stamps as `socket`, or, when unstamped, the agent directory's default socket `<agentDir>/rpc/rpc.sock`; its
pid and start time must match the live process, so a recycled pid proves nothing:

- `stopHost({ drain: true })` (`host stop --drain`) accepts it when that endpoint is the target socket and
  the host advertises `generation_handoff`, and sends the drain. A hard stop still needs a layout-2 owner.
- An ensure on ANY endpoint of the agent directory drains a live legacy host and waits for it to exit when
  its endpoint answers with `generation_handoff` and `list_sessions` (workers included) lists no session.
  Otherwise it refuses `legacy_host`, and the CLI refusal carries `detail`: the pid, its endpoint, how many
  sessions it holds and the `host stop --drain --socket <endpoint>` that retires it.
- A handoff (`host handoff`, and an ensure's upgrade) on an endpoint no layout-2 record proves counts the
  running host's sessions over a connection it keeps open. With any session, or no answer, it refuses:
  `legacy_host` with the same `detail` when a flat record proves the process, `unknown_owner` with the
  session count otherwise. With none, the successor takes the socket; a proven legacy process is sent the
  drain only if a recount over that held connection still lists no session, and a host no record proves
  is never signalled - it drains itself once another generation owns the public entry, and the handoff
  writes one stderr warning naming the socket, that host's instance and its engine.

`ensureHost` fails with a typed `HostDaemonStateError` naming the directory it could not create or write,
and starts no host in that case.

`endpoint.json` names the socket the directory serves, in the spelling its first ensure used (its name
is the hash of that spelling's canonical form). It is
written `0600` when the directory is created and re-asserted under the ensure lock. It is written whole to a
temporary name and linked into place, so no reader ever sees half a file, and a valid one is never rewritten, so
`created_at` is the endpoint's first ensure. `endpoint_kind` is `rpc_host` for a multi-session host and `tui`
for an interactive terminal's control endpoint; the first writer's kind stands like the rest of the record. A
record written before `registry_version`/`endpoint_kind` existed (`{ layout, socket, created_at }`) reads as
`rpc_host` and is never rewritten to add them. Under the lock the ensure does replace a file that does not name a
socket hashing to this directory (torn by a crash of an older build, or foreign): left alone, such a file would
leave the endpoint listed as `socket: null` and kept by `gc` as `unknown_identity` forever. It is the one file a generation's release
leaves behind: a supervisor that exits (idle, drained, or after its host child crashed) removes the pointer,
`settings.json` and its generation directory, and without `endpoint.json` such an endpoint could not even be
enumerated. A generation that exits because another entry TOOK its public socket removes only its own
generation directory: the pointer and `settings.json` then belong to whoever replaced it (a handoff rewrites
the settings before its successor boots and moves the pointer once the rename landed), and removing them could
delete the successor's freshly written registration. `stderr.log` and `crashes.jsonl` stay too. The only thing that ever removes an endpoint directory
(`endpoint.json` included) is the explicit `senpi host gc` below, and only on proof that nothing runs behind it.

The directory is PRUNED of what is no longer running on every registration write and on every single-socket
`host status` (never by `host status --all`):
a `generations/<instanceId>/` whose record names a pid nobody is running is removed, the pointer goes with it
while it still names one, and claims in `reservations/` whose owner is gone are removed too. A record that
cannot be parsed is left alone - an ensure writing one right now must not be mistaken for a generation that
ended.

#### Session paths across generations (`reservations/`)

During a handoff two hosts are alive at once, so the in-process path reservation cannot keep them off one
JSONL file. Every generation records each open session path in
`<daemonDir>/reservations/<sha256(canonical path)[:16]>.json` as
`{ instanceId, pid, processStartTime, sessionPath, attached }`, and removes it when the session closes or
parks. `attached` is republished whenever that session gains its first client or loses its last one, so the
claim says whether anybody is still driving the file.

A claim a current host publishes carries `strict_transfer: true`: its owner removes it itself when the session
parks or closes, so the claim STANDS for as long as its owner runs, attached or not (senpi#7098). A drain parks
every idle session at once, so what a superseded generation still claims is a session it is still writing - a
retained lane runs its turns with no client attached.

A claim without `strict_transfer` (written by an older build) STANDS while one of two things is true: its owner
is the generation the pointer names, or its owner still has a client attached to that session. Such a claim
from a SUPERSEDED generation that published `attached: false` is reclaimable - that generation has been asked
to drain and parks the session as it settles - so the current generation takes the path over instead of
refusing it forever. A claim whose owner is gone (a killed host, a reboot, a recycled pid with a different start
time) is ignored, and a claim written before the `attached` field existed is honored, so a running older build
is never reclaimed from.

An `open_session { sessionPath }` refused by a standing claim answers `session_path_in_use` with
`errorData { owner, retry_after_ms: 2000 }`, where `owner` carries `{ instanceId, pid, processStartTime,
sessionPath, current }` - `current: false` names a generation that is still writing the file but no longer
serves the socket. So a reopen during a handoff waits for the previous writer to finish rather than
corrupting its transcript, and a session file is never permanently unopenable.

### The `senpi host` command

Everything above is reachable from one command, so a terminal, a desktop and a task runner get a
daemon the same way instead of each re-implementing the decision:

```
senpi host ensure     [--json] [--launch-spec <file>] [--policy upgrade|fallback|never] [--socket <path>]
senpi host status     [--json] [--include-workers] [--all] [--socket <path>]
senpi host stop       [--json] [--drain [--instance <id>] [--wait-ms <n>]] [--force]
                      [--expected-generation <json>] [--socket <path>]
senpi host handoff    [--json] [--launch-spec <file>] [--socket <path>] [--allow-downgrade]
                      [--when idle --operation <id> --if-instance <id> --if-generation <n> --target-build <id>]
senpi host shard-path --kind <p|i> --owner <id> [--root <dir>] [--json]
senpi host gc         [--json] [--agent-dir <dir>]
senpi host session <open|close|model|prompt|steer|abort|read|state|list|wait> ...   (see "Driving sessions from the CLI")
```

`host stop --force --expected-generation '{"instanceId":…,"generation":…,"pid":…,"processStartTime":…}'` stops only the
generation the operator confirmed (the identity `host status` reports). It takes the endpoint lock and refuses
`stale_generation` without signalling when another generation holds the endpoint, and `unknown_owner` when the process
cannot be proven. `processStartTime` is `null` on platforms that record none (Windows); there a registration and
confirmation that are both null bind pid, instance id and generation, and the stop proves the same process before
signalling: its live start time (read with a 10 s budget) must be no later than the registration was written, so a
reused pid is refused `unknown_owner`, and an answering host must report the confirmed instance id. It cannot be
combined with `--drain`.

The contract is machine-first: EXACTLY ONE JSON line on stdout and nothing else, diagnostics on stderr,
and an exit code that classifies the outcome without parsing the line.

| Exit | Meaning |
|---|---|
| `0` | it happened (`action`: `start`, `reuse`, `handoff`, `stopped`, `drained`, or a reachable `status`) |
| `1` | it failed; `{ action: "error", reason: "host_error", detail }` |
| `2` | the command line or the launch spec is unusable (`{ action: "error", reason: "launch_spec_*" }`) |
| `3` | refused: `{ action: "refuse", reason, host }` - or an unreachable socket (`status`) |
| `4` | fallback: `{ action: "fallback", reason, host }` - under `--policy fallback`, no host is better than this one |

The socket is `--socket`, else `SENPI_RPC_SOCKET`, else `<agentDir>/rpc/rpc.sock`. `--json` is accepted for
symmetry with other commands; the answer is always JSON (the one exception is `shard-path` without `--json`,
which prints the bare socket path).

- `ensure` prints `{ action, socket, pid, instanceId, generation, engineVersion, engineOrdinal,
  capabilities, launchProfileId, runtimeBuildId, clientRuntimeBuildId, reused, upgradeable, unit, lifetime_tied_to? }`. `unit` is
  `{ cgroup, name, own }` for the host's supervisor on Linux (`null` elsewhere): `own: true` when it runs in its own
  `senpi-host-<instanceId>.scope`; otherwise `lifetime_tied_to` names the unit (`name`) whose stop would end the host
  (see "Supervisor unit" below). `host handoff` prints the same two fields for the successor. `--policy upgrade` (the default) allows a
  generation handoff, `never` only attaches or starts, and `fallback` answers exit 4 rather than attaching
  to a host this build disagrees with. `action` is `handoff` exactly when the socket was already served and
  the process behind it changed. An ensure invoked by an in-process session inside a multi-session host is
  attach-only even when its caller requested an upgrade: a host generation never starts its own successor.
  This is process-local state, not an environment marker, so a shell child remains free to run the explicit
  `senpi host handoff` command.
- `status` prints `{ reachable, lifecycle, socket, pid, instanceId, generation, engineVersion, capabilities,
  launchProfile, runtimeBuildId, handover, sessions: { total, interactive, worker, retained, foreign_attached, foreign_retained },
  zombies, rss_mb, host_rss_mb, host_footprint_mb, open_fds, memory_pressure, path_identity_resolver, env_keys, generations, pointer, crashes, shard, session_rows,
  claims_live, claims }` and exits 3 when nothing answers - with the same
  field set, so a caller parses one shape and branches on one boolean. The additive `lifecycle` field is
  `"ready"` while an answering supervised host accepts opens, `"stopping"` while it shuts down or drains,
  and `null` when nobody answers or the answering host does not advertise its lifecycle. An unserved
  socket therefore includes both `"reachable": false` and `"lifecycle": null`; `null` is not `"ready"`.
  `status --all` carries the same field and values on each endpoint row. While stopping, session listing
  is not queried and its empty counts are unobserved, not proof that all sessions have finished.
  Otherwise, `sessions` is what `list_sessions`
  reports under the same flag, so `worker` stays `0` without `--include-workers`; `foreign_*` is the same
  count from the point of view of a client holding none of those sessions itself. `rss_mb`, `open_fds` and
  `zombies` describe the daemon's whole process tree (supervisor, host, and every tool, kernel and server its
  sessions spawned); `host_rss_mb` is only the supervisor and the host process, the number `ps` shows for those
  pids (the host's memory sampler judges pressure by the host's footprint instead, see "Memory pressure").
  `host_footprint_mb` is that footprint for the same supervisor and host processes (`phys_footprint` on macOS,
  `RssAnon` on Linux): unlike RSS it keeps counting compressed and swapped pages, so a host whose RSS reads
  1.3 GB can hold 14 GB, and it is the number to watch when a host grows. All are `null` where the platform does not publish them
  (`open_fds` is `/proc`-only). `generations` lists every ALIVE generation of
  this daemon as `{ instanceId, generation, pid, engineVersion, rss_mb, host_rss_mb, sessions, current, alive, unit }`, newest
  ordinal last: `rss_mb` is that generation's own process tree, `host_rss_mb` only its supervisor and host processes, `unit`
  the cgroup and unit its supervisor runs in (`{ cgroup, name, own }`, `null` off Linux or for an ended generation), and `sessions` counts the session files it
  still claims in `reservations/` - the one occupancy number that is observable for a generation which no
  longer answers on the socket. Records of generations that ended are pruned by the read itself, so a status
  never lists a dead pid.

  `pointer` (additive) says which generation the daemon directory names as the one serving the socket:
  `{ state: "current", instanceId, candidates: [] }` normally. When the pruned pointer named a dead generation
  (or none exists), the read gives it back to the ONE generation whose record proves it still serves this socket
  (its own instance id and this public socket path, a live pid with the recorded start time, and no stop intent or
  drain request), reported as `{ state: "elected", instanceId, candidates: [instanceId] }`. With zero or several
  such generations nothing is elected: `{ state: "missing", instanceId: null, candidates }` lists the ones it saw,
  and `host stop` / `host handoff` then refuse `unknown_owner`. `host stop` and `host handoff` run the same
  election under the ensure lock; `status --all` only reports it. An election never replaces a pointer another
  writer created meanwhile, and a prune never removes a pointer a registration replaced after the prune read it.

  The last five fields and `memory_pressure` are additive (a client that does not know them ignores them):
  - `memory_pressure`: whether the ANSWERING generation's memory sampler currently reads its footprint above
    `SENPI_RPC_HOST_RSS_WARN_MB` (the state its `host_memory_pressure` records announce), read from its
    `get_protocol_info`; `null` when nothing answers or the host predates the field. It lives in the host process
    alone, so a draining predecessor's state is not reported, and it is observability only: a pressured endpoint
    admits every open.
  - `path_identity_resolver`: the ANSWERING generation's path identity resolver, `{ state, detail }` as `get_protocol_info` reports it; `null` when nothing answers or the host predates the field.
  - `crashes`: records in the endpoint's `crashes.jsonl` that are deaths - supervised host children that died
    rather than stopped, `engine_stop` and watchdog lines excluded; `0` when the file is absent. Each line of that
    file is `{ at, signal?, code?, uptimeMs, kind?, generation?, detection?, sender?, chain?, reason?, stopIntent?,
    stall?, drainingForMs? }`: `kind: "rpc-host"` is a generation's TERMINAL record (at most one per generation),
    `kind: "rpc-host-watchdog"` the host child's own line when its supervisor vanished, and
    `kind: "rpc-host-drain-overdue"` (not a death) a generation still draining once per handoff grace period, with
    `drainingForMs` (senpi#7098); `detection` is
    `supervisor` (it crashed), `external` (a signal nobody announced) or `engine_stop` (an engine process stopped it on
    purpose, named by `sender`/`chain` and `reason`, e.g. `replace_unreachable -> signal:SIGTERM` or
    `readiness_timeout; supervisor_escalated` when the caller had to SIGKILL the supervisor). Every field after
    `uptimeMs` is optional, so older readers keep parsing.
  - `shard`: `{ kind: "p" | "i", key }` when the socket's basename is `<kind>-<16 hex>.sock` (the naming
    contract below), else `null`.
  - `session_rows`: under `--include-workers` only (else `[]`), every row of that same `list_sessions
    { include_workers: true }` reply as `{ id, kind, session_path, cwd, name, attachments, context, memory }`. `session_path` is
    the host's canonical path, the key a client matches a session by; `context` is the published labels
    including the host's own `host_socket`/`host_instance`, `null` where none were published. `memory` is the
    per-session heap split the host published on the listing, as `{ main_heap_mb, kernel_heap_mb, kernel_count }`:
    the host's main-thread heap (the same host-wide number on every row), the sum of this session's kernel
    heaps, and how many kernels that is. All three are `0` for a session holding no kernel, and for every row
    of a host released before the field - never `null`.
  - `claims_live`: session-path claims in `reservations/` whose owner process is still running, `0` when the
    directory is absent.
  - `claims`: under `--include-workers` only (else `[]`), every claim in `reservations/` whichever generation
    wrote it, as `{ session_path, owner_pid, instance_id, generation, attached, live }` - so a path a
    draining predecessor still holds is visible although the answering generation no longer lists it.
    `generation` is the owner's ordinal while its generation record exists, else `null`; `attached` is `null`
    for a claim written before that flag existed.
- `status --all` reports every endpoint the agent directory holds state for and ignores `--socket`:
  `{ endpoints: [<status row>, ...] }`, each row the single-socket report above plus `dir` (the endpoint's
  daemon directory) and `identity` (what named its socket: `endpoint` = `endpoint.json`, `settings` = the
  boot `settings.json`, `generation-settings` = a generation's own `settings.json`; each accepted only when
  that socket hashes to the directory it was found in), `endpoint_kind` (`rpc_host` | `tui`, from
  `endpoint.json`; `rpc_host` for a legacy record or any other source), `alive`, `reason` and `owner`. `alive` is `true`
  exactly when the endpoint is routable - its socket ITSELF answered `get_protocol_info` naming an instance its
  directory recorded under `generations/` (a socket that answers without naming one is not routable, whatever
  generation the directory last recorded; the row's `instanceId` may still show that recorded id) - and `reason`
  is then `null`; otherwise `reason` is `live_unresponsive`
  (a recorded process is still running, or something answered that the directory did not record: a
  suspended terminal, a host past its budget) or `dead` (nothing answered and every recorded process is
  gone, or its pid now names a process with another start time - the same test `gc` applies to
  generations). A `tui` row is probed for at most 1.5 s whatever budget the hosts get, so a stopped
  terminal is reported `live_unresponsive` without stalling the listing. A `tui` endpoint is sent
  `get_protocol_info` and `list_sessions` only - the two commands both endpoint kinds answer - and its row
  carries `owner: { pid, cwd, session: { id, path, name } | null }`: the terminal's recorded pid and the one
  session it lists (`cwd`/`session` are `null` when it did not answer). `owner` is `null` on a host row. A directory none of them names is still listed with
  `socket: null` and `identity: "unknown"`, built from the directory alone - the ensure lock is keyed by a
  longer hash of the socket's transport address and cannot be rebuilt from the 16-hex name, so it can be
  shown but never addressed. Before layout 2 (no `layout.json`) the answer is `{ "endpoints": [] }`. Unlike
  the single-socket form, `--all` REMOVES NOTHING: a dead generation is a row with `alive: false`, an endpoint
  whose host exited stays listed through its `endpoint.json` with `reachable: false` and `generations: []`,
  and reclaiming what ended is left to the explicit, evidence-gated `gc`. Every endpoint is read at
  once, each under its own budget (10 s per read), and a socket that does not answer the identity probe is
  not asked for its session listing, so hung hosts cost about one budget in total; rows stay in directory order. Exit `0` while at least one endpoint answers, `3` when none does or none exists.
- `shard-path` computes a shard socket without contacting any host, so a client that does not link senpi
  can check its own copy of the naming contract against the engine: `{ kind, key, socket }` under `--json`,
  the socket path otherwise. `--root` defaults to `<agentDir>/rpc/shards`.
- `gc` removes the state of endpoints whose host is PROVABLY gone, in the agent directory (`--agent-dir`, else
  the current one; `--socket` is ignored), and answers `{ removed: [{ socket, dir, reason }], kept: [{ socket,
  dir, reason }] }` with exit `0` whatever it found (`2` for a bad flag). It never signals a process and never
  runs implicitly - not inside `ensure`, not inside `status`. For each endpoint whose socket is known it takes
  that socket's ENSURE lock (`<tmp>/senpi-rpc-host-locks/<sha256(transport address)[:32]>.lock`, the one
  `ensureHost` serializes on - not `daemon.lock`; on POSIX the address is the socket path with its directory
  realpath-canonicalized, so every spelling of one socket shares one lock) for at most 2 s, and inside it requires all three: (a) no
  `generations/*/host.pid` names a live process (pid live and start time matching; a live pid whose identity
  cannot be read counts as live; the generation the pointer names is one of them), (b) no claim in
  `reservations/` has a live owner, and (c) connecting to the socket fails with `ENOENT`, or with `ECONNREFUSED`
  on an entry that is a socket (a regular file where the socket should be is kept as `reachable`) - and so does
  every `<socket>.next-*` successor bind beside it. Only then does it unlink the `<socket>.next-*` /
  `<socket>.shield-*` siblings, then the socket, then remove the endpoint directory LAST, still under the lock;
  `reason` is `socket_refused` or `socket_absent`. A sibling that is a directory is not unlinked: it stays and
  the removed entry lists it as `skipped: [{ path, type: "directory" }]`. Because the directory goes last, a
  removal that fails part-way leaves the endpoint listed for the next gc. Everything else is kept with its
  reason: `live_generation`, `live_claim`, `reachable`, `credential_unavailable` (Windows: the socket secret
  is missing or invalid, so the pipe it names cannot be proven silent), `locked` (an ensure held the lock for 2 s),
  `legacy_layout` (a flat directory without `layout.json` - a legacy host's, never touched), `unknown_identity`
  (nothing names the socket, so its lock cannot be taken), or `failed` (reading the evidence or removing threw;
  the entry carries `error`) - and a `failed` endpoint never stops gc from going on to the others.
  One RUNNING host is different (#3268): a host of an OLDER engine runs that engine's idle decision, so when that
  decision is stuck no newer build can end it from inside. For an endpoint otherwise kept as `live_generation` or
  `reachable`, gc (`senpi host gc` and the budgeted pass `ensureHost` schedules) also judges, still under the
  lock and with observing reads only, whether the host is a stale older-engine leftover. A host that is no
  candidate at all - its owner is not proven, it does not answer, or its `engineOrdinal` is not strictly older
  than the caller's (an uncomparable ordinal is equal), which is every host of the caller's own engine - keeps
  the reason above. A candidate is stopped through the `host stop` path only when ALL of these hold, and is
  otherwise kept with the first `stale_*` reason that failed: its recorded policy is not `persistent` (`stale_persistent`), it lists no
  session, workers included (`stale_sessions`), `reservations/` holds no claim (`stale_claims`), it has been up
  longer than its own recorded `idleExitMs` plus 10 minutes (`stale_young`), and its supervisor holds no
  accepted connection on the public socket, read from the operating system (`lsof` on macOS, `/proc` on
  Linux), counted before the judge's own reads connect; an unreadable count, and Windows, keep it (`stale_clients`). A stopped host is listed under
  `stopped: [{ socket, dir, reason: "stale_old_engine", pid }]` (the key is absent when nothing was stopped), and
  its directory is collected by a later gc. The stop itself re-reads the host with 2 s budgets and is refused
  unless both reads answer and report no session, so a host that went silent after it was judged is not stopped.
  `senpi host status --all` marks such a host `stale_old_engine: true`.
  An `unknown_identity` directory is never removed by gc; remove it by hand only after checking that no pid in
  its `generations/*/host.pid` or `reservations/*.json` is running and that no process holds files under it.
  An ensure that raced a gc simply re-creates `endpoint.json` under the lock after gc released it.
  The library call `gcHostEndpoints(agentDir, { kinds: ["tui"] })` narrows a run to endpoints of those
  `endpoint_kind`s (a terminal reaping dead `tui` endpoints at its own startup): every other endpoint, and
  the legacy flat directory unless `rpc_host` is listed, is neither judged nor reported, and the ones it
  judges face the same three-part evidence. `classifyEndpointLiveness(entry)` returns the `alive`/`reason`
  verdict above for one `listHostEndpoints` entry, probing it once under its kind's budget; it reads only.
- `ensure`, `handoff` and `stop` never act on a terminal control endpoint: a `--socket` whose directory's
  `endpoint.json` says `endpoint_kind: "tui"`, or whose name is a terminal socket's (`t-<16hex>.sock`, which a
  terminal that exited leaves unrecorded), is refused with exit 3 `{ action: "refuse", reason:
  "unsupported_endpoint_kind", socket, endpoint_kind: "tui", host: null }` from disk alone, before any
  connection - whatever `--policy`, `--drain` or `--force` says. A terminal owns its endpoint; `gc` reaps a dead
  one on the same evidence as a host's.
- `stop` is the I1 carve-out: a plain stop needs a validated pidfile AND `foreign_attached +
  foreign_retained == 0`, or it refuses with exit 3 and prints the counts it refused on; `--force`
  overrides after printing the same counts; `--drain` is always permitted, because it ends no work. It
  asks through the generation's drain request (SIGUSR1 only for a generation from before it), `--instance <id>`
  names a generation other than the current one, and `--wait-ms <n>` waits for it to exit and adds `exited` to
  the answer; both need `--drain`.
- `handoff` forces a generation handoff from THIS binary. A host that cannot drain and a platform that
  cannot rename answer alike: exit 3 `{ reason: "upgrade_unsupported", detail }`. The handoff runs inside the
  endpoint's ensure lock (the one `ensure` and `gc` take), so an `ensure` arriving while the successor comes up
  waits and then attaches to the successor, and `gc` reports the endpoint `locked` rather than judging it
  halfway. An `ensure`, a `handoff` and a `stop --expected-generation` wait for the lock as long as one
  compliant holder can keep it (senpi#4602): W = H + 10 s, where H = 90 s of discovery + S + 284 s from spawn to
  a settled startup result, and S = max(5 s, M) + 37 s is the stop allowance for the child-stall setting M
  (`SENPI_RPC_CHILD_STALLED_STOP_MAX_MS`, default 60 s). At the default that is S = 97 s, H = 471 s and
  W = 481 s; every value is recomputed from the resolved M on each operation. A waiter that exhausts W exits 1
  `host_error` with `detail` `RPC host ensure lock wait exceeded <W>ms; startup not started by this caller`: it
  started nothing and signalled nothing. An idle handover request waits up to 2 x H + 20 s (962 s at the default)
  for its reply. `gc` keeps its own 2 s lock attempt and reports `locked`. A REFUSED handoff leaves the endpoint
  as it found it: the successor it started is killed and, once it has exited (up to 5 s), its generation record
  and directory are released, so `status --all` never lists it; the boot `settings.json` it rewrote before
  spawning is restored byte for byte. A cleanup that fails is reported in the refusal's `detail`.

#### Shard naming contract (`shardKey`, `shardSocketPath`)

A client may run many endpoints under one agent directory - omo one per parent session (`p`), the Desktop
one per thread (`i`), under `<agentDir>/rpc/shards/`. Every client derives the socket identically:

```
key    = sha256("<kind>:<ownerId>") in hex, first 16 characters
socket = <root>/<kind>-<key>.sock
```

`packages/coding-agent/src/modes/rpc/host-daemon-paths.ts` exports `shardKey(kind, ownerId)`,
`shardSocketPathForKey(root, kind, key)` (no hashing) and `shardSocketPath(root, kind, ownerId)`. Fixed
vectors every implementation must reproduce:

| kind | owner | key | socket under `/r` |
|---|---|---|---|
| `p` | `01a0e28d-40e4-7402-bac7-8de6e76ad84c` | `6d410ba846ba1550` | `/r/p-6d410ba846ba1550.sock` |
| `i` | `thread-0001` | `da99f196e11b1cf9` | `/r/i-da99f196e11b1cf9.sock` |
| `p` | (empty) | `3ba7290d74188485` | `/r/p-3ba7290d74188485.sock` |

#### Launch spec (`--launch-spec <file>`)

The spec is what decides the code a long-lived, machine-wide daemon LOADS, so it is a trust boundary and
deliberately a FILE - never stdin, never an argv blob, both of which have no owner to check:

```json
{
  "spec_version": 1,
  "core": { "session_runtime": "in-process", "multi_session": true, "extensions": ["ext/probe.js"] },
  "tunables": { "idleExitMs": 900000, "coldStart": "transient" },
  "env": { "SENPI_X": "1" }
}
```

Extension paths are resolved against the SPEC FILE'S directory. Four refusals are proven before any
process is started, each reported with exit 2:

| Reason | When |
|---|---|
| `launch_spec_insecure` | the file is not owned by this uid, or it is group/world writable |
| `launch_spec_path_escape` | an extension path leaves the spec directory's tree, lexically or through a symlink |
| `launch_spec_env_denied` | an `env` key outside `^(SENPI\|OMO\|PI)_[A-Z0-9_]+$` |
| `launch_spec_missing_extension` | a listed extension does not exist - a daemon never boots with half a profile |

(`launch_spec_unreadable` and `launch_spec_invalid` cover a missing file and a malformed document.)

#### Daemon environment scope

A daemon outlives the shell that started it and serves every client on the machine, so it does NOT inherit
the ensuring process's environment. It receives an allowlist of NAMES - `PATH`, `HOME`, `USER`, `LOGNAME`,
`SHELL`, `TMPDIR`, `TERM`, `LANG`, `LC_*`, `XDG_*`, `SENPI_*`/`OMO_*`/`PI_*`, `HTTP_PROXY`/`HTTPS_PROXY`/
`NO_PROXY`, `*_API_KEY`, and the provider prefixes (`ANTHROPIC_`, `OPENAI_`, `GOOGLE_`, `GEMINI_`, `AZURE_`,
`AWS_`, `OPENROUTER_`, `XAI_`, `MISTRAL_`, `DEEPSEEK_`, `GROQ_`, `CEREBRAS_`, `MINIMAX_`) - plus whatever the
spec's `env` states. Matching is case-sensitive on POSIX and case-insensitive on win32, where the OS wiring
(`SystemRoot`, `ComSpec`, `PATHEXT`, ...) is allowed as well. Values are never inspected; `status` reports
the granted NAMES as `env_keys` and never a value.

The product-lane allowlist has an explicit transient denylist. Session context (`PI_SESSION_*`,
`PI_GOAL_STORE_FILE`, `PI_PROVIDER`, `PI_MODEL`, `PI_REASONING_LEVEL`,
`PI_PROMPT_CACHE_SAFE_WAIT_SECONDS`), the Python eval-kernel parent
(`SENPI_PY_KERNEL_PARENT_PID`), and inherited `SENPI_RPC_HOST_*` generation/watch/scratch identity never
cross into either an initial daemon or a handoff successor. Legitimate daemon configuration in the same
namespace, such as RSS thresholds, idle windows and feature flags, remains allowed. The spawn applies the
new generation's own instance id, generation and daemon directory after filtering, so caller overrides
cannot replace lifecycle identity.

#### Verifying a daemon build (live QA drivers)

Two POSIX-only drivers in this repository exercise the whole daemon against real processes in a sandbox agent
directory, printing one JSON line per step (written synchronously, so a step that hangs has still printed every step
before it) and a final cleanup receipt. They are how a build is checked before it is trusted with other clients'
sessions:

| Driver | What it proves |
|---|---|
| `node scripts/qa-rpc-socket/inprocess-daemon-qa.mjs` | Two COMPILED binaries of the tree differing only in build epoch; `host ensure --json` run from the older one; per-session `context` isolation (each session's extension sees only its own); `list_sessions` with and without `include_workers`; 50 sessions with the measured thread cost and no refusal; a retained session re-attached across a dropped connection; 200 bash calls leaving zero zombies; and a generation handoff by the newer binary while a client stays connected. |
| `node scripts/qa-rpc-socket/generation-handoff.mjs` | The handoff alone, against the source supervisor: `ensureHost` -> generation 0, `handoffHost` -> generation 1 on a new pid, `session_path_in_use` naming the owner while the held session is parking, `session_closed { reason: "handoff_parked" }`, the predecessor exiting, the transcript reopening intact in the new generation, and `stopHost({ drain: true })` draining to exit. |

Both exit non-zero if a daemon, a fixture host or the sandbox survives the run: a host outliving its QA is
exactly the failure they exist to catch.

### Driving sessions from the CLI

`senpi host session` is a thin client over the wire commands this document already describes: it attaches to a
session (or starts the shared host, for `open` only) and relays one request, so an orchestrating agent or script
can drive a session without writing its own RPC client. It adds no new wire command; it relies on the typed
`errorCode` the host sets on `prompt` (`streaming`, and `provider_credentials_missing`, `provider_credentials_expired`
or `no_model_selected` when the session cannot start a turn), `set_model` (`model_not_found`) and `get_entries`
(`not_found`) refusals.

```
senpi host session open   --cwd <dir> [--model <provider/id>] [--name <text>] [--prompt <text|@file>]
                          [--launch-spec <file>] [--socket <path>] [--json]
senpi host session close  <ref> [--socket <path>] [--json]
senpi host session model  <ref> <provider/id> [--socket <path>] [--json]
senpi host session prompt <ref> <text|@file> [--socket <path>] [--json]
senpi host session steer  <ref> <text|@file> [--socket <path>] [--json]
senpi host session abort  <ref> [--socket <path>] [--json]
senpi host session read   <ref> [--tail <N>] [--since <entryId>] [--messages] [--socket <path>] [--json]
senpi host session state  <ref> [--socket <path>] [--json]
senpi host session list   [--socket <path>] [--json]
senpi host session wait   <ref> [--until idle|done] [--timeout <ms>] [--socket <path>] [--json]
```

The contract is machine-first, exactly like `senpi host` itself: EXACTLY ONE JSON line on stdout per call
(written synchronously), diagnostics on stderr, and an exit code that classifies the outcome without parsing
the line.

| Exit | Meaning |
|---|---|
| `0` | it happened - the payload's `action` names the subcommand (`open`, `close`, `model`, `prompt`, `steer`, `abort`, `read`, `state`, `list`, `wait`) |
| `1` | it failed: `{ action: "error", reason, detail }` with `reason` one of `transport_gone`, `wait_timeout`, `open_failed`, or `host_error` (a host failure that carries no code; `detail` is the host's text) |
| `2` | the command line is unusable: `{ action: "error", reason: "usage" \| "prompt_file_unreadable", detail }` |
| `3` | refused: `{ action: "refuse", reason, detail, data? }` - every host error code (`unknown_session`, `host_draining`, `session_held` with `holders`, `model_not_found`, ...; the host's `streaming` reads `busy` and `not_found` reads `unknown_cursor`) plus the CLI's own `ambiguous_session` (with `candidates`), `host_unavailable` (no host answers the socket and the verb is not `open`) and `unsupported_endpoint_kind` (the socket is a terminal's control endpoint, refused before any connection) |

A refusal is classified by the host's `errorCode`, or by the session router's bare code when that is the whole
`error` string; message text is never parsed. A host started by an older build (reused by `open` as compatible)
sends no `errorCode` for a busy `prompt`, an unknown model or an unknown cursor, so until that host is replaced
those three refusals read exit 1 `host_error` with the host's text in `detail`.

Every verb except `list` resolves `<ref>` (a `sessionId`, `durableSessionId`, `name`, or `sessionPath`) through
`list_sessions` and then ATTACHES to the session before acting. A name that more than one live session carries is
refused `ambiguous_session` rather than resolved to either, and so is a `durableSessionId` that more than one
transcript carries, live or parked (a caller-minted id reused while its first session was parked): `candidates`
lists their paths, or the routing handle (`rpc-N`) of a live session that has no transcript file yet. A
`sessionPath`, or a `durableSessionId` naming one
transcript under `<agentDir>/sessions/`, that the host no longer lists (it parked the session) is RESUMED: the CLI
re-opens it with `open_session { sessionPath, retain_on_disconnect: true }`, so the resumed session again outlives
the call, and acts on the new routing handle it reports. Attaching is what authorizes `close` and what lets `wait` receive events;
it also resets the host's idle window like any other attached connection (see "Host idle exit" above). `list` is
the one exception: it calls `list_sessions { observe: true }`, so polling it never counts as host occupancy.

- `open --cwd <dir> [--model <provider/id>] [--name <text>] [--prompt <text|@file>] [--launch-spec <file>]`
  attaches to or starts the shared host through the same `ensureHost` attach-or-create path as `senpi host ensure`
  (`--socket` resolution is identical, too), then calls `open_session { cwd, retain_on_disconnect: true, ... }` so
  the session survives this process's exit. It prints `{ action: "open", socket, pid, sessionId, sessionPath,
  durableSessionId, cwd, model: { provider, id }, attached, reused, prompt? }`. `--name` sets the session's display
  name; `--prompt` starts one turn after open and reports its `disposition` without waiting for the turn to finish.
  When naming or `--prompt` fails after the session exists, `open` closes that session again and the failure
  payload carries `sessionId`, `sessionPath`, `durableSessionId` and `closed`; `closed: false` (the close itself
  failed, e.g. the transport dropped) tells the caller to close it by those ids.
- `close <ref>` attaches and closes the session. `{ action: "close", sessionId, closed, reason? }`: `closed: false`
  means another client still holds an attachment (`close_session` only released this call's own attachment), not a
  failure. The host aborts and drains a mid-turn session within its own grace; the CLI never force-aborts.
- `model <ref> <provider/id>` changes the model whether the session is idle or mid-turn and prints
  `{ action: "model", sessionId, requested: { provider, id }, model: { provider, id }, pendingModelSwitch }`
  (`model` and `pendingModelSwitch` come from `get_state` read right after the call). `set_model` also persists the
  GLOBAL default model and provider, not just this session's; a switch to a smaller context window can be held as
  `pendingModelSwitch` instead of applying immediately. An unknown model answers `{ action: "refuse", reason:
  "model_not_found" }`.
- `prompt <ref> <text|@file>` starts a turn and prints `{ action: "prompt", sessionId, disposition }`
  (`"started"` or `"handled"` - a `"handled"` disposition means an input handler consumed it and no model run
  necessarily follows). A prompt sent while a turn is already running is refused `busy` (the host's `streaming`
  code); the check is the host's own admission, made when the prompt arrives.
- `steer <ref> <text|@file>` prints `{ action: "steer", sessionId, disposition, streaming }`. `streaming: false`
  means the session was idle when the steer arrived: the message is PARKED and delivered with the next `prompt`,
  it does not start a turn by itself. `streaming: true` means it was queued into the running turn.
- `abort <ref>` stops the running turn (if any) and prints `{ action: "abort", sessionId, acknowledged: true,
  aborted }`. `aborted` reflects whether a turn was actually running when the abort was admitted; an abort on an
  idle session is still exit 0 with `aborted: false` (a no-op, not a failure). Use `wait --until idle` to confirm
  the session has actually settled afterward.
- `read <ref> [--tail N] [--since <entryId>] [--messages]` prints `{ action: "read", sessionId, entries, count,
  total, leafId, nextSince }` (or, with `--messages`, `{ action: "read", sessionId, messages, count }` from
  `get_messages`, the runtime context rather than the durable log). `--since` is EXCLUSIVE (entries after that id)
  and is applied before `--tail`; `nextSince` is the id of the LAST entry this call actually returned, in append
  order - it is the cursor for the next call. `leafId` is the current branch leaf and is informational only; it is
  never the right value to pass as the next `--since`. An unknown `--since` id is refused `unknown_cursor`.
- `state <ref>` prints `{ action: "state", sessionId, durableSessionId, state }`, the session's `get_state` object
  untouched.
- `list` prints `{ action: "list", socket, sessions }`, an observe-only read of `list_sessions`.
- `wait <ref> [--until idle|done] [--timeout <ms>]` (defaults: `idle`, `600000`) blocks on the session's real
  settle events, never on a poll: `--until done` resolves on the first `agent_settled` (or a synthetic one from a
  sealed session) after the call; `--until idle` resolves only once a settle ALSO leaves `steering`, `followUp` and
  `pendingMessageCount` empty in `get_state`, so a steer queued mid-turn delays `idle` until its own follow-up turn
  also settles. `turn_end` and `agent_end` are deliberately never used for either mode: one prompt can produce
  several `turn_end`s through tool continuations, and `agent_end` may still be followed by a retry. It prints
  `{ action: "wait", sessionId, until, outcome }` where `outcome` is `"done"`, `"idle"`, `"already_idle"` (no turn
  was running when `wait` was called; for `--until idle` the queues must also be empty, so a steer parked on an idle
  session keeps `idle` waiting until a `prompt` drains it), `"session_closed"` or `"session_parked"`; a timeout is
  `{ action: "error", reason: "wait_timeout" }` exit 1, and a transport loss while waiting is `transport_gone`.

Session references: `open` and `list` report `sessionId`, `sessionPath` and `durableSessionId` together. `sessionId`
is a per-host-epoch routing handle that disappears across a park or handoff; `sessionPath` and `durableSessionId`
survive it, and every subcommand accepts any of the three (plus the session's `name`) as `<ref>` and re-resolves it
on every call, resuming a parked session as described above. A session parked before its first message has no
transcript yet and cannot be resumed; a reference to it is `unknown_session`.

Ownership: public endpoints first use [authentication](#authentication); socket clients then attach before mutating a session. The `senpi host session` commands already attach
on the acting connection. Raw clients use `attach_session` for a live identity or `open_session` to open/resume
a path. This release serves and logs legacy unattached mutations unless `SENPI_RPC_REQUIRE_ATTACH=1`;
see [Attachment admission](#attachment-admission). Reads remain available without an attachment. `close`
releases the caller's own attachment and closes the session only when no other client still holds one.

Retention limits (what `open`'s `retain_on_disconnect: true` does NOT survive): an explicit `close`, the host's own
idle-eviction window (`SENPI_RPC_SESSION_IDLE_EVICTION_MS`, default 30 minutes, after which the session is parked -
any `senpi host session` verb given its path or durable id resumes it). The host process exiting does not end it: the next
host on the same endpoint reopens it (see "Retained sessions across a host restart"). A session that has not
received a message yet may have no JSONL file on disk even though `open` already reported a `sessionPath`.

A minimal orchestration run:

```sh
id=$(senpi host session open --cwd /work --model anthropic/claude-sonnet | jq -r .sessionId)
senpi host session prompt "$id" "do the thing"
senpi host session wait "$id" --until done --timeout 300000
senpi host session read "$id" --tail 5
senpi host session close "$id"
```

### Child reaping on a socket host (`SENPI_RPC_HOST_REAPER`)

A socket host reaps the exited child processes that no thread is left to wait on. A `worker_threads` Worker owns the
exit watchers of every child it spawned, so terminating one - which is what the session-worker quarantine does - turns
its already-exited children into zombies of the HOST process, for every spawn API (`child_process.spawn`, `Bun.spawn`,
`Bun.$`) and under both the source and compiled runtimes. Children spawned from a live thread are reaped by their own
runtime and never reach the reaper.

Latency and safety: a 1-second unref'd tick enumerates the host's DIRECT children, peeks at each with
`waitid(P_PID, pid, WEXITED | WNOHANG | WNOWAIT)` - which reads the exit status without consuming it - and only
`waitpid(pid, WNOHANG)`s a pid that stayed waitable across two ticks at least 30 seconds apart (`waitpid(-1)` is never
called). So an abandoned child is claimed 30-31 seconds after it exits. That window is what keeps the reaper from
stealing a child from a live owner: a thread blocked in a synchronous call cannot reap its own child until it unblocks,
and a stolen child breaks the owner's contract (measured: `child_process` and `Bun.spawn` reject with `ECHILD`,
`Bun.$` never settles). A thread that blocks synchronously for longer than the window while awaiting a child therefore
loses that child's exit status; `SENPI_RPC_HOST_REAPER_MIN_WAITABLE_MS` raises the window (never below its 5-second
floor) and `SENPI_RPC_HOST_REAPER=0` turns reaping off entirely. The bindings need `bun:ffi`: a host running under Node
logs one warning at startup and reaps nothing. While at least ten children sit waiting, the host logs one line per
five minutes with the count and the three commonest command names.

On Windows, listeners and clients deterministically map the logical socket path to
`\\.\pipe\senpi-rpc-<sha256[:32]>`. Callers keep using the same `unix://` CLI value; the logical path remains the
ownership and settings identity, and callers never construct the pipe name themselves.

Socket event visibility is attachment-scoped for session content: each connection receives agent output only from sessions
attached to that connection, with every record tagged by its routing `sessionId`. Content-free lifecycle records
(`agent_start`, `agent_settled`, `agent_idle`, `session_opened`, `session_closed`, and `session_parked`) are broadcast to all
registered connections, including the supervisor's unattached observer, so host lifecycle accounting remains accurate without
exposing session content. The one exception is `session_closed` and `session_parked` for a session opened with
`kind: "worker"`: they are delivered only to
the connections attached to that session, so machine-driven work neither appears in nor disappears from a client that never
asked for it. Every other lifecycle record, and every record of an `interactive` session, keeps today's broadcast. Host-level
records (`host_superseded`, `host_stalled`, `host_memory_pressure`) are broadcast the same way and describe the host process rather than a
session. Correlated responses and dialog extension UI
requests (select, confirm, input, and editor) are requester-only; other extension UI state records go to the session's
attached connections. To observe a foreign session, open it by its existing
`sessionPath`; the host attaches that connection during `open_session`.

### Session status stream (`subscribe_sessions`)

A multi-session host advertising the capability `session_status` pushes one `session_status` record per change of every session a subscription matches: opened, running, waiting on a question, compacting, idle, unloaded or closed, plus attachment, model, queue and context changes. A subscription is activity-neutral: it never counts as an attachment, never refreshes a session's idle window, and an `observe: true` request never counts as host activity either.

#### subscribe_sessions

```json
{"id": "s1", "type": "subscribe_sessions", "sessions": "all", "include_workers": false, "include_context": false, "mirror": "none", "effects": false}
```

- `sessions`: `"all"` (default), `{ "ids": [...] }` (routing ids, durable session ids or session paths), or `{ "childrenOf": "<durableSessionId>" }` (sessions whose `context.parent_session_id`, or else `context.root_session_id`, equals it).
- `include_workers`: include `kind: "worker"` sessions; default `true` for `childrenOf`, `false` otherwise.
- `include_context`: carry each session's published `context` on its records; default `false`.
- `mirror`: `"none"` (default), `"all"` or an array of record types (`["message_update", "tool_execution_start"]`). The matched sessions' records of those types are also delivered to this connection. Mirroring is an explicit opt-in open to every subscriber of the host (the socket is per user, mode 0600): it is not an attachment and does not keep a session alive. Worker content is mirrored only with `include_workers: true`.
- `effects`: also deliver `effect_status` receipts of matched sessions; default `true` for `childrenOf`, `false` otherwise. Each `effect_status` is enqueued after the record that caused the transition and shares the subscription's `seq`.
- `admissionId`, `retry`: compact admission fields behind `SENPI_ENGINE_SOCKET_COMPACT_UPDATES` (see `cancel_attempt` and "Admission retries"); ignored with the flag off.
- `dialogs`: with capability `dialog_observer`, also deliver the `ui_request_pending` and `ui_request_settled` records of matched sessions; default `false`. It takes effect only together with a `mirror` selection, stays observing, and grants no answering authority (see "UI-answer receipts and dialog observation").

Response:

```json
{"id": "s1", "type": "response", "command": "subscribe_sessions", "success": true,
 "data": {"subscriptionId": "sub-1", "seq": 0, "hostGeneration": "0", "hostInstanceId": "<uuid>", "snapshot": [ /* session_status records, seq 0 */ ]}}
```

The snapshot is the state at subscription time. The response carrying it is the first record of the subscription: a connection that already holds 64 subscriptions is refused with `subscription_limit`, and on the stdio transport the command is refused with `unsupported_transport`. Every later record of the subscription has `seq` strictly one more than the previous one, starting at `seq + 1` behind the response. A reconnect is a new subscription with a fresh snapshot; nothing is replayed. Refusals carry `errorCode: "invalid_subscription"` (or `subscription_limit` / `unsupported_transport`) and `errorData { reason, action }`.

#### unsubscribe_sessions

```json
{"id": "u1", "type": "unsubscribe_sessions", "subscriptionId": "sub-1"}
```

Ends a subscription held by the same connection; a closed connection ends its subscriptions. Any other id answers `unknown_subscription` with `errorData { reason, action }`.

#### set_session_context

```json
{"id": "c1", "type": "set_session_context", "sessionId": "rpc-1", "patch": {"task_status": "running", "run_epoch": 2, "stale_key": null}}
```

An attached connection patches the context a session publishes (on `list_sessions { include_workers: true }` and on `session_status` for subscribers with `include_context`). Keys match `^[a-z][a-z0-9_]{0,63}$`; values are strings of at most 256 characters, numbers, booleans, or `null` to delete; the patched context is at most 4096 bytes of JSON. The host's own keys (`host_socket`, `host_instance`, `shard_key`, `tree_key`) and the lineage keys (`parent_session_id`, `root_session_id`) are refused with `invalid_session_context` and `errorData { reason, action }`. The session's extensions keep reading the context the session was opened with, and a `childrenOf` subscription matches on that frozen open-time context, so no patch moves a session into or out of a supervisor's children view. The response carries the published `context`; subscribers with `include_context` receive a `session_status` with cause `context`.

The SDK sends it with `RpcClient.setSessionContext(patch, sessionId?)`, which defaults to the attached session and rejects with an `RpcCommandError` carrying the code. A client with no attached session that passes no `sessionId` refuses locally, without sending anything, with the same `RpcCommandError` and `errorCode: "session_not_attached"`.

A connection without an attachment receives `errorCode: "session_not_attached"` with `errorData.reason: "this connection is not attached to that session"` and `errorData.action: "attach first with open_session { sessionPath }, then patch its context"`.

#### session_status

```json
{"type": "session_status", "subscriptionId": "sub-1", "seq": 4, "sessionId": "rpc-1", "durableSessionId": "<id>", "sessionPath": "<path>",
 "kind": "interactive", "cwd": "<cwd>", "status": "idle", "reason": "aborted", "attachments": 3,
 "archived": false, "settled": false, "model": {"provider": "anthropic", "id": "<model>"}, "thinkingLevel": "high", "pendingQueue": {"steering": 1, "followUp": 0},
 "lastChange": {"at": "2026-10-12T08:00:00.000Z", "cause": "abort", "by": "client"}}
```

- `status`: `opening`, `idle`, `running`, `waiting_input` (a question is pending), `compacting`, `unloaded` (the routing handle ended and the session reopens by `sessionPath`; `reason` is `idle`, `unload_session` or `handoff`), or `closed` (`reason` is the `session_closed.reason`). After an abort ends a run, `idle` carries `reason: "aborted"`.
- `lastChange.cause`: `open`, `prompt`, `agent_end`, `agent_idle`, `abort`, `question`, `compaction`, `set_model`, `queue`, `attach`, `detach`, `replace`, `park`, `close`, `context`, `rename` (the session's name changed: `set_session_name` or a generated title), `archive` (`set_session_archived`), `settle` (`set_session_settled`) or `retry` (an auto-retry wait started or ended); `by` is `client`, `agent` or `host`.
- `waiting: { kind, attempt, maxAttempts, delayMs, until, error? }` is present only while a `running` session sleeps in an auto-retry backoff: `kind` is `rate_limit` for a 429, rate, usage or quota limit and `retry` for any other transient error, `until` is the ISO time of the next attempt, `error` the provider error cut to 200 characters. It clears when the retried request starts or the retry ends. `get_state` carries it as `retryWait`. A `list_sessions` row carries the same `waiting` without `error`: a listing reaches every connection that can list sessions, so the provider's error text stays on `get_state` and on `session_status`.
- `archived` is the session file's archived flag (`set_session_archived`); it is always present.
- `settled` is the session file's Done flag (`set_session_settled`); it is always present. `settledBy` says how the session reached Done and is present only while `settled` is true and the flag was written with a `by`.
- `context` is present only with `include_context`. `lastEffect: { effectId, kind, state }` names the session's most recent effect receipt (an input with a `clientMessageId`, an abort, a model or thinking-level switch) and is absent on hosts without the `effect_ledger` capability or before the session's first effect.
- On `new_session`, `switch_session` or `fork` the routing id stays; the record carries the new `durableSessionId` and `sessionPath` with cause `replace`.

Ordering: a status rides the subscribing connection's own queue and is enqueued AFTER the record that caused it, so a connection that is both attached and subscribed always reads `queue_update` before the `session_status` it caused, and `agent_idle` before the matching `idle`.

Three-client example (A drives, C attaches, B only subscribes):

```text
B -> subscribe_sessions {}                               <- snapshot [] seq 0
A -> open_session {cwd}                                  B <- session_opened rpc-1; session_status open (seq 1)
C -> open_session {sessionPath}                          B <- session_status attach, attachments 2
A -> set_model {...}                                     B <- session_status set_model
A -> steer {message}                                     B <- session_status queue, pendingQueue.steering 1
A -> abort {}                                            B <- session_status abort, idle/aborted
A -> new_session {}                                      B <- session_status replace, new durableSessionId
A -> open_session {cwd}                                  B <- session_opened rpc-2; session_status open
A -> close_session {rpc-1}                               B <- session_status detach, attachments 1
```

`session_opened { sessionId, durableSessionId, sessionPath, kind, cwd, context? }` is emitted for every session the host creates (not for an attach). An `interactive` session's record is broadcast to every connection, including connections without a subscription. A `worker` session's record reaches its attached connections and matching subscribers with `include_workers`. For both kinds, `context` is included only for matching subscribers with `include_context`; all other recipients receive the record without context.

#### effect_status

```json
{"type": "effect_status", "subscriptionId": "sub-1", "seq": 5, "sessionId": "rpc-1",
 "effectId": "stop-1", "kind": "abort", "state": "done", "disposition": "applied",
 "by": {"connectionId": "A"}, "at": "2026-10-13T08:00:00.000Z"}
```

On a host with the `effect_ledger` capability, a subscription with `effects: true` receives one `effect_status` per effect transition of every matched session: every `rpc_effect` transition (`abort`, `set_model`, `set_thinking_level`) and every input admission transition (`prompt`/`steer`/`follow_up` with a `clientMessageId`, whose `effectId` IS the `clientMessageId`). `kind` is `input`, `abort`, `set_model`, `set_thinking_level`, `unload` or `dequeue`; `state` is `accepted`, `applied`, `done` or `failed`; `disposition` and `outcome` follow the `get_effect_status` shape. `by` names the connection whose command the effect belongs to (absent on `input` receipts, which carry no actor) and `at` is the transition time.

An `effect_status` is enqueued on the subscribing connection AFTER the record that caused the transition and shares the subscription's gap-free `seq`: a subscriber watching an `abort { effectId }` reads the abort's `session_status` deltas and the effect's `accepted -> applied -> done` as one ordered stream, with `done` landing after the `agent_idle` status that sealed the turn. The causing record is a session event or status delta, never the command's own response: a connection that sends `abort { effectId }` and also subscribes can read the effect's `accepted` (and usually `applied`) before its `abort` response arrives. A host publishes `effect_status` only for sessions it holds; transitions of a session no host holds are not buffered.

### Client information

Clients may send `set_client_info` with `{ sessionId?, width, capabilities?, remoteOrigin? }` (`remoteOrigin`: see "Remote origin"). `capabilities` registers the connection's
opt-in client capabilities (see [Client capabilities](#client-capabilities)); a name the host does not know is ignored,
never refused. Registration belongs to the connection that sent it: socket disposal removes it, and clients must
re-register `capabilities` after every reconnect. `width` is accepted for compatibility and has no effect: the host
renders no extension components, so a component factory passed to `setWidget`, `setHeader`, or `setFooter` never
reaches the wire.

In classic `--mode rpc` (one client over stdio), `SENPI_RPC_CLIENT_CAPABILITIES` is the initial set and a
`set_client_info` that carries `capabilities` replaces it, after the `interactive_user` role check; one without
`capabilities` keeps it. Withdrawing `question` settles each pending structured question once as `question_resolved` with
outcome `cancelled`, and withdrawing or declaring `extension_events` stops or starts extension events.

### Session kind and context (`open_session`)

`open_session` accepts two additive, opaque per-session fields. Both are inert inside the host: they never take part in
auth, model, extension or resource resolution, and they are never merged into the host's parsed CLI configuration.

- `kind: "interactive" | "worker"` (default `interactive`) is the session's visibility class. A `worker` session is
  machine-driven work (a task child, a team member): it is omitted from `list_sessions` unless the caller passes
  `include_workers: true`, and its `session_closed` record reaches only the connections attached to it. An `interactive`
  session behaves exactly as before. A value that is neither is refused with `invalid_session_kind` - an unknown kind is
  never downgraded to `interactive`, because that would publish machine-driven work to every client.
- `context: Record<string, string>` (default `{}`) is an opaque label map. The host stores it frozen for the session's
  life, hands it to that session's extensions as `pi.sessionContext`, and republishes it only on
  `list_sessions { include_workers: true }`. Caps, enforced at the boundary: at most 32 keys, every key matching
  `^[a-z][a-z0-9_]*$`, every value at most 16 KiB, and at most 32 KiB of JSON in total. Anything else is refused with
  `invalid_session_context: <detail>`, where the detail names the cap that was broken.

A socket host also stamps its own identity into every session's context, overwriting any client-supplied
value for the same keys, because the host is the authority: `host_socket` is the PUBLIC endpoint clients
address (the supervisor's path for a supervised host, the bound path for a bare one), realpath-canonicalized
through the deepest existing ancestor of its directory (so the first generation of a shard, which starts before
`rpc/shards/` exists, and every successor stamp the same string), and stays the same across a generation handoff; `host_instance` is the answering generation's `instanceId`
(`get_protocol_info`) and changes with every handoff. So an extension can tell which endpoint and generation
it runs behind without an environment variable. `host_socket` is omitted where no public path exists (an
abstract socket, a supervised win32 host); a stdio host adds neither key.

One multi-session host therefore loads ONE extension set and still lets an extension recognize the session it was loaded for
(`pi.sessionKind`, `pi.sessionContext` - see
[ExtensionAPI session identity](extensions.md#pisessionkind--pisessioncontext)). Probe
`session_kind` and `session_context` in `get_protocol_info` capabilities before relying on either: an older host
ignores both fields and lists every session.

Default-invisible worker sessions are invariant **I4** above: a client that does not pass `include_workers: true`
sees the daemon exactly as it saw a host serving only that client.

### Warming a host (`warm`)

A fresh host pays a one-time cost on its FIRST session: the extension module graph compiles, and the extensions'
factories load whatever they load for that session's kind and context (a task engine for a `child` role, for
example). Every later open on that host reuses it. A client that starts one host per session pays it on every session
unless it warms the host first.

#### warm

Loads what the next `open_session` with the same `cwd`, `kind` and `context` needs, without opening a session:

```json
{"id": "w1", "type": "warm", "cwd": "/abs/project", "kind": "worker", "context": {"role": "child"}}
```

```json
{"id": "w1", "type": "response", "command": "warm", "success": true, "data": {"state": "warmed"}}
```

Every field is optional and means what it means on `open_session`: `cwd` defaults to the host's cwd and must be
absolute, and `kind` and `context` are validated with the same caps and refused with the same codes
(`invalid_path`, `invalid_session_kind`, `invalid_session_context`). A socket host stamps its own identity into the
context exactly as it does for an open, so the extensions see what they will see in the real session. The host builds
that session's cwd-bound services - settings, resources, extensions with their factories run for this kind and
context - inside a provider scope of their own, then drops them.

- No session is created: nothing appears in `list_sessions` (with or without `include_workers`), no `AgentSession`
  exists, and no extension receives `session_start`.
- `warm` never attaches its connection, whether or not it carries `observe: true`: a connection that has only sent
  observing reads and warms is an observer, so a host that only received `warm` idles out on its normal deadline
  (`SENPI_RPC_HOST_IDLE_EXIT_MS` under a supervisor, `SENPI_RPC_HOST_EMPTY_EXIT_MS` for the host itself). A warm still
  loading neither holds that window open nor holds a drain.
- It takes no session lock and no open barrier, so it never waits for a live turn and a live turn never waits for
  it. It does share the host's one loop: loading an extension graph is the same work an open does.
- It is idempotent per profile: `data.state` is `warmed` when this call (or a concurrent warm of the same profile it
  joined) did the loading, and `already_warm` when an earlier warm had, in which case nothing runs again. A failed
  load (`warm_failed: <detail>`, for example a `cwd` that does not exist) is not remembered, so it can be retried.
- A host whose sessions run in worker isolates (`--session-runtime worker`) has nothing it can warm from the host
  process: it answers `state: "unsupported"` and does not advertise the capability. A draining generation refuses with
  `host_draining`.
- A host whose launch carried a private descriptor table (`SENPI_PRIVATE_FDS`) runs this warm itself once at boot,
  for its default profile (the host's cwd and context, no `kind`), right after it starts listening, so an extension
  can claim its private channel before any client connects. A `warm` of that profile then joins it, or answers
  `already_warm` once it is done, and never loads again; a boot load that fails is logged to stderr and the host
  keeps serving. Without a table nothing loads before an `open_session` or `warm`.
  The boot warm's factory call is what claims the channel: its services are then dropped and its provider scope is
  closed, so every later session's `takeInheritedPrivateChannel` returns `undefined`. An extension must keep its
  channel handling host-global, never tied to that factory call's `pi`. This applies only to in-process hosts: a
  `--session-runtime worker` host has no `warm`, so one handed a table loads nothing at boot.

Probe `warm` in `get_protocol_info` capabilities before sending it: an older host answers an unknown command with an
error.

### Parking and claiming a built session (`park_claim`)

An in-process multi-session host advertises `park_claim`. A caller that knows the next session's profile can
build it ahead of time:

```json
{"id":"p1","type":"park_session","cwd":"/abs/project","kind":"worker","context":{"role":"child"}}
{"id":"p1","type":"response","command":"park_session","success":true,"data":{"state":"parked"}}
{"id":"c1","type":"claim_session","cwd":"/abs/project","kind":"worker","context":{"role":"child"},"retain_on_disconnect":true}
```

A successful claim has exactly the `open_session` success payload (`sessionId`, `state`, permission-mode fields
and, where available, `presence`), with `command: "claim_session"`. It takes the opener's normal connection
capabilities, attachment, ownership and retention policy. No runtime is built in the claim request.
When no ready park matches, or an option requires a fresh open, the response is:

```json
{"id":"c1","type":"response","command":"claim_session","success":true,"data":{"claimed":false}}
```

Send a normal `open_session` after that miss. A claim does not wait for an in-flight park. A ready park is consumed
once; concurrent claims cannot receive the same session. After a successful claim, the host schedules a replacement
for that profile in the background.

Both commands require an absolute `cwd`. `kind` defaults to `interactive`; `context` has the same validation and
host-identity merge as `open_session`, and its key order does not affect matching. Repeated parks of the same profile
share one build or answer `state: "already_parked"`. Each host holds at most four speculative profiles, including
builds in flight and scheduled replacements; another profile answers `state: "full"`. This cap never limits ordinary opens. A ready park expires
after 60 seconds; repeating `park_session` does not extend its lifetime.

Claim accepts the open options. `retain_on_disconnect`, model/provider, thinking level, permission preset,
prompt surface and browser engine apply through the same live operations used by ordinary session commands or
attach-on-open. A requested `sessionPath`, `durableSessionId`, `expectedHostInstance`, `spawnedBy`, `env`,
`auto_title`, `retryFallback`, `attended: false`, or an unpaired provider/model choice returns `claimed: false`
without consuming the park. Compact admissions (`admissionId`,
`retry`, or a connection that selected compact transport) also miss, so the caller uses the existing `open_session`
admission contract. Invalid applicable options receive their ordinary error response.

Parks run the existing open implementation without an owner or reply. They start attended, in memory, and acquire
their persistent file and file hold only when claimed. Until then they appear in no session listing, status stream,
`session_opened` event, session-list file, hosted export, durable-id collision check, attachment count or zero-session
trim count. Build timing is dropped. `park_session` never makes its connection an idle-exit attachment; a claim does.
Both methods are `device_admin` in the method-class table because they require a host cwd.

Expiry, drain, handoff and stop dispose parks without a public terminal record or a handover entry. Builds already
in flight are closed when they finish; a stopped host never schedules replacements. Parks have no persistent
transcript to survive a crash, and no successor reopens them. Worker-isolate hosts do not advertise `park_claim` and
answer `park_claim_unsupported`; classic RPC and terminal single-session endpoints answer `multi_session_disabled`.
Probe the capability before sending either command.

### Delegated connections (`declare_delegation`)

A client that forwards records on behalf of someone else (a relay host forwarding a remote viewer) declares it, and
the host then decides every record on that connection with its own method-class table: the forwarder keeps no
table. Hosts that do this advertise `delegated_connection_v1`.

```json
{ "id": "d1", "type": "declare_delegation", "principal": { "deviceId": "laptop-7", "deviceName": "Laptop", "conn": "c1" }, "granted": ["observe", "drive"] }
{ "id": "d1", "type": "response", "command": "declare_delegation", "success": true, "data": { "granted": ["observe", "drive"], "digest": "71d68465…" } }
```

- Only a connection that proved the endpoint key (see "Authentication"; on Windows, the socket secret) may declare;
  any other gets `delegation_unauthenticated`.
- The first declaration must come before any record other than `get_protocol_info` and `authenticate`, else
  `delegation_late`.
- `principal.deviceId` (1-256 characters) is required; `deviceName` (1-256) and `conn` (1-64) are optional.
  `granted` holds each of `observe`, `drive`, `answer`, `thread`, `device_admin` at most once (anything else is
  `delegation_malformed`).
- A declaration on a delegated connection may only narrow it: the same principal and a subset of the current grant,
  else `delegation_fixed`. It takes effect for the very next line, even one written in the same chunk.

On a delegated connection every record is checked before dispatch:

| Check | Refusal `errorCode` |
|---|---|
| Not JSON, not an object, or without a string `type` | `delegation_malformed` |
| A type the engine does not classify | `delegation_unclassified` |
| Its class (for a record-dependent type, the class of this record) is not granted | `delegation_not_granted`, `errorData: { class }` |
| A `connection_local` record without the grant it needs (below) | `delegation_local_only`, `errorData: { class }` |

`connection_local` records act on the delegated connection itself and need no grant, except `subscribe_sessions`
(`observe`), `record_user_activity` (`drive`), and `release_session`, `warm`, `reclaim_session` and `move_session`,
which reach the host (`device_admin`). `set_client_info` needs no grant and is not filtered: a viewer declares its own
roles. A permitted record runs exactly as on any other connection, with the same answer: a record its type's schema
would refuse is not refused by the delegation check, it gets the same response a local connection gets. A refusal is an ordinary error response
(`success: false`, `error`, `errorCode`). Secret and grant-select dialogs stay answerable only from the connection
that raised them, delegated or not.

A delegated connection ends whenever the viewer it forwards for leaves, while the forwarder keeps serving what that
viewer opened to the next one (senpi#5808). So every `open_session` on a delegated connection is retained, whatever
`retain_on_disconnect` it carries (an explicit `false` included): the connection's end detaches the session, which
stays `open` with `attachments: 0` and attachable from any connection, exactly like a retained session (see "Retained
sessions"). The host decides this when it reads the line, so a connection that ends while its open is still running
leaves that session retained too. Like any retained session it is still closed by an explicit `close_session`, parked
by the idle-eviction window, and recorded (at open, and again at park) for the next host on the endpoint, which reopens
it on startup, so it survives into the next generation and across a host restart. `attach_session` never turns retention on: attaching over a delegated
connection to a session that is not retained leaves it closing with its last attachment. One consequence to know: a
delegated `open_session` by `sessionPath` (which needs `device_admin`) that lands on a session already live and opened by
someone else joins it as an attach that asks for retention, so it turns retention on for that live session and every
client of it, the same as a local `open_session` that passed `retain_on_disconnect: true` would. A connection that never
declares keeps the ordinary rule: closed with its last connection unless `open_session` asked for
`retain_on_disconnect: true`.

Private MCP presenter records are the exception: on a delegated connection, every record whose `type` starts with
`mcp_form_` or `mcp_presenter_` is answered in the private reply shape `{ "type": "mcp_form_reply", "id"?, ... }`,
never with `type: "response"`, so a forwarder can route the answer by its type alone. The four presenter client
records (`mcp_presenter_context`, `mcp_form_presented`, `mcp_form_response`, `mcp_form_sync`) reach the presenter
authority exactly as on a local connection when the declaration granted `answer`; that authority still decides
every form. Otherwise the reply is `{ "type": "mcp_form_reply", "id": "...", "error": "<code>" }`:

| Record | `error` |
|---|---|
| A presenter client record without the `answer` grant (also after a narrowing re-declaration drops it) | `delegation_not_granted` |
| `mcp_presenter_control_info` | `presenter_not_authorized` |
| Any other `mcp_form_*` or `mcp_presenter_*` type | `delegation_unclassified` |

A private reply bypasses the connection's event queue, snapshots, mirrors and replay. These records are not in the
method-class table, so `classify_record` answers `class: null` for them and the digest is unchanged.

#### Connection roles on a delegated connection (`delegation_roles_v1`)

A host that advertises `delegation_roles_v1` also takes `roles` on `declare_delegation`: the connection roles
(`interactive_user`, `task_parent`) the forwarder lets the principal hold. Each appears at most once; anything else is
`delegation_malformed`. The roles themselves are still claimed by the viewer's own `set_client_info`; `roles` is the
ceiling, and a role counts only while both the claim and the ceiling hold it.

```json
{ "id": "d1", "type": "declare_delegation", "principal": { "deviceId": "laptop-7" }, "granted": ["observe", "drive", "thread"], "roles": ["interactive_user", "task_parent"] }
{ "id": "d1", "type": "response", "command": "declare_delegation", "success": true, "data": { "granted": ["observe", "drive", "thread"], "digest": "71d68465…", "roles": ["interactive_user", "task_parent"] } }
```

- The first declaration decides the mode for the connection's life: with `roles` it is role-bound, without them the
  roles are the client's own claims as before. `roles` on a later declaration of a connection that started without
  them is `delegation_fixed`.
- A later declaration may only narrow `roles` too (else `delegation_fixed`); omitting `roles` keeps the current set.
  Every successful reply on a role-bound connection echoes the set in force after it as `data.roles`, in the order
  `interactive_user`, `task_parent`.
- A narrowing takes effect for every record the engine reads after it, including a record that was admitted earlier
  and reaches its role check later in a session worker. Work already admitted (a held input, a turn that started)
  stays.
- `detach_connection` on a role-bound connection starts a new incarnation of the connection with the same roles
  ceiling: a role claimed before the detach no longer counts, so the client claims again with `set_client_info`. A
  `set_client_info` written before the detach and decided after it is refused alone with
  `errorCode: "delegation_incarnation_stale"`; it changes nothing, and the connection stays open.
- The `remoteOrigin` of any delegated connection is its principal (`deviceId`, `deviceName`): a `set_client_info`
  carrying another valid `remoteOrigin` succeeds and the value is ignored; a malformed one is still
  `remote_origin_invalid`.

A forwarder may number each record it forwards on a role-bound connection with a top-level `relayExec` (a positive
safe integer). The host removes it before anything else reads the record, refuses any other value as
`delegation_malformed`, and adds an `authority` receipt to every response to that record:

```json
{ "id": "h1", "type": "hold_input", "sessionId": "s1", "inputId": "i1", "revision": 0, "text": "…", "relayExec": 41 }
{ "id": "h1", "type": "response", "command": "hold_input", "success": true, "data": { "entryId": "…" }, "authority": { "exec": 41, "incarnation": 1, "epoch": 1, "roles": ["interactive_user"] } }
```

`roles` is the set of roles the record's role checks granted, or `null` when it consulted none. `incarnation` starts at
1 and grows by one per `detach_connection`; `epoch` starts at 1 in each incarnation and grows only when a narrowing
removed a role or the incarnation ended. Order receipts of one connection by `(incarnation, epoch)`. Connections that
are not role-bound never get `authority`, and `relayExec` is an ignored member there.

`classify_record` answers the class of one record without running it, on any connection:

```json
{ "id": "c1", "type": "classify_record", "record": { "type": "prompt", "message": "/mcp" } }
{ "id": "c1", "type": "response", "command": "classify_record", "success": true, "data": { "class": "device_admin", "version": 1, "digest": "71d68465…", "static": false, "rule": 1 } }
```

`class` is `null` for a record the engine does not classify; `static` says whether the class depends only on the
type (`rule` is then absent), so a client may cache static answers per `digest`. It is never an authorization: the
host decides again when the record arrives.

### Prompt surface

Where a session's replies render decides its system prompt. `terminal` is the classic prompt; `app` (a host that
shows replies as chat, such as the OmO Desktop) keeps the same intent routing and stop-condition rules but asks for no
visible `I read this as ...` routing line, and tells the agent that tool and hook feedback (comment-checker findings,
language-server availability, internal notices) is for it to act on, not to report unless it changes the result.
`chat` (a chat bridge that posts each reply to people in a conversation) takes every `app` rule and also drops the
handoff block and todo/ledger lines: the reply is the answer itself, and the todo tool emits no "Handoff due" cue.
As a backstop, the `chat-reply-scrub` builtin removes a leading routing line, a handoff block and todo-ledger lines
from each finalized assistant message on `chat` before it is emitted or persisted; streamed `message_update` deltas are
not rewritten.

A multi-session host decides the surface per session: `open_session.promptSurface: "terminal" | "app" | "chat"` builds that
session's prompt for the named surface, so one host serves a terminal client and an app client at once. An omitted field
uses the host process's `SENPI_PROMPT_SURFACE` (`app` or `chat` selects that surface; unset or any other value is `terminal`),
which remains the only switch for a single-process `--mode rpc` client. A later `open_session` that attaches to a live
session with another `promptSurface` rebuilds that session's prompt; an attach without the field keeps the current
surface, and `new_session` / `switch_session` / `fork` inside the session keep it too, also when the attach lands while
one of them is still building the replacement. Probe `prompt_surface` in
`get_protocol_info` before sending the field; an older host ignores it. Probe `prompt_surface_chat` before sending
`chat`: a host without it refuses `chat` with `invalid_launch_profile`, so a gateway falls back to `app`. Any value other
than `terminal`, `app` or `chat` is refused with `invalid_launch_profile`.

#### Fallback chain per session (`retry_fallback_profile`)

`open_session.retryFallback: { modelFallback: boolean, fallbackChains: Record<string, string[]> }` is the fallback
policy THIS session runs with, e.g. a task child's own chain. It overrides that session's `retry.modelFallback` and
`retry.fallbackChains` in memory only: it is never written to a settings file, and no other session on the host sees
it. A session opened without the field keeps the host's settings. It is applied when the open creates the session; an
attach to a live session keeps the policy that session was created with. Probe `retry_fallback_profile` in
`get_protocol_info` before sending the field. A malformed profile (a missing `modelFallback`, a chain that is not an
array of non-empty selectors, a selector longer than 512 characters, more than 32 chains or 32 entries per chain) is
refused with `invalid_launch_profile` rather than opening a session without the chain its caller asked for; an empty
chain (`[]`) is accepted and means no fallback for that key. If something inside that session later changes a
fallback setting through the settings setters, that write follows the setters' own rules (it persists to the global
settings file) and replaces the session's override for that one key only: a `setFallbackChain` drops the profile's
chains, while `modelFallback` keeps the profile's value. The policy is not stored with the session, so a client that
reopens a session after it was closed sends the profile again.

#### Browser engine per session (`browser_engine`)

`open_session.browserEngine: "connected" | "builtin" | "none"` names the browser THIS session's skills drive: the
user's own browser, the app's in-app browser, or none. It is session-scoped, never process-wide: the session's tool
subprocesses (the bash tool and everything it spawns) and its eval kernels, including their child processes, see
`OMO_BROWSER_ENGINE=<value>`, and no other session on the host does. A session opened without the field sees no such
variable, even when the host process itself exports one (a daemon never inherits it from the process that ensured it).
`BSK_HOME` and `BSK_BIN` are per install, not per session: they pass from the host environment to every session
unchanged. A later `open_session` that attaches to a live session with another `browserEngine` moves that session to
it, and an attach without the field keeps the current engine; `new_session` / `switch_session` / `fork` keep it too,
also when the attach lands while one of them is still building the replacement. Probe `browser_engine` in
`get_protocol_info` before sending the field; the capability is advertised only because the value reaches every
consumer above. Any other value is refused with `invalid_launch_profile`.

#### Host tools (`host_tools`)

Every session on a host that advertises `host_tools` registers its host tools (today `show_html_page`) through the
SDK's `attachHostTools`: the tool always serves on its own, and a host bridge may route its calls to an app that
serves the same public name. The public SDK exports the writer such an app calls back (`writeHtmlPage`). An app
offers its host tool attachment (and the credential that serves it) only to a session on a host that names this
capability; any other host keeps the standalone tool.

#### Caller env per session (`session_env`)

`open_session.env: Record<string, string>` is the per-spawn caller env channel (senpi#4381): the small, explicit set
of variables THIS session's tool subprocesses (the bash tool and everything it spawns, in-process or in the tool
child) see on top of the process environment. It is applied to that one session only, after the daemon's own name
allowlist: the values are never merged into the host process environment, never carried to a successor generation
through it, and never visible to a session that neither received them on its own open nor inherited them as a task
child (below), so two clients opening through one daemon with different values each get only their own and a later
open without the field gets none. Names are checked against the host's caller-passable set: exactly
`OMOCAT_LANE` by default (the lane identity a task tree's tools label their posts with), plus whatever names the host
process was started with in `SENPI_RPC_CALLER_ENV_NAMES` (comma-separated; a session-owned or host-owned name such
as `PI_SESSION_ID` is never accepted). A name outside that set, a non-string value, a name that is not `[A-Z_][A-Z0-9_]*`,
more than 16 entries, a value over 4096 characters or one containing NUL is refused with `invalid_session_env: <detail>`
naming the offender (a name longer than 64 characters is cut to its first 64 plus `...`) and the passable set; values
are never echoed. A task child (`open_session.spawnedBy` naming, by `durableSessionId` or `sessionId`, a parent this
host holds open and bound, the same rule attach uses) inherits its parent's entries, and its own `env` entries win
over them; a `spawnedBy` naming a parent that is opening, closing, quarantined, closed or not on this host inherits
nothing. Inheritance follows the same trust boundary as
attach: the host does not tie the opening connection to the parent, so any client on the host that could attach to
the parent (and run its tools there) can open a child that inherits the parent's entries, which grants it nothing
attach does not. Applied when the open
creates the session; an attach keeps the session's existing env. A session parked for a generation handoff carries
its env into the successor's reopen as part of its own record, not through the successor's process environment.
Probe `session_env` in `get_protocol_info` before sending the field.

A skill that must tell the client what the browser is doing publishes it as that session's own event: an extension
registers a tool that calls `pi.rpc.emit(name, data)`, an eval cell reaches it as `tool.<name>(...)`, and the host adds
the owning `sessionId` to the `extension_event` record. Only clients that advertised `extension_events` receive it.


### Session auto-titling

Auto-generated session titles are on by default only for interactive launches. A multi-session host decides titling per
`open_session`: `auto_title: true` titles that session, `auto_title: false` leaves it untitled, and an omitted field
keeps the host-wide default (`--auto-title-sessions` or the `auto_title_sessions` client capability). Probe
`auto_title_per_session` in `get_protocol_info` before relying on the field; an older host ignores it. A non-boolean is
refused with `invalid_launch_profile`. Sessions resumed with existing context messages are never retitled.

The title is generated as part of the settle of the prompt's run: the title request follows that run's last model
request, and its `session_info_changed` is emitted after the run's `agent_end` and before its `agent_settled` and
`agent_idle`, so it precedes anything a client or a background job does once the session is idle. A run that is aborted
(Esc, Stop, `abort`) is not titled; the next prompt's run titles the session instead.

`--auto-title-sessions` still opts every session on that host into titling when `auto_title` is omitted. It is
deprecated for multi-session hosts — prefer per-session `open_session.auto_title` so two clients on one daemon do not collide
over a launch-profile flag:

```bash
senpi --mode rpc --multi-session --auto-title-sessions
```

Startup: `senpi --mode rpc --multi-session` → NO default session is constructed (no default `AgentSessionRuntime`, no default extension/watcher load). Classic `senpi --mode rpc` is unchanged except that `get_protocol_info` is answered and a resolved `extension_ui_response` is acknowledged under its frame `id` (see [Extension UI Responses](#extension-ui-responses-stdin)). Mode is fixed at process start; there is no runtime transition.

### Session replacement

A replacement (`new_session`, `switch_session`, `fork`) responds as soon as the swap is committed; the derived-surface refresh that rebinds extensions continues afterwards. That refresh does not disturb work the client starts against the committed session: tool activation performed while extensions are still binding no longer cancels an in-flight compaction or invalidates its context. Outside an MCP startup window, `loaded_surfaces_changed` is emitted only when the surface digest actually changes, so it is NOT a settle barrier for the extension rebind; the one settle point it does carry is the end of the MCP startup window described under [loaded_surfaces_changed](#loaded_surfaces_changed).

#### Replacement identity event

When `new_session`, `switch_session`, or `fork` swaps the live session - including replacements an extension drives, which a client never issued - every attached connection receives:

```json
{ "type": "session_replaced", "durableSessionId": "…", "sessionFile": "…", "cwd": "…", "sessionName": "…" }
```

The command response reports only `{ cancelled }`, so this event is the only push channel carrying the new identity. The identity is `durableSessionId`, never `sessionId`: top-level `sessionId` is reserved for the per-connection routing handle that multi-session hosts tag every record with, and that tag is applied last, so reusing the key would overwrite the identity the event exists to deliver. Classic mode emits the event untagged.

A replacement first stops the session's running turn. That turn's `agent_end` (`aborted: true`) arrives before `session_replaced` and names the cause, so a client that did not ask for the abort can tell it apart from a failure:

```json
{ "type": "agent_end", "aborted": true, "abortCause": { "kind": "session_replaced", "reason": "new", "targetSessionFile": "…", "targetSessionId": "…" } }
```

`reason` is `new`, `fork` or `resume` (`switch_session`); when present, `targetSessionId` equals the `durableSessionId` of the `session_replaced` that follows. A fork of a session that was never saved gets its new id only after the teardown, so it names no target. The first named cause wins until the `agent_end` it explains: a plain `abort` arriving meanwhile does not erase it. An ordinary `abort`, a `reload` and a shutdown carry no `abortCause`.

### Session lifecycle: unload and reopen

#### unload_session

```
open --(turns)--> idle --unload_session / idle sweep--> unloaded (session_parked) --open_session { sessionPath }--> open
                                                        close_session / release_session --> closed (session_closed, terminal for this handle)
```

`unload_session { sessionId, effectId?, interrupt?, clearQueue?, children?: "refuse" | "detach", force?, deliveries?: "refuse" }` frees a session this host keeps loaded. The transcript stays on disk; queued input stays in the admission ledger and is restored on the reopen (input sent without a `clientMessageId` too) unless `clearQueue`; every attached client receives `session_parked { sessionId, sessionPath, reason: "unloaded" }` (the idle sweep's park says `reason: "idle"`); the session leaves `list_sessions`; `open_session { sessionPath }` reopens it.

The answer is always `success: true` with `data.outcome`: `unloaded` (with `sessionPath`), or `refused` with `reason`, `detail` and `action`, changing nothing:

| `reason` | When | Override |
|---|---|---|
| `turn_active` | an agent run, a prompt about to start, compaction, barrier-held work, and a run with any tool body executing even while a dialog is open (a running tool can open one, such as an MCP elicitation); never a run whose only work is an unanswered dialog with no tool body executing (a permission prompt before its call starts), which the unload aborts (the dialog is cancelled) and waits for, bounded, as with `interrupt: true` | `interrupt: true` aborts and waits (bounded) first |
| `work_pending` | bash, an admitted delivery not yet written (its ids in `pending.deliveries`), another request for the session | `interrupt: true`; once the aborted work settles, a delivery still waiting in the runtime's queues leaves them and the ledger unwritten (its sender redelivers it), and every later answer lists its id in `dropped.deliveries`. With `deliveries: "refuse"` a busy session (any `turn_active` blocker) holding such deliveries is refused here, with or without `interrupt` and before anything is interrupted; a delivery admitted while an interrupt it did allow is settling, and an idle session's stranded deliveries, are still handed back and named in `dropped.deliveries` |
| `extension_work` | extension-published work: background terminal jobs, non-persistent monitors, detached eval cells, a pending question; `detail` names the sources | `force: true` (that work is stopped; only persistent monitors come back on the reopen) |
| `children_live` | child tasks still working, or worker sessions here whose `context` names this session as parent or root | `children: "detach"` leaves them running |
| `attached` | other clients hold the session (none of the caller's own holds count) | `force: true`; they receive the park |
| `host_draining`, `session_closing`, `unsupported` | the host is draining, the session is already closing, or it has no file / a worker isolate owns it | none |

With `effectId` the unload is a ledger effect (`kind: "unload"`): `done` with `disposition: "unloaded"`, or `failed` with `outcome.kind: "refused"` and the same reason; a same-id retry replays (a refusal with its `pending.deliveries`). Capability: `unload_session`; `deliveries` and `pending.deliveries`: `unload_refuse_deliveries`. CLI: `senpi host session unload <ref> [--interrupt] [--force] [--clear-queue] [--children detach]` (exit 3 on a refusal).

##### Graceful close (`graceful: true`)

`unload_session { sessionId, graceful: true, waitMs?, force?, children?, effectId? }` closes a session without interrupting it (oh-my-openagent#14313). `graceful` and `interrupt` exclude each other. Capability: `unload_graceful`.

1. The fence, in one step: automatic turns (monitor, goal and loop wakes) wait as notices under the engine-turn hold `closing`, `admit_external_message` refuses every new delivery with `errorCode: "session_closing"`, and the queued input leaves the session unread: admitted delivery ids in `dropped.deliveries` (their senders keep them), the user's queued text in `dropped.user_messages`.
2. The drain: the running turn, its tool calls, bash, compaction, prompts in preflight and other requests end on their own. Nothing is aborted. The wait is bounded by `waitMs` (default 60 000 ms, at most 600 000 ms).
3. The close: the `closing` hold is released, a `session-closed` custom entry (`{ graceful, turn, waited_ms, returned, stopped: { wake_sources }, at }`) is the clean-stop record, and the teardown's `session_shutdown` carries `closed: true`. The terminal builtin then records no monitor or background job to restore, loops end `stopped` and an active goal is paused. The run ended normally, so a reopen writes no `interrupted-run` entry and arms no hold.

The answer is `outcome: "unloaded"` with `sessionPath`, `dropped` and `graceful: { turn, waited_ms, stopped }`. `turn_active` and `work_pending` are what a graceful close waits for, and `extension_work` is what it stops, so neither refuses it; every other reason refuses before anything is fenced. A drain that outlives `waitMs` answers `outcome: "refused"`, `reason: "turn_active"`, `timed_out: true`, `open: true`, `admission: "reopened"`, `turn` and `waited_ms`, plus `dropped`: the hold is released and admission reopened, so the session keeps running as before, minus the input already handed back. With `effectId` the effect is `done` only when the session closed, so its `updatedAt` is the close.

A terminal's control endpoint takes the same record, `graceful: true` only (anything else is refused `unsupported`). It also refuses `composer_draft` while the composer holds unsent text or an attachment, before the fence and again after the drain, so a close never discards what a person typed. After the answer, the terminal exits by itself as a quit does, and its session file keeps the same clean-stop record.

### Multi-session host lifecycle (cold start + idle exit)

The lifecycle supervisor is also available to bundled/rebranded runtimes through the hidden internal launch route `--internal-rpc-host-supervisor`. This route is wire-invisible and intended only for desktop launchers: it receives the public socket, ownership directory, and the runtime command/arguments to wrap, then runs the same `host-lifecycle.ts` implementation used by `ensureHost()`. Normal CLI modes do not use or advertise this route. Compiled standalone binaries also re-enter themselves through this route automatically: a bun executable always boots its embedded entrypoint, so the script-path re-entry used under a JS runtime would be parsed as CLI arguments (`Unknown option: --socket`) and the host could never start.

When a Node.js or Bun caller starts a host, both spawn levels retain runtime options such as loaders and memory limits, but remove eval/print expressions, `--input-type`, and interactive mode from `process.execArgv`. This lets embedding code launched with `node -e` or `bun -e` start the intended host entry instead of replaying itself. Under Bun, any token beginning with `-e` or `-p` is removed as well, because Bun reads it as code glued to the flag (`-eCODE`, `-e=CODE`, `-pCODE`); Node rejects those forms, so single-dash V8 options such as `-expose-gc` are kept there. Explicit child commands keep their supplied arguments.

On win32 the supervisor's internal hop lives under `<daemonDir>/internal-<uuid>`, and that directory is created recursively. Before allocating the internal hop or spawning a child, the supervisor ensures `<publicSocket>.secret` exists, creating its parent directories and a 32-byte secret with mode `0600` when needed. An existing valid secret, including one written by `ensureHost()`, is reused unchanged. Direct launch therefore works on a fresh profile without caller-side secret provisioning. Provisioning failures identify the bootstrap step and secret path; the public endpoint still requires the secret handshake before forwarding RPC traffic.

Hosts started through `ensureHost()` are wrapped by a lifecycle supervisor that owns the public socket and spawns the
real RPC host on a private internal hop. The policy lives in `<daemonDir>/settings.json` (and is copied into
the generation's own directory):

```json
{ "socket": "…/rpc.sock", "capabilities": ["extension_events", "custom_unsupported"], "coldStart": "transient", "idleExitMs": 900000 }
```

- `coldStart` — `transient` (default): the host exists for the current login session and idle-exits. `persistent`:
  no idle exit; the host stays until it is stopped or dies.
- `idleExitMs` — idle-exit window in milliseconds, default `900000` (15 minutes).

Environment overrides beat the file, and invalid values fall through to the next source: `SENPI_RPC_HOST_COLD_START`
(`transient`|`persistent`) and `SENPI_RPC_HOST_IDLE_EXIT_MS` (positive integer milliseconds).

The host exits only after the window elapses with NO attached client connections and NO active turns — continuously.
Any attached connection or agent turn resets the window, so a busy host never exits. A connection attaches with its
first request line, unless that line is an OBSERVING read: a side-effect-free read carrying `"observe": true` -
`get_protocol_info`, `list_sessions`, `subscribe_sessions`, `unsubscribe_sessions`, `get_effect_status`,
`get_pending_inputs`, `get_subscription_limits`, and the session reads `get_state` and `get_entries` (capability
`observe_reads`) - or a `warm` (marked or not - see "Warming a host"). A connection that only ever sends observing reads never counts and never resets the window, so a
poller (`senpi host status [--all]`, which marks both of its reads, a doctor loop, a runtime panel) can look at every
endpoint as often as it likes without keeping any of them alive; the first request that is anything else attaches the
connection from then on, and `observe` on any other command is ignored. While a connection has not sent its first
line yet the host does not exit, and the window keeps running. Hosts that predate the field ignore it, so a marked read
works against every generation. A watcher can therefore read a session's state and history (`get_state`,
`get_entries` with `observe: true`) as often as it likes: the host's attached count stays at 0 and its idle window
keeps running.

An observer can HOLD the host (senpi#5626): an observing read that also carries `"hold_host": true` makes its
connection a holder, which counts as an attached connection (it resets the idle window and keeps the host open) until
an observing read on the same connection carries `"hold_host": false` or the connection closes. Only the literal
booleans on a read marked `observe: true` count; a `warm` or an unmarked read never holds. A remote-control daemon
holds the host this way while at least one remote viewer is attached, and releases it when the last one leaves. A
held observer is occupancy everywhere occupancy is read: the idle-exit window, the empty-host exit, and the
owner-death quiescence check. Hosts that predate the field ignore it and treat the read as a plain observing read.

A connection from one of the host's OWN sessions is DEPENDENT and never counts either. A host keeps its generation
id (`SENPI_RPC_HOST_INSTANCE_ID`) in its own environment (a socket host that named itself writes it there at start),
and every child it starts for an agent (shells, eval kernels, the tool child) gets it as
`SENPI_RPC_ORIGIN_HOST_INSTANCE` instead, so a nested host never adopts it as its own identity (senpi#7034). The
host's other launch hand-off (daemon directory, generation, build id, watch binding, key sentinel and its
launch-default `SENPI_RPC_CLIENT_CAPABILITIES`) never reaches those children. `RpcClient` sends whichever of the two
ids it has as `"origin_host_instance"` on every socket request. When a connection's first non-observing request
names the host's own generation, the
connection neither holds the window open, nor blocks the owner-death grace, nor keeps an empty host alive. Without
this, a task tree whose children open their own children on the shard they run in (omo's `p` shards are keyed by the
root session) keeps that shard alive through its own connections after the owner and every outside client are gone.
Turns still count as activity, so a dependent session mid-turn keeps the host open until the turn ends. Hosts that
predate the field ignore it.

An attached connection whose sessions on the host have ALL closed stops keeping it open (oh-my-openagent#14272): a
parent that keeps its task-shard connection after its last session there closed no longer keeps a 0-session host
alive, and the window starts when that session closes. A connection that never held a session still counts as
before (an ensure's attach hold, a client about to open), as does any connection with an open or a command in flight;
attaching (the first non-observing line) restarts the window. The supervisor proxies bytes and cannot see sessions, so its observer
connection sends `{"type": "watch_host_occupancy", "observe": true}` (an observing read with no response) and the
host answers on that connection with `{"type": "host_occupancy", "holders": <n>}`, the number of attached
connections that still occupy it, at once and again on every change; the supervisor counts at most that many attached
clients, plus held observers. Until the host has answered, and while the observer connection is unhealthy, every
attached client counts, as before. While a supervisor watches, the host's own empty exit stays with the supervisor.
The owner-death quiescence check still counts every attached client. The supervisor learns about turns through
its observer connection to the host; while that connection is unhealthy it cannot see turns, so it treats activity as
unknown and keeps the host open as if a turn were running — but only for one idle window, during which it keeps
reconnecting. An observer that stays unhealthy for longer than the window stops counting as busy, and the connection
count alone decides from there. A `persistent` host has an infinite window and so keeps its infinite benefit of the
doubt. The exit itself is clean: the RPC host
receives SIGTERM first, flushes pending output, removes its socket, and the supervisor then removes `settings.json`,
its generation directory and, last, the registration pointer (`host.pid`); the stderr log stays for diagnostics. The
crash-path cleanup the host runs when its supervisor dies uses the same order, so a missing pointer always means the
teardown is complete. After an idle exit, the next `ensureHost()` transparently
starts a fresh host. `get_protocol_info` over the public socket behaves exactly as before; the supervisor is
wire-transparent.

`ensureHost()` hands its caller an attach hold: the connection its readiness answer arrived on stays open and counts
as an attached client, so the idle window cannot close between the ensure and the caller's own attach, however slow
that attach is. Every caller must call `release()` on the returned `EnsuredHost` once its own client is
attached, or right away when it attaches later on its own connections; the idle window starts from there. Until then
the host counts the calling process as an attached client, so a transient host whose ensuring process is still running
never starts its idle window: a long-lived caller that ensures and never releases keeps the host up for its whole
lifetime. The hold never keeps the calling process alive, and the operating system ends it when that process exits.

On POSIX, the supervisor writes a fresh 32-byte internal key once to its child's stdin and keeps the write end
open. Before the CLI touches `process.stdin`, the child reads exactly that key within a two-second startup budget,
reopens `/dev/fd/0` as a close-on-exec lifetime descriptor, and restores fd 0 to `/dev/null`. Descendants that inherit
stdin therefore receive immediate EOF. A missing or short key refuses startup with `internal_key_unavailable`.

On Linux the supervisor also creates `lifetime.fifo` (mode 0600) in its private 0700 hop directory, holds its only
writer (close-on-exec, opened before the child is spawned), and passes the path in `SENPI_RPC_HOST_LIFETIME_FIFO`. The
host opens the read end non-blocking; EOF, when the kernel closes the last writer at the supervisor's death, ends it. This
is the Linux event binding, because reopening stdin fails there. On macOS libuv reports no EOF for a FIFO, so the
reopened stdin is the event binding. While either is armed, the recorded-identity check is one 30 s backstop.

Where reopening succeeds, Node watches lifetime EOF with an unref'd `net.Socket`; Bun uses a `Bun.file(fd).stream()`
reader that does not hold `process.exit()`. Any reopen failure, including Linux socketpair stdin's `ENXIO`, is logged
and falls back to polling the recorded supervisor `SENPI_RPC_HOST_WATCH_PPID`: a free `kill(pid, 0)` every tick, and
its start compared on one clock per platform, rarely. On Linux that is `SENPI_RPC_HOST_WATCH_PSTART_TICKS`, the
supervisor's `/proc/<pid>/stat` start ticks (internal, not a secret; immune to wall-clock steps, read without spawning);
elsewhere it is the `ps lstart` value in `SENPI_RPC_HOST_WATCH_PSTART`. Only `ESRCH` or an observed start change ends
the host. Missing, unreadable, timed-out or permission-denied identity observations keep it
running. The direct parent is never compared: spawning wrappers may legitimately be between supervisor and host.
Slot 3 is still passed but is not armed for supervised POSIX children because wrappers can close or reuse it.
Windows retains its inherited lifetime pipe. Bare hosts and embedders without supervisor configuration are unaffected.

The POSIX internal hop stays in its per-launch temporary directory and publishes no key file. Proxy, readiness and
activity-observer connections all prove the in-memory key with challenge-response before sending session traffic.
The readiness probe (10 s) and the activity observer (5 s) bound each handshake attempt; the proxy forwarding a public
connection has no deadline. An uncoordinated supervisor (a direct launch, or a successor started by a command that is
not the engine's own) fails startup on the first silent attempt, as before. Under a coordinated start it disposes that attempt and retries on a
fresh connection with fresh nonces, and the launcher's startup phases below decide when the start has failed. A wrong
key proof still fails at once.

#### Startup readiness (senpi#4602)

`ensureHost()` no longer gives a new host one fixed 10 s to answer. It owns a startup controller from just before
the spawn, on its own monotonic clock. The supervisor and its host child report fixed milestones on a dedicated
startup pipe at descriptor 16, above the 5..15 range the private-descriptor table forwards. The supervisor relays
the child's records in a frame of their own, so neither process can complete the other's phase. Each phase gets a
finite allowance from the moment it is entered. Repeats, heartbeats and wrong-attempt records add no time, and every
deadline is clipped to 180 s after the spawn:

| Phase | Allowance | Completed by |
|---|---:|---|
| `supervisor_bootstrap` | 30 s | the supervisor's startup stub, before its lifecycle graph loads |
| `supervisor_setup` | 15 s | the supervisor, once its host child is spawned and its pipe is relayed |
| `host_bootstrap` | 30 s | the host child's startup stub |
| `host_runtime` | 60 s | the host child, once everything its internal listener needs is initialized |
| `internal_ready` | 15 s | the supervisor's authenticated internal-ready reply |
| `observer_ready` | 15 s | the supervisor's first authenticated activity observer |
| `public_published` | 15 s | the supervisor, once the public socket and key are published |
| `presenter_resolved` | 30 s | the launcher, once its presenter exchange settles (immediately when none was requested) |
| `public_verified` | 10 s | the launcher's compatible public `get_protocol_info` answer and its attach hold |

A custom host-child command (`--child-command`) cannot report its own progress. The supervisor declares this before
spawning it, and `host_bootstrap` + `host_runtime` + `internal_ready` become one `opaque_host` phase of 90 s, completed
only by the authenticated internal reply. A supervisor command that is not the engine's own runs in a legacy mode: one
`public_verified` phase of the whole 180 s, with every inner limit of its own. A slow start that keeps meeting its
phase deadlines is accepted. A stalled phase fails at its own allowance, and nothing runs past 180 s. At a deadline,
expiry beats an event that arrives in the same instant, and a settled start is never revived. A failed start runs its
owned teardown within the failed-start allowance (104 s at the default `SENPI_RPC_CHILD_STALLED_STOP_MAX_MS`). Spawn
to a settled failure is therefore at most 284 s. The failure exits 1 `host_error` with one machine-readable `detail`
line, followed by the host's stderr diagnostics:

```
RPC host startup timed out: phase=<phase>; limit=<phase|overall>; phase_budget_ms=<n>; startup_budget_ms=180000; elapsed_ms=<n>; cleanup=<completed|incomplete>
```

An explicit failure keeps its own message: the host exited, it answered with an incompatible protocol, or a startup
record broke the protocol. `cleanup=incomplete` means the teardown could not prove the child exited, so its
registration and startup intent are kept rather than read as gone.

Before the spawn, the launcher writes `startup-intent.json` (0600) in the endpoint's daemon directory under the ensure
lock. It records the attempt nonce and generation; once known it also records the child's identity, and the supervisor
records the same nonce in its own generation directory. The next ensure reconciles a leftover intent through the
candidate's own identity. A candidate proven gone is cleared; one still running refuses `host_stalled`. One that
nobody can identify refuses `endpoint_occupied` until the intent is 284 s old, after which it no longer blocks the
endpoint. Nothing is ever signalled on intent evidence.

#### Successor startup and endpoint adoption (senpi#4602)

A generation handoff's successor runs the same phases and the same 180 s ceiling, with one difference in order:
`presenter_resolved` comes right after `observer_ready`, and `public_published` after it. While the presenter
exchange runs, the successor has only its own `<public>.next-<gen>` listener; the predecessor keeps serving its
unchanged public socket, key and pointer. The launcher grants publication only after a validated presenter result:
it writes `adoption-grant.json` (0600, naming the attempt) into the successor's generation directory and wakes the
supervisor on the startup pipe. Only then does the successor publish its key and rename its entry over the public
path. A presenter exchange that misses its 30 s phase ends the successor before it touched the predecessor's endpoint,
and the handoff is refused. A presenter channel that closes without `enrolled` (for example a refused enrollment for
a foreign or stale predecessor) passes the phase as not enrolled, and the handoff proceeds as it always did. When the
predecessor is a running host performing an idle handover, it asks its launch owner for the successor's fresh
presenter permit only at that phase, so the 30 s permit covers the exchange and not the successor's boot. The
presenter channel itself waits up to 180 s for its first frame; the existing 30 s exchange window starts with that
frame. A successor started by a command that is not the engine's own keeps the old order and waits for its public
answer under the 180 s legacy phase (formerly a fixed 30 s).

Every rename or remove of the public socket entry - the successor's adoption, a generation's close-time shield and
its final unlink - runs under one short cross-process fence per canonical endpoint (an exclusive SQLite lock next to
the ensure lock, released by the kernel when its holder dies) and re-reads the endpoint's owner token
(`<ensure-lock>.owner.json`: endpoint, generation, instance, pid and a per-claim nonce) inside it. A start claims the
token with its bind; an adoption requires that the grant still stands, that the token still names the predecessor
and that the entry is still the one the handoff was decided against, then renames and writes its own token before the
fence is released. A predecessor whose teardown was decided before the adoption therefore re-reads the successor's
token and leaves its entry alone. A host advertises this with the `endpoint_owner_fence` capability. A successor
claims the token guard only against a predecessor that advertises it; the first handoff away from an older host runs
as before and keeps that host's race with a late rename.

When a successor attempt fails, its launcher revokes the grant and reads the owner token inside the same fence. An
adoption that started within its window but committed after the deadline is a completed handoff: the successor is
registered and the predecessor drains, nothing is rolled back. One that had not committed can no longer commit.
The child announces `launch_id: "internal"` and `socket_auth`; neither side sends the key. After authentication,
HKDF-SHA256 derives separate `senpi-rpc-internal c2s` and `senpi-rpc-internal s2c` keys using the two raw nonces as salt.
Each record has a four-byte big-endian ciphertext length (17..65552), AES-256-GCM ciphertext and a 16-byte tag.
The nonce is four zero bytes followed by a big-endian 64-bit direction counter, starting at zero; AAD is the
UTF-8 direction label (`c2s` or `s2c`) followed by that eight-byte counter. A direction closes at 2^32 records.
Plaintext (1..65536 bytes per record) is released only after tag verification. Tampering, replay, reordering,
invalid lengths and incomplete records at EOF close the hop. Complete-record truncation is ordinary transport loss.
JSONL lines span records with backpressure and retain the existing 16 Mi-character ceiling. Windows retains the
secret-file/raw-handshake internal hop.

#### Supervisor unit (Linux)

A supervisor is detached into its own session, but on Linux a process stays in the cgroup of whoever started it. A
supervisor started by `host ensure` or `host handoff` from a transient unit (a terminal's per-terminal service, an ssh
session scope, a CI job) therefore used to die with that unit (senpi#7099). Where `systemctl --user is-system-running`
answers for the spawn environment (`XDG_RUNTIME_DIR` set) and `systemd-run` is on its `PATH`, each generation's
supervisor is started as `systemd-run --user --scope --unit=senpi-host-<instanceId>.scope --collect --quiet -- <supervisor
argv>`: `systemd-run` moves itself into the new scope and then execs the supervisor in place, so the spawned pid is
the supervisor and every inherited descriptor (owner pipe, presenter channel, startup pipe) is kept; the scope is
unloaded when the generation exits. No running process is moved between cgroups. Before placing a generation the
probe starts one throwaway scope (`systemd-run --user --scope --collect --quiet -- true`); a manager that answers but
refuses transient scopes (no cgroup delegation in a container, bus or polkit policy) is treated like no manager.
Without a reachable user manager that accepts scopes (containers, CI without systemd, macOS) the spawn is unchanged
and never fails for it; `host ensure`, `host handoff` and `host status` then report the unit the host's lifetime is
tied to. Only a manager that accepted the probe scope and then refuses the generation's own (a policy change in that
instant) fails that start, as any spawn failure does.

### Supersession lifecycle: `host_superseded`

Before parking for a generation handoff, the old host sends every connected client one unsolicited record:

```json
{"type":"host_superseded","instanceId":"old-host-uuid","generation":0,"successor":{"socket":"/tmp/agent/rpc.sock"}}
```

`instanceId` and `generation` identify the OLD host, matching its `get_protocol_info` response. `successor.socket`
identifies the public socket, never the supervisor's private hop. `successor` is `null` when a drain is requested
without a known replacement. This record has no request id or session handle; older clients can ignore it.

1. The announcement is queued on every connection before handoff parking changes any session.
2. Every parkable session, attached or unattached, is parked immediately. A session is **parkable** when no agent
   run, bash/tool execution, compaction, queued session work, or in-flight host request remains. Accepted opens,
   binding creation, close requests, and steer delivery must finish. This is the ordinary busy predicate with
   **durable wake-source holds excluded**: persistent monitors, scheduled continuations and goal-loop holds do not
   pin an old generation. They resume from the persisted session when reopened, as after a restart. Ordinary idle
   eviction retains its broader activity predicate, including all wake sources.
3. Active sessions keep serving their existing connections and park when their turns and requests settle. Each
   released handle emits `session_closed { sessionId, reason: "handoff_parked", sessionPath }` after releasing its
   file. This is not a session deletion: reopen `sessionPath` on the successor to obtain a new routing handle.
   That `sessionPath` is the CANONICAL path the host reserved the file under, which is not necessarily the string
   the client passed to `open_session` (a scratch dir under `/var/...` on macOS is reported as `/private/var/...`).
   A client matching the record against its own stored path must canonicalize before comparing; reopening with
   either spelling resolves to the same reservation.
   The connection closes after its last attached session parks; a connection shared with another active session
   stays open until that session also settles. A command racing parking on the old connection is either served
   or answered by that terminal record and close, never `unknown_session` for the parked handle. New opens on a
   draining supervised connection are refused with `host_stopping`; a bare (unsupervised) socket host
   still returns `host_draining`. Re-resolve the public endpoint rather than retrying the draining connection.
4. The **supervisor** starts `SENPI_RPC_HANDOFF_GRACE_MS` at supersession (default **600000 ms / 10 minutes**).
   This is a soft grace, not an abort deadline or a delay before parking. At every expiry while the generation
   still drains it appends `{ kind: "rpc-host-drain-overdue", generation, drainingForMs }` to the endpoint's
   `crashes.jsonl` (the alarm host monitors read; it is not a death) and requests another drain pass. Sessions
   still mid-turn or handling requests remain alive even beyond grace; no turn is cut short. Parkable sessions never wait for grace. A bare socket host has no supervisor grace timer,
   but follows the same announce/park/settle sequence.
5. Once every session has parked and its terminal records have drained, the generation exits even if an observer
   or client never voluntarily disconnects. Neither the normal idle timeout nor persistent-host mode can pin it.

A client may react to `host_superseded` early, but the old generation retains each file until its work settles;
`session_path_in_use` on the successor remains a retryable response until parking releases that claim. A client
that ignores the announcement still receives the terminal record and connection close.

### Multi-session host occupancy (idle eviction, retention, empty-host exit)

**The daemon does not cap sessions.** On the in-process runtime - the default for a `--listen` socket host, i.e. the
shared daemon clients attach to - there is no session limit, no admission counter, and no eviction of a live session
to make room for another: capacity is memory, and `open_session` is never refused for occupancy. `too_many_sessions`
exists only on the worker runtime described below. On that runtime every session owns a worker isolate and a complete
runtime; on the in-process runtime each session is a runtime in the host process. Memory depends on a session's
extensions and contents; neither runtime provides process-fatal OOM containment.

Closing a session on the in-process runtime also closes what that session's extension instances left open. After the
extensions' `session_shutdown` handlers run, senpi closes every server (`Bun.serve`, `Bun.listen`, `node:net` and
`node:http` servers), `node:net` client socket and timer that an extension's own code created during the session and
has not released, and writes one stderr line per extension naming what it closed. Memory those handles kept reachable
is then collectable. Senpi's own builtin extensions and inline SDK factories are not tracked, and neither is work senpi itself does on an
extension's behalf (a turn the extension started, a UI notification it showed). See
[extensions.md](extensions.md#session_shutdown) for what this means for an extension that shares one server across
sessions.

What the host does enforce are lifecycle windows, and they only ever return memory from work nobody is doing:

- **Idle eviction**: a session with no activity-refreshing command and no session-owned work for
  `SENPI_RPC_SESSION_IDLE_EVICTION_MS` (default 30 minutes) is closed through the exact `close_session` sequence
  (abort → waitForIdle → dispose, all attachments drained, path reservation released) and every attached connection
  receives that handle's `session_closed { reason: "idle_evicted" }` broadcast plus a final `close_session` response
  record. A session opened with
  `retain_on_disconnect` is PARKED by that same sweep instead: identical teardown, but the terminal record is
  `session_parked { sessionId, sessionPath }` and there is no `close_session` response, because nothing closed the session -
  the routing handle was released while the session itself stays on disk and reopens with `open_session { sessionPath }`
  (as a NEW handle). A client that does not know `session_parked` ignores it and learns the handle is gone from its next
  command's `unknown_session`. A GENERATION HANDOFF also parks attached sessions, using the distinct activity
  predicate below, and emits `session_closed { sessionId, reason: "handoff_parked", sessionPath }`, so a client can tell "the host handed
  over, reopen by path" from "this session ended". An explicit `close_session` is `reason: "client_close"`; the host
  process exiting is `reason: "host_shutdown"`, except for a retained session on a socket host, which PARKS instead
  (`session_parked { reason: "host_shutdown" }`) because the next host on the endpoint reopens it (see "Retained sessions
  across a host restart"). `reason` is optional on the wire; a client that does not know a
  value, or receives a record with no `reason` field, treats the record exactly as a reason-less one. "Session-owned
  work" is the complete activity contract, not just a streaming turn: an agent run, a running bash command,
  background terminal jobs and any other published wake source (terminal monitors, loop-guard holds), compaction,
  and barrier-held session work all defer eviction, and the idle clock restarts when that work settles. An evicted
  session resumes like any other: the next `open_session` with the same `sessionPath` reopens it.
- **Observational reads**: session state, history, model/auth inventory, loaded surfaces, and `memory_report`
  do not restart the idle clock of a **detached** session in either runtime. With any client still attached,
  these reads keep refreshing activity as before: an attached client polling `get_state` keeps the same live
  routing handle and runtime. An attached session receiving no commands can still idle-evict as before.
  Commands that change the session restart the clock even when detached. An in-flight request or prompt
  preflight prevents ordinary idle parking while the request is running; directory-removal teardown is separate.
- **Completed detached workers**: on the in-process runtime, a retained `kind: "worker"` session with zero
  attachments is parked on the next occupancy sweep once its transcript is flushed and it has no session-owned
  work, queued input, admitted unwritten delivery, pending prompt, or in-flight request - provided the disconnect
  has already stood for at least five seconds (a short grace age, so a transient reconnect keeps the live runtime
  instead of re-opening cold). It does not wait out the normal idle window. This releases its runtime and eval
  kernels, not its durable history: reopen its
  `sessionPath` to continue under a new routing handle. Active monitors and other wake sources still prevent
  early parking. Unflushed workers, worker-isolate runtimes, and interactive sessions keep their normal window.
  A zero-attachment worker without a recorded disconnect time also keeps its normal idle deadline.
- **Worker capacity** (worker runtime ONLY - a stdio host, `--listen stdio://`, an embedder, or a socket host that
  passed `--session-runtime worker` explicitly): at most 20 workers may be preparing, open, closing, or quarantined
  together, because each one is an isolate the host must keep alive. Admission beyond this bound fails explicitly
  with `open_failed: too_many_sessions`; it never evicts another session or starts an OS process as a fallback. It
  applies to new worker allocation, not attachments: a known canonical path or original opening spelling joins its
  already-bound owner without allocating a worker, even at capacity. An unknown path/alias still needs a preparation
  worker slot. In-process SDK registries using an injected runtime factory retain their existing behavior. A socket
  host on its default runtime never reaches this bound and never answers `too_many_sessions` - there is nothing to
  raise, tune, or shard.
- **Retained sessions**: a session opened with `open_session { retain_on_disconnect: true }` treats a client's
  disconnect as a DETACH, not a close. The dropped connection's attachment is released immediately (no waiting for a
  streaming turn, since nothing is being torn down), the entry stays `open` with `attachments: 0`, keeps running any
  in-flight turn to settlement, keeps its path reservation and worker slot, and stays in `list_sessions`. A later
  `open_session` with that `sessionPath` — from any connection — attaches to the same routing handle and returns
  `attached: true`. Retention never outranks an explicit teardown: a `close_session` from an attached connection still
  reaches zero attachments and closes the session, a socket host's shutdown parks it (see below), and the idle-eviction
  window above still
  parks it (or the completed-detached-worker rule above parks it sooner) — announced as
  `session_parked { sessionId, sessionPath }`, after which the file reopens by path like any
  evicted session, and the parked session counts as gone for the empty-host exit below. The park is also recorded
  for the NEXT generation, which reopens it on startup; the host that parked it never reopens it on its own, so a
  client reopening the session right after `session_parked` is the only open of that path (senpi#3485). Retention survives
  the host process too (next item). Any attach may turn retention
  on for a live session; no attach turns it off for clients that already rely on it. Omitting the flag is byte-identical
  to the previous behavior — the session is closed with its last connection — except on a delegated connection
  (`declare_delegation`), where every `open_session` is retained (see "Delegated connections"; senpi#5808). Probe `retain_on_disconnect` in
  `get_protocol_info` capabilities before relying on it: an older host silently ignores the field.
- **Retained sessions across a host restart**: every retained session with a session path is recorded in the
  endpoint's daemon directory (`handover-parked/`, one entry per session path, the same record a handoff park writes)
  as soon as its open succeeds; the entry follows the session's `set_session_context` patches and its park, and a
  transcript switch (`new_session`, `switch_session`, a fork) moves it to the new file, so only the transcript the
  session is on comes back. An explicit `close_session`, a `release_session` (the file is another runtime's then) or
  a reclaim removes every key the session was recorded under. While the session is open the entry names the process
  that holds it; a park drops that, and a host never reopens an entry whose holding process is still alive. So during
  a generation handoff the successor does not open a session its draining predecessor still has loaded, idle and
  detached ones included: it reopens the predecessor's
  park once the drain writes it (or the entry, if the predecessor dies without parking). A host
  that starts on the same socket and agent dir - after a handoff, a clean stop, a crash, or a kill in the middle of a
  turn - reopens, in the background right after it binds, every entry an earlier process wrote, replaying the
  recorded launch profile as `open_session { sessionPath, durableSessionId, retain_on_disconnect: true, ... }`: the same
  open-by-path a TUI resume runs on its session file. The session is `open` in `list_sessions` again with the same
  `durableSessionId`, `sessionPath` and transcript, announced by a `session_opened` record, and no client has to
  re-open it. A clean stop (SIGTERM, idle or empty exit) parks each retained session first: attached clients receive
  `session_parked { sessionId, sessionPath, reason: "host_shutdown" }`, never `session_closed`, and a turn running at
  the stop ends with `agent_end { aborted: true, abortSource: "system", abortCause: { kind: "host_shutdown" } }`, never
  a user abort. A killed host sends nothing. Either way the turn the stopped process was running is not resumed: the
  transcript holds what was persisted before the stop, as after a TUI crash. The routing handle (`sessionId`, `rpc-N`) is new, since handles are unique per process;
  a client holding the old one gets `session_not_found` and re-resolves the session from `list_sessions` (or
  `session_opened`) by `durableSessionId`. A relay that mirrors `list_sessions` (relayd keeps no session store of its
  own) therefore sees the session again unchanged. Not reopened: an entry whose session file is gone (a session that
  never received a message has none), an explicitly closed or reclaimed session (its entry is removed), and a session
  whose context `task_status` is terminal (`completed`, `cancelled`, `error`, `failed`, `lost`, `interrupted`). There is
  no separate resume-by-durable-id request: `open_session { sessionPath }` already resumes a known transcript, but a
  remote client learns sessions only from `list_sessions`, so a session the restarted host did not list could not be
  resumed by one at all.
- **Empty-host exit**: when the registry holds zero sessions AND no client is connected, continuously for
  `SENPI_RPC_HOST_EMPTY_EXIT_MS` (default 15 minutes), the host exits through its clean shutdown path (flush, socket
  removal), for stdio and `--listen` hosts alike. A connected client counts as occupancy even with no session open,
  so the host never drops a live socket under itself - except a connection whose every request so far was an
  observing read (`"observe": true`, the same rule as the idle-exit window above) or a `warm`, which never holds the host open,
  unless the observing connection holds the host (`"hold_host": true`, see the idle-exit window above).
  A connection that has not sent its first request yet still counts. Supervised hosts stay clean either way: a supervisor reads a
  child exit of 0 without a signal as an intentional idle stop and exits 0 with the same cleanup, not as a crash.

Values are positive integers; invalid values fall through to the defaults. These lifecycle windows run inside the host process,
so they hold even for embedders and hand-started hosts that have no supervisor.

### Interactive sessions expose a control endpoint

An interactive terminal session is its own process with its own local session; nothing joins it to a host. Another
local session reaches it only through a control endpoint, and only when an extension of that terminal registers
one with `pi.session.registerControlEndpoint({ inboxDir, drain, isSessionReferenced? })` (see
[pi.session](extensions.md#pisession)). OmO's thread component registers one at startup; a plain `senpi` with no
registrant opens no socket and writes no registry directory.

- **Platform.** Every platform. On win32 the socket path below is the endpoint's logical address: the secret is
  written beside it, and the listener binds the named pipe the host transport derives from the path and the secret
  (`\\.\pipe\senpi-rpc-<32hex>`), the address every client already connects to after reading the secret. It is
  registered and listed like a POSIX terminal. On a multi-session host the
  same call binds nothing - the host's public socket is the endpoint - see "Waking a host session (`wake`)".
- **Socket and auth.** The endpoint listens on `<agentDir>/rpc/tui/t-<16hex>.sock` (16 hex of the SHA-256 of a
  fresh instance id). When that path is longer than a Unix socket path allows, it moves to
  `/tmp/senpi-rpc-<8hex>/tui/`, which must be a private directory of this user. The directory is 0700 and the
  socket 0600. A 32-byte secret is written 0600 beside the socket, and every connection must send it first, the
  TUI-specific handshake; public RPC hosts use [challenge-response](#authentication). A wrong TUI secret
  is disconnected before a line is read. After that it is
  ordinary RPC framing: one LF-terminated JSON object per request, one response carrying its `id`.
- **Registration order.** Registering first writes the session header (so the session id is durable), reaps dead
  `tui` endpoints (`senpi host gc` scoped to `kinds: ["tui"]`), binds the socket and only then writes the
  registry directory under the ensure lock, generation record before `endpoint.json`. A listed endpoint is one
  that answers; a failed step undoes the earlier ones and answers `{ status: "failed", reason }`.
- **`endpoint_kind`.** The registry record is `{ layout: 2, registry_version: 1, endpoint_kind: "tui", socket,
  created_at }` (see "Daemon state directory (layout 2)"). `senpi host status --all` lists the terminal with
  `endpoint_kind: "tui"`, `owner` and `alive`, probing it for at most 1.5 s. `senpi host gc` reaps a dead one on
  the same evidence as a host. `ensure`, `handoff` and `stop` refuse it with `unsupported_endpoint_kind` (exit 3)
  before connecting, because a terminal endpoint is owned by its terminal process.
- **Commands.** Anything not listed below is answered `unsupported` as data. No command opens another session or
  runs a command; input goes through the terminal's admission (`steer`/`follow_up`/`prompt` below), so the
  user's draft still holds it.
  - `get_protocol_info`: `mode: "tui"`, `endpoint_kind: "tui"`, `capabilities: ["tui_control", "session_status",
    "tui_observer", "observe_reads", "entries_tail"]` (`tui_observer`: the observe-and-drive set below), `generation: 0`, the endpoint's
    `instanceId`, `commands`: every command this endpoint accepts, and `method_classes`: the same table and digest a
    host's answer carries (one builder serves both). A terminal from before the session controls below lists no
    `commands`; one from before senpi#6158 carries no `method_classes`.
  - `list_sessions`: exactly one row, `kind: "interactive"`, `surface: "tui"`, `attachments: 1`, plus the same
    `archived`, `settled`, `settledBy?`, `activity` and `model?` fields a host row carries.
  - `get_state`: the RPC session state plus `turn_epoch`, `blocking_question`, `compacting`,
    `editor_has_draft` and `state_version`.
  - `get_messages`.
  - `get_entries { since?, before?, limit?, tail?, maxBytes? }`: the host's answer, pages and tail pages included
    (see `get_entries`).
  - `set_session_name { name }`: a blank name is refused.
  - `subscribe { cursor? }`: a feed of `session_control_event { seq, kind, data }` records, where `kind` is
    `state`, `report` (an assistant message's text), `question` (pending question ids) or `completion` (the
    session went idle, with `turn_epoch`). Resubscribing with the last `seq` replays what the 256-record ring
    still holds after it.
  - `open_session { sessionPath }` (or `{ sessionId }`) naming this terminal's session attaches the connection, as
    on a host: the answer is `{ sessionId, state, attached: true }`, preceded by the replay of the in-flight
    message and pending questions, then the session's records (`message_update`, `agent_end`, ...) in the
    host's projection. A path or id of any other session is refused `terminal_single_session`; a terminal hosts
    one session. Detaching is closing the connection; neither changes the terminal.
  - `subscribe_sessions` / `unsubscribe_sessions`: the host's status stream over this one session
    (`session_status`, `effect_status`, the same `mirror` opt-in for content to a client that never attached).
    `attachments` counts the terminal plus each attached client; a subscriber, mirrored or not, is not one.
  - `steer`/`follow_up { message, whenIdle?, clientMessageId?, expected_turn_id? }` and
    `prompt { message, streamingBehavior? }`: delivered through the terminal's admission
    (`admitExternalMessage`), so input the user submitted and the runtime has not taken yet holds them, with the host's `whenIdle` choice (`queue`, the
    default, holds input on an idle session for its next turn; `start` starts one; `prompt` always starts). A
    steer that names no `expected_turn_id` steers the current turn. The answer's `disposition` is `started`,
    `queued` or `held` (with `holds`: kept as a notice until the person releases a Stop or an interrupted run); `held_draft` (the user's submitted input has not reached the runtime yet) and `turn_conflict` are refusals with a reason and an action.
    Unlike a host's input, the message lands as a remote delivery (a `session_control_delivery` entry the
    terminal renders as "remote message"), not a user message: there are no prompt templates, slash commands or
    skills. Input sent with a `clientMessageId` is answered with an admission receipt,
    `admission { clientMessageId, durableSessionId, disposition }`; a retry with the same id and the same input is
    answered from it, with `replayed: true` (and `duplicate: true`) and the original `disposition`, and delivers
    nothing; the same id with different input is refused `client_message_id_conflict`. Frames carrying
    `images`, `thinkingLevel`, `expandPromptTemplates`, `unknownCommandAsText`, `sessionTitlePrompt` or
    `enqueueOrder` are refused `unsupported_field`, naming them.
  - `get_effect_status { effectId, sessionPath? }`: the same effect ledger as a host.
  - `set_client_info { width, capabilities? }`: declares the connection's roles (`interactive_user`,
    `task_parent`), fixed once declared (`connection_role_fixed`), as on a host.
  - `attach_session { sessionId, durableSessionId, expectedHostInstance? }`: a live attachment, as on a host:
    `sessionId` is the terminal's session id from `list_sessions`, `durableSessionId` the same id, and
    `expectedHostInstance`, when sent, this endpoint's `instanceId`. Answers `{ sessionId, attached: true }` after the
    replay of the in-flight snapshot, then the session's records follow; another session is `unknown_session`, an
    identity that does not match is `session_identity_mismatch`.
  - `release_attachment { sessionId }`: drops this connection's attachment, answered `{ deferred: false }`;
    `session_not_attached` when it holds none.
  - `abort { intent?, effectId?, awaitIdle?, clearQueue?, graceMs? }`: the host's `abort` and effect receipts.
    `intent: "stop"` is refused `stop_requires_interactive_client: declare interactive_user with set_client_info first`
    until the connection declared `interactive_user`.
  - `wake { delivery_ids? }`: one drain pass, answered `{ admitted: [{ delivery_id, kind }] }`.
  - `extension_ui_response`: answers only a question this session asked and still waits on
    (`unknown_request` / `question_incomplete` / `invalid_response` otherwise). `uiRequestId` names the
    question (a pending question id from the `question` feed); without it, `id` does. The answer settles by
    the host's rule (see `question`) and the reply carries the frame's `id`, as on a host (see "Extension
    UI Responses").
  - The session controls run the pane's own paths, so validation, the footer and persistence are the ones the
    user gets doing it in that terminal:
    - `get_available_models` and `get_available_thinking_levels`: the same answers as a host's.
    - `set_model { provider, modelId }`: the `/model` switch (the footer and the pane's status line). It applies
      to that session only: the default model new sessions start on is left alone, and the `model_change` entry
      records `source: "control"`. An unknown model is refused `Model not found: <provider>/<modelId>`; a switch the
      session refuses answers its reason. Success answers the model, as on a host.
    - `set_thinking_level { level, scope? }`: the thinking-level selector. `scope: "turn"` sets this session's
      level; otherwise the level is also remembered for the model (the selector's Ctrl+S). A level the active
      model cannot run is refused `Thinking level <level> is not supported by the active model.` and nothing
      changes, for either scope. A host refuses it only for `scope: "turn"`; for the default scope a host clamps it
      to a level the model runs.
    - `interrupt { turnId? }`: Esc on a running turn - queued input returns to the editor, the turn aborts and
      settles before the answer. Answers `{ interrupted: true, turnId }` with the `turn_epoch` it stopped. An idle
      session answers `{ interrupted: false }`; a `turnId` that is not the running turn answers
      `{ interrupted: false, turnId }` with the running one and leaves it alone. The session stays open.
- **Admission.** A message from another session enters only through the registrant's drain, which calls
  `pi.session.admitExternalMessage({ delivery_id, text, deliverAs, expected_turn_id? })`. One synchronous call
  decides and acts:
  - `started`: the session was idle, and the delivery starts a turn.
  - `queued`: the session is mid-turn and `deliverAs: "followUp"`; the delivery goes on the follow-up queue once.
  - `steered`: the session is mid-turn, the steer names the current `turn_epoch`, and it goes on the steering
    queue once.
  - `turn_conflict`: the epoch is stale, or a steer names none.
  - `held_draft`: input the user submitted has not reached the runtime yet (a buffered submission, a command that
    may still submit text). Nothing is enqueued; retry on the next wake. A draft still in the composer holds
    nothing: an idle session starts the delivery's own turn and leaves the draft in place (senpi#7043).
  - `held` (with `holds`, the hold kinds): the session is idle under a hold a peer cannot release - a person's Stop,
    an interrupted run, a parent's run hold (senpi#6490). The delivery is kept as a held notice and starts once that
    hold is released; do not send it again. An `unattended` hold alone is released by the delivery (`started`).
  - `already_admitted`: this process already holds or already wrote that `delivery_id`, or the session file refused
    its entry and it is not admissible again yet (see `failed` below).

  The delivery becomes a `custom` transcript entry, `customType: "session_control_delivery"`, whose `details`
  carry the `delivery_id`. `listAdmittedDeliveries()` reports `pending` (held by the runtime) and `emitted`
  (entry written) for the life of the process. When the session file refuses a delivery's entry (`EACCES`,
  `ENOSPC`), the delivery is settled as `failed: [{ delivery_id, error }]` (listed only while non-empty): it is no
  longer held, so it blocks no later delivery and no release, and it stays with its sender. It becomes admissible
  again once the run that refused it has settled and the file's last write succeeded: the redelivery then starts or
  joins a later run, whose start drops the refused copy from the model context (so the model holds it once, as the
  file does), and it never loops against a file that still refuses writes.
- **Wake.** The drain runs on edges only, never on a timer, as the extension event `session_control_wake`. The
  edges are: the session went idle (`idle`), the user's last submission reached the runtime (`submission`),
  the editor was cleared without a submission (`draft_cleared`), a `wake` command (`command`), an entry created
  or deleted in `inboxDir` (`inbox`), an admitted delivery reaching the transcript (`emitted`), and the
  terminal continuing after a stop (`continue`). One pass runs at a time; edges that arrive during a pass merge
  into exactly one more pass. A first `inbox` pass runs right after registration.
- **Exit.** A clean exit unregisters the endpoint. A session whose file holds only its header is deleted, unless
  `isSessionReferenced()` answers `true`.

A session that lives on a multi-session host is taken over by a terminal with `release_session` (see "Handing a
session over (`release_session`)"); a terminal's own session is never handed over through its endpoint.

### Endpoint kinds: hosts and terminals

An agent directory's endpoint registry (`rpc-host-daemon/<16hex>/endpoint.json`) names two kinds of endpoint.
`rpc_host` is a multi-session host, everything in this section. `tui` is ONE interactive terminal whose extension
registered a control endpoint (see "Interactive sessions expose a control endpoint" above). Both kinds appear in
`senpi host status --all` and are reaped by `senpi host gc` on the same evidence; only a host is ever ensured,
handed off, drained or stopped (see "The `senpi host` command").

### Waking a host session (`wake`)

`wake { sessionId, delivery_ids? }` is session-scoped like `prompt`, and has the contract of a terminal endpoint's
`wake`, so a sender wakes every recipient kind with one command. An extension on a host session registers the
same way it does in a terminal - `pi.session.registerControlEndpoint({ inboxDir, drain })` - and on a host that
registration binds nothing: the host's public socket is the endpoint (`registered.socket` is its `host_socket`).
The drain then runs on the session's `session_control_wake` edges - `agent_idle`, an admitted delivery reaching
the transcript, an entry created or deleted in `inboxDir`, and this command - one pass at a time, edges that
arrive during a pass coalescing into one more. `wake` answers `{ admitted: [{ delivery_id, kind }] }`, the outcome
of the pass that covered it (`delivery_ids` appear on that pass's event). With no drain registered it still
emits `session_control_wake` into the session's extensions and answers `{ admitted: [] }`. A host without a
public socket (stdio) answers a registration `{ status: "unsupported", reason: "unsupported_mode" }`: nothing
outside its parent could reach it. `pi.session.admitExternalMessage` and `listAdmittedDeliveries` work on host
sessions exactly as in a terminal.

### Handing a session over (`release_session`)

`release_session { sessionId, reason: "takeover", interrupt?, force? }` hands a session to a runtime outside the
host - `omo daemon adopt` resumes it in a local terminal with `senpi --session <session_path>` (a path; `--resume`
is the picker). It is a teardown, not a transfer: nothing is replayed. The host appends one `custom` entry
`session_released` (`{ reason, interrupted, attachments, host_instance, released_at }`, a bookkeeping entry the
model never sees) to the transcript - writing the header first if the file was still buffered - then drains
every attachment, disposes the runtime, releases the path reservation (in-process and the cross-generation claim
in `reservations/`) and answers `{ released: true, session_path, attachments, dropped }`. From then on `list_sessions`
no longer lists it and the handle answers `unknown_session`.

- It hands over only a QUIET session: no agent run, no `prompt` still in preflight (its command already answered,
  its run not started), no queued user steer/follow-up (`queued`: still owed a turn even after the stream it was
  aimed at ended), no admitted delivery not yet written, no bash, compaction or barrier-held session work
  (the fields the handoff park judges by), and no other request for that session in flight on any connection.
  Otherwise it is refused, changing nothing: `turn_active` when a turn is running or about to start (`busy`
  contains `turn`, `prompt`, `queued` or `delivery`), `session_busy` for other work (`bash`, `compaction`, `session_work`,
  `activity`, `request`); `errorData { attachments, busy: [...] }` names every signal. The refused work runs to
  its end on the host, which keeps the path.
- With `interrupt: true` a busy session first has its queues emptied, then its run and any bash aborted (a turn
  that a pending prompt starts meanwhile is aborted too), and external admission closed; the release waits up to
  10 s for the run to go idle, for the other requests and prompts to settle - the cancelled bash is recorded then,
  before the release - and checks again. Still busy answers the same refusal with `errorData.interrupted: true`
  and `errorData.dropped`; otherwise the entry records `interrupted: true`. Every refusal after the interrupt
  (still busy, `attached` because a client attached while it waited, `unknown_session`, `session_closing`)
  reopens admission on the session the host keeps and carries `interrupted: true` and `dropped` in `errorData`,
  since the queues were already emptied.
- A refusal whose `busy` names `queued` also carries `errorData.retry_with: { interrupt: true }` and a `hint`:
  queued user input is owed a turn even when none is running (an aborted run leaves it queued), and only an
  interrupt release takes it out and hands it back in `dropped.user_messages`.
- Nothing queued vanishes silently. `dropped: { deliveries, user_messages }` (always present; empty without
  `interrupt`) lists what the interrupt took out of the queues: `deliveries` are the ids of admitted deliveries
  that were never written - they are no longer in the session's ledger and not on disk, so their sender delivers
  them again to the next owner - and `user_messages` is the user's queued steer and follow-up text in enqueue
  order. The host only hands them back; what the adopting client does with them is its own decision (for example,
  resubmit them in order as queued prompts).
- The final check, closing external admission and the close claim run in one synchronous step: a command for the
  session routed after it finds the session closing (`session_closing`); a drain pass still running admits
  nothing more (`pi.session.admitExternalMessage` throws, the delivery stays with its sender); and work started
  before it is seen by the check. Nothing is written to the file after `session_released`.
- A session whose file was never written first waits for its header write, before that final check, so the
  `session_released` entry has a file to land in. A prompt or delivery routed right after such a release is not
  answered `session_closing`: either its whole turn runs and lands before `session_released`, or it is still
  running at the final check, which then answers `turn_active`. A header write that fails answers `release_failed`
  with `errorData.detail`, and the session stays hosted. A session whose file exists awaits nothing here.
- It refuses while another client is attached (e.g. a second Desktop window): `attached` with
  `errorData { attachments }`, counting only OTHER connections' holds. The caller's own holds, including repeated
  attaches, do not require `force` (capability `release_caller_aware`): a client attached to the session it
  releases is drained with it. With `force: true` the other clients receive
  `session_closed { sessionId, reason: "released", sessionPath }`, which tells them the file is now written
  elsewhere and must NOT be reopened on this host.
- A draining host answers `host_draining`; a worker-isolate session or one with no file answers
  `release_unsupported`.
- A hand-over that fails after it began - the header or the `session_released` entry cannot be written
  (`EACCES`, `ENOSPC`, a removed directory), or the teardown throws - answers `release_failed` with
  `errorData { detail }` (the error message), plus `interrupted: true` and `dropped` after an interrupt. When
  the entry could not be written the session stays on this host as it was: admission reopened, no
  `session_released` entry on disk or in memory, and a later release can be retried. A teardown that fails
  after it claimed the session leaves it closing.

A release with `reason: "move"` (and a `moveId`) seals the session for a move to another device: its `session_released` entry records `move_id`, `target` and `session_id`, and from then on any write to the file is refused with `session_moved_away` until that same move is reclaimed. A later `takeover` release, or any ownership entry for another move, is refused too. A `move` without a `moveId`, or with one that is not a plain id (a letter or digit first, then letters, digits, `.`, `_` or `-`, at most 128 characters), is refused with `invalid_release_reason`, and a session whose own id is not a plain id is refused with `release_unsupported` (`errorData.detail: "session_id_not_plain"`) before anything is interrupted or sealed. A `session_moved_away` refusal after an `interrupt` carries `interrupted` and `dropped` like any other refusal after one. Before the seal, a `move` release runs the extensions' `session_move_export` handlers, each under the `session_shutdown` handler budget (`sessionShutdownHandlerTimeoutMs`); a handler that throws or is still running at the cap fails the release with `release_failed` (nothing sealed, admission open again). So does state a bundle could not carry: a staged file, or a resident blob of the session, whose path in the bundle would have more than 32 segments (`MAX_BUNDLE_PATH_SEGMENTS`) fails the release with `release_failed` before the seal, and `errorData.detail` names the path; the session stays live on this host. Each `move` release attempt stages into its own folder and its `session_released` entry records that attempt (`state_attempt`); `move_session export` bundles only the sealing attempt's state, so a handler still running from an earlier, failed attempt of the same move never feeds the bundle. A release refused after those handlers ran and before its seal is written removes its own attempt's folder; one refused after the seal (for example `session_closing`) keeps it, since the seal names it.

### Moving a session to another device (`move_session`)

A move hands a session to another host under the same id (capability `move_session`). The transport between the two hosts only carries the bundle folder and the receiver's answers; every decision about the session file is taken by `move_session`. Each host keeps its move folders under `<agentDir>/session-moves`.

| `op` | Side | Fields | `data` |
|---|---|---|---|
| `prepare` | receiver | `moveId`, `cwd?` (absolute), `repository?` | `{ state: "ready", expires_at }` (or `receiving` / `accepted` if it already is); the move must see its bundle within 10 minutes. With `cwd` it first checks that folder's repository and then holds the move to it; capability `move_session_prepare_repository` |
| `cancel` | receiver | `moveId` | the record: `declined` with reason `cancelled`, unless already `receiving` or `accepted` |
| `export` | sender | `sessionPath`, `moveId`, `target`, `droppedUserMessages?`, `inline?`, `inlineMaxBytes?` | `{ move_id, session_id, bundle_dir, files }`; `bundle_dir` is the folder to send, kept until `finish`. With `inline`, also `inline_files` when the bundle is small: see "Moving without a bundle folder" |
| `import` | receiver | `cwd` (absolute), `bundleDir` (absolute) or `files`, `from?`, `sessionDir?` (absolute), `open?` | `{ session_id, session_path }`; the session lands in this host's session folder for `cwd`, or in `sessionDir`. With `open`, the opened session's data sits beside it. A move lands in one file only: see below |
| `status` | receiver | `moveId`, `sessionPath?` or `landing?` | the answer for the sender: `receiving`, `accepted`, or `declined` / `failed` with `reason`; an unknown move is recorded `declined` (`no_record`) before the answer. `accepted` carries `revoked: true` once the import was revoked, with or without `sessionPath`; `revoked: true` wins over `accepted` for writability: that copy refuses every write (`session_moved_away`). A `sessionPath` whose file is not this move's import is refused with `move_mismatch`. Beside `accepted` it says where the move landed (`session_path`, `session_id`, `cwd`, or `landed_file: "gone"`): see below; capability `move_session_status_landed_path`. With the path it says whether that copy can still be written (`writable`, and `sealed_by` when it cannot); capability `move_session_status_writable`. With `landing` the answer comes from the file at the place the move would have landed, before the record: see below; capability `move_session_status_landing` |
| `finish` | sender | `sessionPath`, `moveId`, `answer` (the `status` data, `revoked` included; the fields that say where the move landed are not read) | `{ ownership: "moved" \| "writable" \| "moving" }`; an answer with `revoked: true` takes the session back (`writable`), and is refused with `move_already_moved` if the file was already marked moved |
| `revoke` | receiver | `sessionPath` (the imported copy), `moveId` | `{ ownership: "moved" }`; capability `move_session_revoke` |
| `copy` | either | `sessionPath`, `sessionId` (a plain id), `sessionDir?` (absolute) | `{ session_id, session_path }`: a new writable session with the source's history; capability `move_session_copy` |
| `identity` | either | `sessionPath` (a session file of this host) or `cwd` (a folder), exactly one | `{ repository: { rootCommits, originUrl? } }`, or `{}` when there is none; reads only, changes nothing; capability `move_session_identity` |

A move lands in one file only. The first `import` that starts receiving a move records the session file it lands as; from then on, while the move is receiving or accepted, an `import` for any other folder is refused with `move_fenced` before any session file or record is written (it may leave an empty session folder for that other folder), so two imports at once, or an import after a crash lost the `accepted` record, never land a second copy. The rename itself also runs only into that recorded file. Importing again into the same file returns it unchanged when it is there (a landed file whose `accepted` record a crash lost is accepted then). So does an import into that file that overlapped the one that landed it: it looked before the file was there and reached the record after, and it is answered the landed session, never `move_fenced`. A move lands once: if the landed copy was deleted, the copy is gone, and an `import` for the move is refused with `move_fenced` whether or not it was revoked (copy the session to a new thread to keep working). A move an older version started receiving, whose record names no landing file, accepts only the file it already landed (an `import` into that same folder); an `import` into any other folder is refused with `move_fenced`.

`status` for an accepted move also says where it landed (capability `move_session_status_landed_path`): `{ "state": "accepted", "session_path", "session_id", "cwd" }`, the session file the move's record names, with the id and the folder that file's header names. Without it only the `import`'s own answer names the landed session, so a caller that lost that answer and no longer has the bundle cannot bind a session that landed. The path is the landing target the record stores. It is read under the record's lock, by the same read of that file that settles an interrupted step, and it is answered only while the file there still records this move. If no file is there, or the file there no longer records the move, the answer is `{ "state": "accepted", "landed_file": "gone" }` with no path: the move stays accepted, and a deleted copy is gone. A record that names no landing target (an older version wrote it) answers `accepted` alone. `revoked: true` stays beside these fields. A `move_fenced` refusal of a move that is already accepted here carries the same fields in `errorData`, beside `detail`, and `revoked: true` when that copy was sealed, whichever op was refused: an `import` into another folder, or a `prepare` that names another folder than the one the move was readied for. The fields only add to the refusal: if the record or the landed file cannot be read at that moment, the refusal is sent as `move_fenced` without them. Whoever may send the `import` may ask: on a delegated connection `move_session` needs `device_admin`, and the answer names a path on this host, as the import's answer does. Nothing is opened, held or rewritten for it. `finish` reads only `state`, `reason` and `revoked` from the answer it is given, so a `status` answer can be passed on as it came.

Beside the path, the answer says whether that copy can still be written here (capability `move_session_status_writable`): `"writable": true`, or `"writable": false` with `"sealed_by": { "move_id", "state": "moving" | "moved", "target"? }`. Where a move landed is read from that move's own entries, so the path is still answered after a later move released the session from this host (it moved on to another device, or back). The copy there is then read-only, and a write to it is refused `session_moved_away`. `writable` and `sealed_by` are the verdict of the rule that refuses those writes, taken from the same read of the file, so the answer and the refusal agree. `sealed_by` names the move that sealed the copy. Its `target` is the device that move's release named. It is absent when the release named none (`release_session` takes `target` as optional), never an empty string: the destination is then not known to this host, and a caller shows it as another device, the words the `session_moved_away` refusal uses for the same case. For a later move it says `moving` until that move ends and `moved` once it finished; if that move is declined and the session is taken back here, the answer is `writable: true` again. For this move's own revoke it names this move, with `state: "moved"` and `target` the device the session went back to, beside `revoked: true`. A `move_fenced` refusal's `errorData` carries the two fields with the path. Neither is sent beside `landed_file: "gone"`. A client that binds a session from this answer checks `writable` first.

`status` can name the place a move would have landed instead of a session path (capability `move_session_status_landing`): `{ "op": "status", "moveId", "landing": { "cwd", "sessionFileName", "sessionDir"? } }`. `cwd` is the absolute folder the `import` was given, `sessionFileName` is the session file name the bundle's manifest carries, and `sessionDir` is the absolute session folder the import named, only if it named one. The host resolves the landing path from those values exactly as `import` does, and makes no folder for the question. It then reads the file there before it asks its record:

| At the landing path | `status` answers | It records |
|---|---|---|
| a file that records this move | `accepted` with where it landed (`session_path`, `session_id`, `cwd`), also when the move's record is lost; `accepted` with `revoked: true` when that copy was sealed again | nothing: no record is made for a move whose record is gone |
| a file that does not record this move (the copy an earlier move of the session left there, or another session) | what the record says, as when no file is there: that file is not this move's landing | as below |
| no file | what the record says; an unknown move is `declined` (`no_record`) | an unknown move is recorded `declined` (`no_record`) before the answer, which fences a later import of it |

This is what makes `declined` (`no_record`) safe to act on. A record can be lost while the session it described landed; a sender that reads "no record" as "never arrived" would take the session back and leave two writable copies. A `status` that names the landing answers `accepted` for such a move, so `no_record` is answered only when no landing is there. `landing` together with `sessionPath`, a `cwd` or `sessionDir` that is not absolute, and a `sessionFileName` that is not a plain session file name (a path separator, `..`, another extension) are refused `invalid_move_request` and nothing is recorded. Send this `status` only after the import answered or its deadline passed: on a move this host has no record of, the answer records the fence.

An interrupted step never leaves two writable copies, and the record always ends up agreeing with the files. Before the import renames the session into place, the record is stamped `committing`, so a crash or a failure on either side of the rename never lets the move land again: a failure after the rename never records `failed` beside the landed copy. `status` then settles the move from the file at the recorded landing target. If this move's file is there, the move is `accepted` (with `revoked: true` if it is sealed); if no file is there, the move is `failed` once the stamp is 30 seconds old, and the sender takes the session back. Until then `status` answers `receiving`: a commit holds the move's lock from its stamp to its rename, so a younger stamp may belong to a commit whose process stalled until its lock was taken over, and that commit can still land the file when it runs again. A commit checks the record again wherever a stalled process may have lost its lock: right before it writes its stamp it must find the move receiving for its target, and the stamp's own write refuses a holder that was told its lock is gone; right after the stamp it must still hold the lock and find its own stamp; and it checks that once more right before the rename that lands the file, after the wait for the session's move lock (up to 5 seconds) and the rewrite of the session file. A commit that finds the move settled by another process at any check stamps or lands nothing and is refused `move_fenced`; a copy it had already rewritten is removed and the sidecars it had moved go back. A stamp's age is not read from the wall clock alone: the stamp also carries its machine's uptime, and a reader on the same machine counts it old only when both clocks say so, so a wall clock that was stepped forward does not settle a healthy commit `failed`. A reader on another machine, a reader after a restart, and a reader of a stamp an older version wrote go by the wall clock alone, where a stamp dated after now counts as old. What the checks cannot cover: a process that stalls between its last check and the rename itself for longer than the settle bound, or during the stamp's own write while another import of the move fails, can still land a second writable copy once another process has settled the move `failed`. A same-file `import` confirms a landed file the same way and keeps its revoke mark, and `status` also restores a revoke mark a crash lost after the copy was sealed. A repeated `finish` re-queues the dropped input once and removes the bundle.

`revoke` seals the copy this host imported for a move after the sender took the session back, so two writable copies never exist. It appends `session_moved` with `reason: "revoked"` (and `target` set to the import's `from`), and from then on any write to the copy is refused with `session_moved_away`. It runs under the same move lock as `export` and `finish` (`session_held`, `session_open_here`). Only a file whose latest ownership entry is this move's `session_moved_in` is revoked; a repeat for the same move changes nothing and answers the same, and any other file (another move's import, the sender's released copy, a session that was never imported) is refused with `move_mismatch`. A client checks for the `move_session_revoke` capability before relying on it.

`copy` lets work go on from a session that is read-only here (one that moved away, or a revoked import). It writes a new session file with the source's entries under the header id `sessionId`, in `sessionDir` or in this host's session folder for the source's `cwd`. The inherited ownership entries name the old session id, so they do not apply to the copy, which is writable. The source is only read. An id that a session file in that folder already carries is refused with `move_target_occupied`; the source's own id, or an id that is not plain, is refused with `invalid_move_request`; in both cases nothing is written. A client checks for the `move_session_copy` capability before relying on it.

A copy the receiver already used is still revoked: entries written to it after the import (turns typed on this host) are kept, and the copy becomes read-only for good, so the client offers "Copy to a new thread" to keep working from it. Refusing would leave two writable copies of one session.

The receiver's record of the move stays `accepted` after a revoke; that state is final. Under the same move lock, after the copy is sealed, `revoke` adds `revoked: true` to that record, so `status` reports the revoke with or without `sessionPath`, and the engine's write guard refuses every write to the copy whatever the record says. A crash between the seal and the record write leaves the record plain `accepted` until the revoke is repeated (a repeat writes it again); meanwhile `status` with the copy's `sessionPath` still answers `revoked: true`, read from the file. With `sessionPath`, the file is read in this host's queue for that session file, so a `status` racing a `revoke` in this host answers after it; across processes it may answer just before it, and asking again settles it. A `sessionPath` whose file exists but is not this move's import (another session, a mistyped path) is refused with `move_mismatch`; a path with no file answers from the record. `finish` treats an answer that carries `revoked: true` as a take-back, never as a move: the receiver's copy is sealed, so the sender's copy must be the one writable copy. A sender still sealed for the move reclaims it exactly as for `declined` (`session_reclaimed` with `reason: "revoked"`, queued input back, under the move lock); a sender that already took the session back is left as it is, and a repeat changes nothing. A sender already marked moved by an earlier plain `accepted` answer cannot be taken back: that `finish` is refused with `move_already_moved` and changes nothing, since neither copy is writable any more; the client offers "Copy to a new thread".

To take a session back, the sender's client first sends `cancel` to the receiver, which fences a move whose import has not landed (a later `import` is refused with `move_fenced`), then sends `revoke` if the import already landed (`cancel` answers `accepted`). A `cancel` that answers `receiving` met an import in flight; the client asks `status` until it settles and revokes if it is `accepted`. A `revoke` alone does not fence a pending move: before the import it is refused with `move_mismatch`, and a late import would still land a writable copy. A client whose `revoke` did not succeed (an error, a timeout, a lost connection) repeats it before acting on any `status`: a revoke that sealed the copy but crashed before marking the record leaves the record plain `accepted`, and the repeat writes the mark again.

#### Checking the repository before the release

A session moves only into a checkout of the same repository, and until senpi#6435 only the `import` decided that. The import runs after the sender released the session, so a move that could never land still ended that session's runtime, sealed its file and took its queued input, and the user saw the refusal at the last step. Two reads let a client decide before it releases anything. A host that has them advertises `move_session_identity` and `move_session_prepare_repository`; against a host without them, keep today's order.

`identity` answers a repository identity and nothing else. It opens, claims, seals and rewrites nothing and touches no move record, so it may be sent at any time, including while the session is open. Send it CONCURRENTLY with the `get_state` a move already makes before its release: on that route it costs no extra wall time.

- `{"op":"identity","sessionPath":"…"}` on the SENDER answers what the session recorded: `{ repository: { rootCommits, originUrl? } }`, or `{}` when it recorded none. It is the value `export` writes into its bundle, read the same way (the file's last `repository-identity` entry wins). It reads only a session file of that host's own session folder (`<agentDir>/sessions/<folder>/<name>.jsonl`, decided on the resolved path, so a link out of that folder is refused without being opened) and scans at most 1 GiB of it. Every path it will not read answers one and the same refusal, `move_failed`, so the answer never says which paths exist. A larger file answers `move_failed` too, with its own detail.
- `{"op":"identity","cwd":"…"}` on the RECEIVER answers that folder's own git identity: the read `import` already makes on the folder a caller names. It never refuses for what the folder is. A folder with no repository, one that is not there, one that is not a directory and one that cannot be read all answer `{}`, so it never says which folders exist. Only a malformed request is refused with `invalid_move_request`: a relative `cwd`, both fields at once, or neither.

`prepare { moveId, cwd, repository }` then decides with the comparison the import makes. The same repository readies the move and the record keeps `cwd`; a `cwd` that does not exist on this host answers `workspace_missing`, anything else answers `move_repository_mismatch`, and neither readies anything, so the sender never releases. A `cwd` with no `repository` is compared as "the session recorded none", which is a mismatch, exactly as that bundle's import would be. `repository` without `cwd`, a relative `cwd`, or a `repository` that is not `{ rootCommits: string[], originUrl?: string }` is refused `invalid_move_request`, and nothing is readied. The folder is kept and compared as resolved text: `.` and `..` segments and doubled or trailing slashes are normalised, but a symbolic link is not followed and letter case is not folded, so a path through a link, or in another case on a disk that ignores case, is another folder to the move. An `import` that spells the folder that other way is refused `move_fenced`: it writes no session file and no record, though it may leave an empty session folder for that other spelling, and the move stays ready for the spelling it was readied with; send `prepare` and `import` the same `cwd`.

A move readied for a folder lands only there: an `import` naming another `cwd` is refused `move_fenced`: it writes no session file and no record, though it may leave an empty session folder for that other `cwd`, and the move stays ready for the folder its `prepare` checked, so the right import still lands. A second `prepare` for the same folder answers the same record with the same `expires_at`; one for another folder is refused `move_fenced`; one naming no folder answers the record and leaves the folder as it is, so an older client's `prepare` changes nothing. A move readied with no folder takes the folder of the first `import` that receives it, and `cancel` is unchanged throughout.

A `prepare` with neither `cwd` nor `repository` behaves exactly as it always did, and `import` keeps its own check: the bundle is the authority, and the folder can change between the two steps. So can the session: `identity` answers what the session recorded when it was asked, and `export` reads the session again after the release, so a session that records another repository in between passes `prepare` and is refused `move_repository_mismatch` by the import, after the release. Nothing lands, the move is declined (`repository`), and the sender takes the session back with `finish`; read `identity` as close to the release as the caller can.

`export` and `finish` run one at a time per session file, so two `finish` calls for one move settle it once and hand the queued input back once. This holds across processes too: each step takes the session's move lock, refuses a session any live process holds (`session_held`, for example another host generation on the same agent directory) and makes a concurrent open of that session wait or refuse. Inside the lock, both first refuse a session this host has open (compared after resolving `.`, `..` and symlinks).

The order is: the sender reads the session's repository (`identity`, alongside its `get_state`) and the receiver reads the target folder's; the receiver `prepare`s with both, which refuses a folder of another repository before anything is released; the sender releases the session with `release_session` reason `move` (usually with `interrupt: true`) and passes its `dropped.user_messages` to `export`; the transport carries `bundle_dir` to the receiver, which `import`s it; the sender asks `status` (on start, on reconnect, and when the session is opened) and `finish`es with the answer. `accepted` leaves the sender's copy read-only for good; `declined`, `failed`, or `accepted` with `revoked: true` makes it writable again with its queued input back. `receiving` changes nothing.

Refusals carry `errorData.detail` (the reason and what to do): `invalid_move_request` (a field does not parse), `session_open_here` (export or finish of a session this host has open), `move_not_released` (export of a file not sealed for that move), `move_fenced` (a move already answered, a bundle for a move the receiver never readied, or an `import` or `prepare` naming a folder other than the one the move was readied for), `move_bundle_invalid`, `move_repository_mismatch` (`cwd` is not a checkout of the same repository: from `prepare` before the release, and from `import`), `workspace_missing` (`cwd` does not exist on this host, from the same two steps; an `import` declines the move `repository` exactly as for a mismatch, so only the code tells the two apart), `move_target_occupied`, `move_mismatch`, `move_already_moved` (a revoked answer for a sender already marked moved), `session_moved_away`, `session_held`, and `move_failed` for anything else. `move_failed` also refuses an `export` whose sealing `release_session` staged extension state that is no longer on disk: the session is never bundled without it, and `finish` with a `declined` answer takes it back.

#### Moving without a bundle folder

Four additions let a small bundle travel inside the move's own answers, so the transport carries no folder and the receiver needs no separate `open_session`. Each has its own capability; a client checks for it before sending the field it names. An older host ignores `inline`, `sessionDir` and `open` (the folder answer, this host's own session folder, no open) and refuses an `import` without `bundleDir` with `invalid_move_request`.

| Field | On | Capability | What it does |
|---|---|---|---|
| `inline: true`, `inlineMaxBytes?` | `export` | `move_session_export_inline` | Also answers `inline_files` when the bundle fits the cap |
| `files` | `import` | `move_session_import_files` | The bundle itself, in place of `bundleDir` |
| `sessionDir` (absolute) | `import` | `move_session_import_session_dir` | The folder the session lands in, as on `copy`. A relative one, one with a file in its place or above it, and one this host cannot look at (no permission, a symlink loop) and a folder it may not write into is refused `invalid_move_request` and the move stays importable; a folder that is not there yet is created |
| `open` | `import` | `move_session_import_open` | Opens the landed session on the importing connection in the same answer |

`inline_files` is every file of the bundle folder as `{ path, sha256, base64 }`, the manifest (`manifest.json`) first: `path` is the file's `/`-separated path inside the bundle, `sha256` is the hex digest of its bytes, and `base64` is those bytes as padded base64. `export` answers it only when the files together hold at most 1,048,576 bytes (1 MiB, counted before base64) and number at most 1,024. The host states that cap in its capabilities as `move_session_inline_max_bytes:<n>`, so a client reads the number instead of assuming it. `inlineMaxBytes` asks for less, for example when the transport that will carry the import takes a smaller record; a value above the cap means the cap. A bundle over the limit is answered exactly as without `inline`: no `inline_files`, and the transport carries `bundle_dir`. The folder is written and kept until `finish` either way.

`import` takes that list unchanged as `files`. The engine writes it into a folder of its own under `<agentDir>/session-moves/incoming`, verifies it exactly as it verifies a bundle folder, and removes the folder when the import ends, however it ends. Before it writes, it also removes the `inline-` folders under `incoming` that were not modified for an hour (an import that died left them); a younger one, and a folder of any other name, is kept. Every file must match the manifest and the `sha256` it was sent with; a file that does not, or a listed file that was not sent, is refused `move_bundle_invalid` and the move is recorded `failed` (`bundle_invalid`), as for a folder. The list itself is checked before a folder is made or a byte is written, and a list refused there is refused `move_bundle_invalid` with the move's record left as it was (the manifest names the move, so a list that cannot be trusted settles no move). That covers: a path that cannot be a file inside the bundle (absolute, a drive path, an empty, `.` or `..` segment under either separator, a NUL character, a segment longer than 255 bytes, or a path longer than 1,024 bytes); a path sent twice; a path that is also the folder of another sent path; a missing manifest; a manifest whose bytes do not match its `sha256`; and a file the manifest does not list. `bundleDir` together with `files`, a list whose entries are not `{ path, sha256, base64 }` strings with padded base64, more than 1,024 files, or files over the cap is refused `invalid_move_request` and changes nothing. No path in a bundle may have more than 32 segments (`MAX_BUNDLE_PATH_SEGMENTS`), in either form of the import: a folder import whose manifest lists a deeper path is refused `move_bundle_invalid` when the manifest is read, and an inline import that sends or lists one is refused before a folder is made. The engine's own paths are at most four segments deep; extension state under `state/` is as deep as its extension makes it (senpi#6469). Two paths in a bundle that differ only in letter case, or only in Unicode form, are one name on some file systems. An import refuses such a bundle `move_bundle_invalid` before the move is touched, but only where the file system it would write on really treats them as one name: for a bundle that holds such a pair it asks that file system (it writes one empty file, looks for it under the other spellings and removes it), in an inline bundle's staging folder and in the session folder; it does not go by the platform's name. Where the names are kept apart the bundle is accepted, with one exception that holds on every host: a backslash in a bundle path is always read as a separator, so two paths that differ only by a backslash against a slash (`files/x\y` and `files/x/y`) are one name and a bundle that holds both is refused, here as on a host whose file system would keep them apart, because a bundle travels between computers (senpi#6472). The sender refuses first, so that a session is never sealed for a move a receiver would refuse: `release_session` for a move answers `release_failed` before its seal, and `export` of a session whose staged state or resident blobs would not fit answers `move_failed` and writes no bundle (`errorData.detail` names the path). An `export` refused for a session that an earlier version already sealed leaves it sealed: `finish` with a `declined` answer takes it back. `finish` reads only the format, the move id and the queued input from the bundle the sender kept, so a bundle written before the cap still finishes, either way; a kept bundle in a format this version does not know is refused, and the session and the bundle stay as they are.

`open` is `true`, or an object of `open_session` fields to open the session with (for example `{ "retain_on_disconnect": true }`); `id`, `type`, `sessionPath`, `cwd` and `admissionId` are the import's own and are refused `invalid_move_request` before anything is imported. The open is the one an `open_session` for the landed file from the same connection would be, with the import's `cwd` as its folder: the opened session works in the folder the import named, whatever folder the host was started in. Retention follows that connection's rule too: on a delegated connection the opened session is retained whatever `retain_on_disconnect` says, and on a machine-owned host an open that does not say is retained. On success the answer is the import's `{ session_id, session_path }` with the open's data at the keys `open_session` uses (`sessionId`, `state`, and the rest), delivered where an `open_session` reply is. An open that fails (`host_draining`, `session_held`, an invalid launch field) never undoes the import: the answer is still `success: true`, with `open_error: { error, errorCode?, errorData? }` and no `state`, the move is `accepted`, and the client opens the session with `open_session`. A refused import opens nothing. On a connection that negotiated compact updates an open needs an `admissionId`, which the import's `open` does not take, so there the import's open always fails `compact_admission_required`: the import stands, the failure is reported as `open_error`, and the caller opens the landed session with `open_session`. A host that is draining answers `open_error` with `host_draining` the same way. An import that finds its move already landed answers the landed session only for the folder it landed for: the same bundle imported into the same `sessionDir` with another `cwd` is refused `move_fenced` and opens nothing, since that folder's repository was never checked.

```json
{"id":"1","type":"move_session","op":"export","sessionPath":"/abs/session.jsonl","moveId":"move-1","target":"device-b","inline":true}
{"id":"1","type":"response","command":"move_session","success":true,"data":{"move_id":"move-1","session_id":"...","bundle_dir":"/abs/session-moves/outgoing/move-1","files":1,"inline_files":[{"path":"manifest.json","sha256":"...","base64":"..."},{"path":"files/session.jsonl","sha256":"...","base64":"..."}]}}
{"id":"2","type":"move_session","op":"import","cwd":"/abs/repo","from":"device-a","files":[{"path":"manifest.json","sha256":"...","base64":"..."},{"path":"files/session.jsonl","sha256":"...","base64":"..."}],"open":{"retain_on_disconnect":true}}
{"id":"2","type":"response","command":"move_session","success":true,"data":{"session_id":"...","session_path":"/abs/sessions/.../session.jsonl","sessionId":"...","state":{"sessionId":"...","sessionFile":"/abs/sessions/.../session.jsonl"}}}
```

### Continuing a session on another computer (`session_relocation`)

The agent can ask to continue its own session on another of the user's computers (tools `list_relocation_targets` and `relocate_session { target, reason }`). The engine knows no other machines, so it asks the client that offers relocation, and that client (the host app, for example the desktop) runs the move with the commands above. The engine never moves anything itself and never interrupts a turn. Both tools are registered search-exposed and kept out of the agent's tool list until a host offers relocation for the session. They are activated at the start of each run while it is offered, so a plain CLI session (or one with no offering client) never sees them.

A multi-session host advertises `session_relocation` in `get_protocol_info.capabilities`. A client offers relocation by sending `session_relocation` in its own `set_client_info.capabilities` and attaching to the session (`open_session`). Relocation belongs to ONE connection: the earliest-attached connection of the session that advertised it. Only that connection receives `host_request` and `relocation_due`; every other attached client (an older client, a second window) sees neither, and a `host_response` from any connection other than the one asked is refused `not_offering_connection` and changes nothing. When no attached connection offers it (a plain CLI, a classic single-session `--mode rpc` process, a client that does not offer it, a session running in a worker isolate, which `release_session` could not release anyway, and the stdio lane of a multi-session host, which has no connection identity to address or tell apart from other answerers; a desktop uses the socket host), both tools answer `unavailable` with reason `not_offered`, nothing is sent, and the session keeps working here. A classic single-connection handler reads its own client's capabilities.

The session asks with an outbound `host_request`, tagged with the routing `sessionId` and sent to the offering connection only:

```json
{"type":"host_request","id":"hr_5f0c...","method":"list_relocation_targets","sessionId":"rpc-1"}
{"type":"host_request","id":"hr_9a1d...","method":"relocate_session","target":"Studio","reason":"heavy build","sessionId":"rpc-1"}
```

The client answers once, under the request's `id` and the same `sessionId`, with `data` (or `error` when it failed):

```json
{"type":"host_response","id":"hr_5f0c...","sessionId":"rpc-1","data":{"targets":[{"name":"Studio","online":true,"capacity":"high","aboutToSleep":false}]}}
{"type":"host_response","id":"hr_9a1d...","sessionId":"rpc-1","data":{"accepted":true,"moveId":"mv-a1","target":"Studio"}}
{"type":"host_response","id":"hr_9a1d...","sessionId":"rpc-1","data":{"accepted":false,"reason":"target_busy","detail":"Studio is running a build"}}
```

Every `host_response` is acknowledged under its `id`: `{"type":"response","command":"host_response","success":true}`, or `success: false` with `error: "unknown_host_request"` (no request of this session waits for that id: already answered, timed out, or never sent), `"not_offering_connection"` (the request went to another connection), or `"invalid_host_response"` (no `id`). A host that accepts a move and is told `unknown_host_request` answered too late (after `no_answer`) or for a closed session: the agent was told the move did not happen, so the host must roll back what it prepared for that move (for example `move_session cancel` on the receiver).

- `list_relocation_targets` `data`: `targets`, each `{ name, online, capacity?, aboutToSleep? }`. `name` is what the agent passes as `target`; `capacity` is a free-form hint. The list passes through unchanged; one that does not parse is refused `invalid_host_answer`.
- `relocate_session` `data`: `{ accepted: true, moveId, target? }` accepts (`moveId` is the plain id the host will use for `release_session` and `move_session`; `target` is the name to show, defaulting to the asked one), and `{ accepted: false, reason?, detail? }` declines. The host should prepare the receiver before accepting, and must decline a session it cannot release (for example one in a worker isolate, which `release_session` answers `release_unsupported`).
- The session waits at most 60 seconds for an answer (refused `no_answer`); an aborted tool call is refused `cancelled`; a session closed while waiting is refused `session_closed`; a request whose connection leaves the session (`close_session`, `detach_connection`, a dropped socket) is refused `app_disconnected` at once; `error` is refused `host_error` with the error text; a request whose `host_request` cannot be written to the connection is refused `send_failed` at once, with the write's error text.
- A session without a session file answers `unavailable` with reason `not_releasable` without asking. One accepted move per run: a second `relocate_session` while one is scheduled or still being asked is refused `already_scheduled` without asking.

The agent's tool results are typed in `details`: `{ status: "listed", targets }`, `{ status: "scheduled", target, moveId }`, `{ status: "unavailable", reason, detail }`, or `{ status: "refused", reason, detail }` (the host's own `reason` and `detail` when it declined). Every outcome except `scheduled` leaves the session open and writable here.

**When the move happens.** An accepted request is scheduled; it never interrupts the run that asked for it. The tool result tells the agent the work continues on the target when this turn ends, and the run goes on to its natural end (further tool calls, its closing reply, queued follow-ups). When that run settles and goes idle (`agent_idle`, after its settle-time extension handlers) and every `prompt` call behind it has returned, the session sends one event:

```json
{"type":"relocation_due","moveId":"mv-a1","target":"Studio","reason":"heavy build","sessionId":"rpc-1"}
```

It comes after the run's `agent_end`, and only when no new run has started meanwhile; if one has, the notice follows that run's settle instead. At that point `release_session` finds the session quiet. The host then runs the ordinary move: `release_session { reason: "move", moveId, target }` from its own attached connection (which does not count as another client, so no `force` is needed; another attached client makes it refuse `attached` and the session stays writable), `move_session export`, the transport to the receiver, `import`, `status` and `finish`. The release ends this runtime: `session_released` records `move_id`, `target` and `session_id`, and the thread keeps its id, conversation and queued input (`dropped.user_messages` travels with `export`). A host that decides not to move after `relocation_due` changes nothing; the session stays writable here, and the host should tell the agent (for example with a follow-up prompt).

`relocation_due` is delivered **at most once**. The schedule lives only in the running host: no due event follows when the user aborts any run while it is scheduled (the run that asked for it, or a later run the notice was waiting behind: the user's control wins), when the session closes or its runtime is replaced, when the connection that accepted it leaves the session before the notice (`close_session`, `detach_connection`, a dropped socket) or no longer offers relocation, and when the host process ends. A host must therefore time out an accepted request that never receives `relocation_due` and roll back what it prepared (a readied receiver expires after 10 minutes on its own).

If the schedule is cleared because the offering connection left, the user aborted, or the offering capability was withdrawn or taken over by another connection, the agent receives exactly one custom session message of type `session_relocation`, with `details: { status: "dropped", reason, moveId, target }`. The reason is respectively `disconnected`, `aborted`, or `withdrawn`; `moveId` and `target` identify the accepted request. A withdrawal during a long run is reported when the run settles. After a user abort, the notice is appended at `agent_settled`, before another prompt is needed, and is saved even if the session then closes. The message says the session stays on this computer and the agent should keep working here. It is context only (`display: false`, `triggerTurn: false`): it never starts another turn or resumes a user-stopped run. This is a session message through the existing message events, not another host request or a new RPC event type. Session disposal and process exit still have no later agent notice.

### Device operations for the local relay host (`machine_op`)

A multi-session host advertising `machine_op_v1` runs the `run` step of one device operation for the local relay host (senpi#6752). The relay host keeps admission, grants, consent, the run-once ledger, audit, blob relay and deadlines; the host runs the op and answers the relay host's own `OpOutcome`. The five records below are not in `RPC_METHOD_CLASS` (the method-class digest is unchanged). They are answered only on a connection that proved the endpoint's launch key and declared no delegation; any other connection gets `errorCode: "machine_op_not_authorized"` and nothing runs. A record that does not parse gets `machine_op_malformed`.

```json
{ "id": "m1", "type": "machine_op", "op": "fs.write", "args": { "path": "notes.txt", "bytes": "aGk=" }, "op_id": "op-7", "deadline_ms": 1763251200000, "scope": { "root": "/home/me", "confined": false }, "sender": "device-a", "env_overlay": { "RELAY_STATE_DIR": "/home/me/.relay" } }
{ "id": "m1", "type": "response", "command": "machine_op", "success": true, "data": { "state": "applied", "response": { "path": "/home/me/notes.txt", "writtenBytes": 2 } } }
```

- `op`: one of `fs.read`, `fs.read_range`, `fs.write`, `fs.write_range`, `fs.edit`, `fs.glob`, `fs.grep`, `fs.stat`, `fs.list`, `shell`, `exec_command`, `write_stdin`, `wait_for_command`, `kill_terminal`, `process.info`, `mesh.message`. Any other op answers `{ state: "refused", error: { code: "malformed", message: "unknown op <op>" } }`. `args` and every response are the relay host's own shapes; bytes travel base64 (`args.bytes`, the read response's `bytes`).
- Writes carry their bytes inline: one RPC line carries up to 16 MiB of JSON, so an 8 MiB write fits. No other carrier exists; an `args` key the op does not take (`bytes_path` included) is refused `malformed`.
- `op_id`: opaque (the relay host sends `JSON.stringify([sender, batch_id, op_id])`). The answer is cached by the whole string (4,096 answers, 24 hours after settling) and bound to `sender`. A repeat from the same sender answers the first outcome and never runs again; a repeat that arrives while the op still runs joins it; a repeat from another sender is refused `errorCode: "machine_op_conflict"` and runs nothing.
- `deadline_ms` (optional): absolute epoch ms on this machine's clock; absent means the op has no deadline. The op is aborted then (`state: "cancelled"`, code `aborted`); a shell's own `timeoutMs` still answers `timed_out`.
- `scope`: the relay host's scope verdict. `confined: true` refuses any path or symlink resolving outside `root` (`policy_denied`). `confined: false` anchors relative fs paths and glob's `cwd` at `root`, and an OS refusal answers `os_permission_denied`. A `shell` or `exec_command` with no `cwd` runs in `root`.
- `sender`: the device the op runs for; it owns the terminals its `exec_command` creates. `write_stdin`, `wait_for_command`, `kill_terminal` and `process.info { handleId }` act only on their own sender's handle; another sender's answers `{ state: "failed", error: { code: "not_owner" } }`.
- `cross_owner` (optional, boolean): set by the relay host only after its own admin verdict on another sender's op or handle; it lifts the owner checks above and on `machine_op_result` / `machine_op_cancel`.
- `env_overlay` (optional, string values): laid last over a `shell` or `exec_command` child's environment, `args.env` included.

Terminals run on one host-owned terminal manager and outlive the connection that created them; handle ids are the manager's. An `exec_command` whose first wait is aborted (deadline, cancel, shutdown) kills its terminal before answering `cancelled`, so nothing is left running without a handle. A `kill_terminal` waits at most 5 s for the process to end and answers the lifecycle it reached. While an op runs or a machine terminal lives the host is not idle: no idle handover and no empty-host exit. From the idle check that starts a handover's switch, or the empty-host exit, a new `machine_op` is refused `machine_op_unavailable` (retry it) and runs nothing; a blocked handover admits machine ops again. A wait without `last_seq` answers the newest retained page; `lastSeq` and `totalBytes` are byte offsets; a `last_seq` older than the retained output (1 MiB per handle) fails `replay_gap`, and an unknown handle `unknown_handle`. The engine's mesh inbox is `<agentDir>/machine/inbox/<topic>.jsonl`.

```json
{ "id": "r1", "type": "machine_op_result", "op_id": "op-7", "sender": "device-a" }
{ "id": "r1", "type": "response", "command": "machine_op_result", "success": true, "data": { "known": true, "outcome": { "state": "applied", "response": { "path": "/home/me/notes.txt", "writtenBytes": 2 } } } }
{ "id": "o1", "type": "machine_op_owner", "handle_id": "bash_3f2a_1" }
{ "id": "o1", "type": "response", "command": "machine_op_owner", "success": true, "data": { "sender": "device-a" } }
{ "id": "h1", "type": "machine_op_health" }
{ "id": "h1", "type": "response", "command": "machine_op_health", "success": true, "data": { "ok": true, "terminals": 1, "cache": 12, "version": "2026.11.15-2" } }
```

`machine_op_cancel { op_id, sender }` aborts that op if it is running (it then answers `state: "cancelled"`, code `aborted`) and answers `{ cancelled: true }`; an op that is not running answers `{ cancelled: false }`. `machine_op_result` and `machine_op_cancel` for another sender's op are refused `machine_op_conflict` unless `cross_owner: true`. A `machine_op` whose engine state cannot be prepared (its `<agentDir>/machine` directory) is refused `machine_op_unavailable` on that line, nothing is cached, and the next op tries again. `machine_op_result` answers `{ known: false }` for an op_id it does not hold or whose op is still running (send the `machine_op` again to join it). `machine_op_owner` answers `{}` for an unknown handle. `machine_op_health` is read-only: running terminals, cached answers and the engine version.

### Host self-observation (event-loop stalls and memory pressure)

Every in-process session shares the host's event loop, so a session that blocks it freezes every other session and the
transport with it. A multi-session host therefore watches itself. Both observers run on unref'd timers, and both only
REPORT: nothing here aborts a turn, kills a session, or refuses an `open_session`.

- **Event-loop stalls**: a 200 ms timer measures how late it is actually invoked; that lateness is the time the loop
  could serve nobody. Drift above `SENPI_RPC_LOOP_LAG_WARN_MS` (default 500) writes one stderr line per 10 seconds,
  `senpi rpc host stall: event loop blocked <drift>ms (sessionId=<handle> tool=<tool>)`. Drift above
  `SENPI_RPC_LOOP_LAG_ERROR_MS` (default 5000) additionally broadcasts a `host_stalled` record
  (`{ type, driftMs, sessionId?, tool?, processCpuMs?, heapDeltaMb? }`) to every connection, like the other content-free lifecycle records.
  `processCpuMs` is the process CPU time spent during the stalled window and `heapDeltaMb` the JS heap change across it, so a
  stall explains itself: CPU close to `driftMs` means the host was busy (a large heap drop in the same window points at a
  collection), and CPU close to zero means the process did not run at all (the machine starved it, or it sat in a blocking
  wait). The stderr line carries the same two numbers as `cpu=<ms> heap=<+/-MB>`.
- On accepting an `open_session`, the host sends that connection a `queued` record
  (`{ type, for_request, position, in_flight }`) before the open enters the session loop.
  `position` is 1-based and `in_flight` counts opens already accepted across the whole host,
  since every session shares one loop. It is addressed to the opener only, carries the request
  id under `for_request` rather than the response-id field, and is dropped if that connection
  has disconnected. The bundled `RpcClient` treats it as the host's acknowledgement: an
  acknowledged open waits up to 10 minutes for its response instead of the 30 s request
  deadline (a busy host was measured answering after 57 s), and a timeout after it names the
  queue position instead of a bare deadline. A lost transport still rejects at once.
- A multi-session host sends the same `queued` record for a session-routed `prompt` the moment it receives it,
  before the prompt's preflight runs on the session's loop (`position` counts that session's requests in flight).
  The bundled `RpcClient` then waits up to 5 minutes for the prompt to be accepted instead of the 30 s request
  deadline (a compaction's longer wait is never shortened by it), and a timeout after it says the host received the prompt. A prompt the host never acknowledged still
  fails at the request deadline. A reply written for a session that already closed is dropped, with one stderr
  line naming the session.
- **Stall attribution**: each routed command is dispatched inside an `AsyncLocalStorage` scope carrying its routing
  `sessionId`, and an in-process session's tool executions open a span carrying `{ sessionId, tool }` for as long as
  the tool runs. A stall is blamed on the synchronous work that finished inside the measured window, or on the tool
  still executing when it ended; when neither exists the record and the log line carry no session, because the stall
  belongs to the host itself. Worker-runtime sessions block their own isolate rather than the host loop and
  deliberately have no tool spans.
- **Memory pressure**: a 30-second sampler reads the host's memory footprint: `phys_footprint` on macOS, `RssAnon` on
  Linux, `PrivateUsage` on Windows, and RSS only where none of those can be read (`measure: "rss"`). RSS itself never
  decides: it keeps counting memory the host already returned (after a collection or an eval kernel reset it stayed
  at gigabytes while the footprint was back near 150 MB, senpi#2261). Above `SENPI_RPC_HOST_RSS_WARN_MB` (default 4096,
  compared with the footprint despite its name) it broadcasts `host_memory_pressure`
  (`{ type, rssMb, footprintMb, measure, sessions, main, kernels }`) on every sample, writes one stderr line per five minutes naming
  both numbers, and HALVES the idle-eviction window above while the host stays above the threshold, so idle sessions
  return their memory sooner. `main` is `{ heapBytes }`, the host's main-thread heap in bytes (`bun:jsc heapSize()` when
  the runtime offers it, else `process.memoryUsage().heapUsed` - on Bun that counts the main thread only, never a kernel
  worker's heap, which is also why the loop-lag watchdog's `heapDeltaMb` is a main-thread figure). `kernels` lists every
  live kernel as `{ sessionId, language, liveBytes, measure }`, so the record names which sessions own the pressure:
  `measure: "heap"` for a JS kernel's own estimate, `"footprint"` for an interpreter process's footprint; a kernel
  without a reading yet reports `liveBytes: 0`, and one that crashed between samples is absent rather than repeated
  with a stale number. `list_sessions` rows carry the same split per session as `memory`
  (`{ main_heap_bytes, kernel_heap_bytes, kernel_count }`, zeros for a session holding no kernel), which is what
  `host status --all --include-workers --json` reports as `{ main_heap_mb, kernel_heap_mb, kernel_count }` on
  `session_rows`. It is released as soon as the footprint falls back under the threshold. Memory never refuses an open: the
  host has no resource caps, so every `open_session` is admitted whatever the host holds (#2207). Hosts released
  before #2207 had a second admission watermark; current hosts have no such admission path.
- **Per-endpoint pressure under sharding**: an agent directory may contain many independent hosts, so each endpoint
  samples and reports its own memory pressure. `host_memory_pressure` describes only the host that emitted it; pressure
  on one `p-*` or `i-*` endpoint does not gate opens on another endpoint. In `host status --all`, `rss_mb` is the
  endpoint generation's whole process tree, `host_rss_mb` is the supervisor plus host processes, and `memory_pressure`
  is whether the answering generation is above the threshold right now. Read them on the endpoint row (and the RSS
  pair on its generation rows) rather than treating an aggregate agent-directory number as an admission
  signal. The warning threshold remains observability-only: every endpoint continues to admit worker `open_session`
  requests while pressured.
- **Stall-proof dead-peer detection**: the socket dead-peer budget (30 s, `socket-event-fanout.ts`) counts only time
  the host loop actually SERVED. The loop-lag watchdog deposits each measured drift into a process-wide ledger
  (`loop-blocked-time.ts`) and the deadline re-arms for whatever blocked time landed inside its window, so a host that
  blocked for longer than the budget cannot cut every live peer on unblock (#1905). A peer that drains nothing for a
  fully-served 30 s window is still cut.
- **Teardown order**: a session's provider scope closes only after its runtime disposal settles, on the graceful path
  and at the close grace deadline alike; a config-reload watcher callback bound to a closed scope is a no-op (#1905).

- **Zero-session trim**: when a host that held sessions drops to zero (opening and closing ones included), it runs one
  full collection (`Bun.gc(true)`; `gc()` on Node only with `--expose-gc`) and, one second later, broadcasts
  `host_trimmed { footprintBeforeMb, footprintAfterMb, measure, collected, sessions, pauseMs }` - the allocator returns
  freed pages lazily, so the after reading waits for it. At most one trim per minute; idle exit is unchanged.
- **Busy-host trim**: a host whose footprint is at least 2 GB also collects when its session count drops while other
  sessions still run (`sessions` > 0 in the record), because a host whose sessions keep allocating never idles long
  enough to return freed pages (#3218). Each collection is timed (`pauseMs`), and the next busy-host trim waits at least
  60 s and at least 100 times that pause, which keeps collection near 1% of a busy host's loop in steady state. A drop that
  lands inside that wait is held and collected when it ends. The
  first busy-host trim has no earlier pause to wait on, and one collection on a multi-GB live heap can itself exceed
  the stall threshold (a `host_stalled` record and ~120 s of refused ensures, never a lost session).
  These collections are the only synchronous work the no-sync rule allows, and the record is their log.

`host_stalled`, `host_memory_pressure` and `host_trimmed` are additive records: a client that does not know them ignores them.

#### The no-sync rule

One event loop serves every session of the daemon, so a synchronous wait taken while handling one session is an
outage for all of them: a five-second `spawnSync` inside a tool is five seconds in which the host answers nobody -
not another session's `prompt`, not even `get_protocol_info`. The rule for code on the session path is therefore
absolute: **no blocking primitive, and no unbounded synchronous filesystem read.**

- Banned inside the engine: `execSync`, `execFileSync`, `spawnSync`, `Bun.spawnSync`, `Bun.sleepSync`, `Atomics.wait`.
  A ban-with-ledger audit (`test/suite/no-sync-in-session-path.test.ts`) walks the transitive call graph rooted at the
  session registry, session binding, connection handler, command router, `AgentSession`, auth storage and every tool,
  and fails on any call site the checked-in ledger does not already record with the reason it is still there.
  Synchronous filesystem calls are reported against the same ledger: a new call site, or one more call inside a
  ledgered function, fails; removing one never does. The blocking ledger is five bounded entries - the sync credential
  and settings lock backoffs (1 s budget each), the memoized `which`/`where` probe, the win32 `taskkill` path and an
  on-demand tool extraction - and the filesystem ledger records each remaining synchronous read/write with the bytes
  it moves (the JSONL transcript append is deliberately there), so "how long can this host be frozen by its own code"
  has a written answer instead of a guess.
- The same rule applies to EXTENSIONS, where nothing can enforce it: an extension that shells out synchronously,
  sleeps synchronously, or reads a large file synchronously inside an event handler freezes every other client's
  session on that host. Use the async API, and give genuinely CPU-bound work its own worker or child process.
- The rule is observable rather than enforced at runtime: the stall watchdog above is what names the offender.
  `host_stalled { driftMs, sessionId, tool, processCpuMs, heapDeltaMb }` and the matching stderr line are how a blocking call in a session or a
  tool becomes a report instead of an unexplained freeze.

### Worker ownership and flow control

This section describes the WORKER runtime (`--session-runtime worker`). An in-process host owns transport,
attachments and reservations on one event loop, so none of the cross-thread grants, credits or opening deadlines
below exist there.

The main host owns transport, attachments and canonical reservations. Workers canonicalize caller-supplied paths;
main does not synchronously traverse those paths. An open prepares a path, obtains the main host's exclusive grant,
and only then constructs its session writer and runtime. A conflicting alias attaches to an open owner or fails
explicitly before opening another writer.

SessionManager writes, switches, forks, new sessions and imports obtain the same grant before writer creation or
append-side normalization. A grant is bound to a LIVE writer, not to the worker's lifetime: every snapshot a fully
open worker publishes names the session files its live session writers still own, and the host releases each granted
path that list (and the worker's current session path) no longer names. A session replaced by `new_session`,
`switch_session`, a fork or an import therefore frees its previous file as soon as the replacement is published:
another `open_session` for that superseded path opens its own worker instead of attaching or failing, and the
previous opening spelling stops resolving to the replaced owner. Each worker may reserve at most 64 live paths
at once; a request past that budget first reconciles against the latest snapshot and only then fails with
`session_reservation_limit`, which is distinct from `session_path_in_use` (another owner holds the path). Only a
fully open entry reconciles. An entry that is opening, closing or quarantined keeps every acquired path, because a
worker stuck in a syscall can still be writing a path it can no longer report. Close or an opening deadline requests
worker termination, but does not release reservations or worker capacity until the actual exit event. A syscall that cannot yet be interrupted can therefore keep an entry
internally quarantined after the routing handle has closed. `list_sessions` continues to publish `closing`, not a
new status: existing clients must not mistake a quarantined worker for a live reattach target. Retry the path only
after that entry disappears.

Each worker accepts at most 64 ordinary pending requests totaling 16 MiB, plus four reserved interrupt/UI-response
slots totaling 1 MiB. Prepare, commit and bind share one 30-second opening budget starting with worker allocation;
they do not each reset that budget. Interrupt requests have a five-second deadline. Ordinary commands remain bounded
by count and bytes without imposing a new timeout on long-running commands. The desktop's 60-second open/readmission
window is a separate client-side wait: the host normally reports its earlier 30-second failure within that window,
but a slow transport can delay delivery. Neither timeout proves worker exit or permits concurrent reopening.
UI cancellation coalesces to one pending request, and close has its own control message. IPC output and snapshots are limited to 16 MiB per record, with one acknowledged record at a time. Over a
socket host, credit returns as soon as every destination of that session has ACCEPTED the record into its own bounded
queue (64 MiB per connection), not when the peer's kernel has drained it: a client that is merely busy cannot withhold
the producing worker's credit. On the shared stdio lane credit still waits for stdout backpressure. A five-second credit
failure closes that session visibly (`session_error` followed by `session_closed`), rather than retaining an
unbounded queue. Socket clients advertising `event_resync` use the same-connection recovery described above.
Other socket queues keep their independent overflow/disconnect behavior: a connection whose queue would
exceed 64 MiB is cut immediately, and a peer that has not accepted a single pending write within 30 seconds
(`DEFAULT_STALL_MS`) is cut as a dead peer. That budget is a transport liveness bound and is deliberately independent
of the 5-second worker control deadline — a busy client is not a dead one. A cut connection receives one `overflow`
record (`error: "overflow, resync required"` or `"stalled, resync required"`); the host then half-closes the socket
instead of destroying it, so a peer that resumes reading within a 5-second grace (`SOCKET_CUT_GRACE_MS`) still receives
that notice, and everything already written to it, before EOF. A peer that is still silent when the grace expires has
its socket destroyed. A cut peer must reconnect and resynchronize, while the session keeps running and its other
destinations keep receiving output. A failed or cut connection never withholds a session's credit and never fails the
host writer; only the stdio lane can. Because credit no longer paces a session against its slowest reader, a
session that outruns a peer fills that peer's 64 MiB queue instead of slowing down, and that peer then resynchronizes
or, without `event_resync`, is cut on overflow. The default stdio
queue is bounded at 64 MiB or 4096 records, with reserved terminal-failure records and one control-overflow notice.
Close admission counts both queued output and pending close replies (including their serialized bytes) before
releasing an attachment or waiting for teardown. An admitted first closer reserves its lifecycle and terminal reply;
admitted joiners follow those records in FIFO order. Excess closes are not admitted and do not release ownership.
One bounded `overflow` record with `command: "close_session"` and
`error: "rpc_close_output_overflow, resync required"` reports the saturation episode instead of retaining a reply
or promise for each rejected request. Over sockets, this notice goes only to the requester whose close was rejected;
each connection may have at most one outstanding notice, released when its sink consumes it. After socket-only drain,
a subsequent saturation episode on the same connection can report a new notice without reconnecting. A healthy peer is not
told to resynchronize, and a newly affected or reconnected peer receives its own notice. Stdio retains one notice per
episode. Clients receiving a notice must stop issuing closes, drain output, and resynchronize unacknowledged requests; the notice is not a successful close acknowledgment. Admission resumes as capacity becomes available.
Canonical reservations and worker capacity remain held until native exit, including after close-output overflow.

The classic handler, extension UI bridge and provider scope run inside the owning worker; only
plain data crosses IPC. Inline `main()` extension factories cannot be cloned and are rejected in shared mode: use
file-backed extensions. Classic single-session RPC remains in-process. Standalone Bun builds must embed
`src/modes/rpc/session-worker.ts` as an explicit entrypoint. Bun 1.4.2 supports `--compile --splitting`
with `--minify --keep-names`; standalone release and package binary builds use these flags to share code
between embedded entries. Splitting does not change the worker-entry define contract below.
Node bundles must ship `session-worker.js` beside the chunk containing its worker client.
Third-party/rebranded Bun wrappers must pass the published
`dist/modes/rpc/session-worker.js` as an additional compile entry, set an explicit `--root`, and set
`--define=SENPI_RPC_SESSION_WORKER_ENTRY='"./<worker-path-relative-to-root>"'`. The define is a build-time
contract, not an environment variable. Its path must match Bun's embedded entry name, not the source machine's
absolute path or the runtime working directory. The client resolves it against its compiled `import.meta.url`
before constructing the Worker: Bun 1.4.0 resolves a bare relative Worker string against the real cwd instead
of the embedded filesystem. Verify the relocated wrapper on the wrapper's supported Bun version and platform
by opening two shared sessions;
a standalone Senpi smoke does not verify a wrapper's different compile graph.

Workers isolate JavaScript event loops, not OS processes: they do not promise syscall cancellation, process-fatal OOM
containment, or containment of arbitrary native code. They are not an extension sandbox.

### D1 normative table (multi-session mode)

Hosts that support `open_session.permissionPreset: "accept-edits"` advertise
`permission_preset_accept_edits`. This preset allows project read/list/grep/edit
and asks for bash, external_directory and other tools. Clients without that
capability must use `ask`, never `workspace`, for an edit-only approval promise.
Hosts that support `permissionPreset: "auto"` advertise `permission_preset_auto`;
clients without it must not send `auto`.
Explicit permission rules and remembered approvals retain their existing precedence, except under `auto`: there settings and CLI rules can only narrow the preset (the more restrictive decision wins), and an "Always" answer (saved in `.senpi/permissions-approved.jsonl`, from this or an earlier session) still allows its pattern.
An `open_session` that attaches to a live session with another `permissionPreset` moves that session to it: the next
tool call is decided under the new preset, in either direction, and `new_session` / `switch_session` / `fork` keep it,
also when the attach lands while one of them or a `reload` (or two overlapping reloads) is still rebuilding the
session. An attach that names a preset is applied even when the session was opened or last attached with the same one.
An attach without the field keeps the current preset. An attach accepts exactly the values `open_session` accepts and
treats them the same way: an unknown preset name is applied like one given to `open_session`, so the session's next
tool call is refused with `Permission setup failed: Invalid --permission-preset "<name>". ...` until a later attach
names a valid preset.

| Command | Params | Success data | Notes |
| --- | --- | --- | --- |
| `attach_session` | `sessionId`, `durableSessionId`, `expectedHostInstance?`, `takeover?`, `holder?` | `{ sessionId, attached: true, holder?, generation?, released? }` | Live-only, identity-fenced attachment; never opens/resumes or changes the launch profile. `takeover` (headless engine only) lets the other clients go quietly. Capability `attach_session`. |
| `release_attachment` | `sessionId` | `{ deferred: boolean }` | Releases exactly one caller hold with disconnect semantics; `deferred` is true only when settlement owns the final release, and false while draining. Capability `release_attachment`. |
| `reclaim_session` | `sessionPath`, `durableSessionId`, `expectedHostInstance` | `{ reclaimed: true, sessionId }` | Atomic attach-and-claim of every caller hold; refuses other connections before aborting. Capability `reclaim_session`. |
| `get_protocol_info` | - | `{ protocolVersion: 1, serverVersion: string, capabilities: string[], mode: "classic"\|"multi", instanceId: string, generation: number, engineVersion: string, engineOrdinal: [y, m, d, n, epoch], launch_profile: { profile_id, core }, method_classes: { version, digest }, memory_pressure?: boolean }` | Answered in BOTH modes; side-effect-free; the capability probe. Multi-session hosts include `multi_session`, `session_held` (the active foreign-holder admission guard, in both runtimes), `retain_on_disconnect`, `session_kind`, `session_context`, `auto_title_per_session`, `durable_session_id`, `moved_path_guard` (senpi resolves and guards paths the OmO desktop moved with its data home), `prompt_surface` and `prompt_surface_chat` plus the negotiated launch capabilities. Those are HOST capabilities (a client never sends them) and are advertised only in multi-session mode, where the host owns the attachment refcount and the per-session launch profile. The identity fields are described under "Host identity" above; compatibility is decided from `protocolVersion`, `capabilities` and `engineOrdinal`, NEVER from `serverVersion`. |
| `open_session` | `sessionPath?`, `cwd?`, `provider?`, `modelId?`, `thinkingLevel?`, `permissionPreset?`, `retain_on_disconnect?`, `kind?`, `context?`, `auto_title?`, `durableSessionId?`, `promptSurface?`, `browserEngine?`, `retryFallback?`, `env?` (all optional; paths MUST be absolute) | `{ sessionId, state: RpcSessionState, attached?: true }` | `sessionPath` = today's `--session` semantics (open-if-exists else create persisting there, `session-manager.ts:926-940`); an omitted `cwd` means the folder the file's header names when `sessionPath` is an existing session file (capability `open_session_header_cwd`; see "The folder an open_session works in"), and the host's cwd otherwise; `provider`/`modelId` applied only on create (resume restores the session's model — mirrors `SenpiSessionRuntime.ts:198-200`); params form the immutable launch profile (D8). When the path is already held by a fully-open session, the open ATTACHES to it: same routing handle, `attached: true`, one more attachment counted; the runtime is torn down only when the last attachment closes. Idle sessions past the eviction window are closed by the host itself. `retain_on_disconnect: true` (default false) makes a dropped connection DETACH from this session instead of closing it — see "Retained sessions" below. `kind` (default `interactive`) and the opaque `context` map are described under "Session kind and context" above; both are stored frozen for the session's life and never influence auth, model or resource resolution. |
| `close_session` | `sessionId` | `{}` | Refused with `unknown_session` when the requesting connection never attached to that handle (a close releases the CALLER's attachment, and `list_sessions` publishes every handle). Otherwise aborts active work, awaits agent idle + settled persistence for up to the host grace window (default 10s), then quarantines any worker that has not exited without releasing its path reservation; its response is the LAST record tagged with that handle for the first closer — no events after (test-pinned). An admitted concurrent close joins the same teardown and receives its own successful response; output saturation rejects admission with the bounded close-overflow/resync notice described above. |
| `list_hands` | `sessionId?` | `{ hands: [{ device, label, platform, reachable }], selected? }` | Headless engine with a hand directory only (capability `hand_selection`; otherwise `hand_selection_unsupported`). See "Hand selection (headless engine)". |
| `select_hand` | `sessionId`, `device: string \| null` | `{ sessionId, selected }` | Records which hand runs the session's tools (`null` = this process). Refusals: `hand_not_listed`, `hand_unreachable` (`errorData.device`), `session_busy`, `hand_selection_unsupported`, `unknown_session`, `session_closing`. Method class `device_admin`. |
| `list_sessions` | `include_workers?` (default false) | `{ sessions: [{ sessionId, durableSessionId, sessionPath, cwd, name, status, attachments, retain_on_disconnect, kind, context?, archived, settled, settledBy?, activity, model? }] }` | Includes `opening`/`closing` entries. `archived` is the session file's archived flag (see `set_session_archived`); a thread list hides archived rows by default, and the host lists them like any other row. `settled` is the session file's Done flag (see `set_session_settled`) and is always present; `settledBy` is present only on a settled row whose flag was written with a `by`. `activity` is `running` while a turn is in flight (the same streaming state `session_status` reports as `running`) and `idle` otherwise, including an opening row. `model` is the session's current `{ provider, id }`, the same value `session_status.model` carries, and is absent while it is unknown. `retain_on_disconnect` is true when the session outlives its last attachment (an open or attach asked for it; retention is never revoked), so no client's release or disconnect can end it. Internally quarantined workers remain externally `closing` until exit. `attachments` is the session's live client attachment count; `0` on an `open` row is a retained session with no client attached. Every row carries `kind`. Rows with `kind: "worker"` are omitted unless `include_workers: true`, and `context` is published ONLY on that listing — a default listing carries no `context` at all. |
| `detach_connection` | - | `{ deferred: string[] }` | Multi-session hosts that advertise `detach_connection`. Meant as the connection's last request: the host releases every session attachment this connection holds and answers only after that, so another connection's next `list_sessions` no longer counts it. `deferred` names the sessions that still count it (see `#### detach_connection`). Closing the socket afterwards releases nothing more. `senpi host session` sends it before closing, bounded at 5 s; on a host without the capability, or after a request timed out or the connection was lost, it relies on the release at socket close. |
| `release_session` | `sessionId`, `reason: "takeover" \| "move"`, `moveId?` (required for `move`), `target?`, `interrupt?`, `force?` | `{ released: true, session_path, attachments, dropped }` | Hands the session to a runtime outside this host. See "Handing a session over (`release_session`)" below. |
| `move_session` | `op` and its fields (see "Moving a session to another device (`move_session`)") | per `op` | Drives one step of a session move between hosts. Capability `move_session`. |
| `host_response` | `id`, `data?`, `error?` | `{ type: "response", command: "host_response", success }` | Answers one `host_request` of the session (see "Continuing a session on another computer"). Capability `session_relocation`. |
| `wake` | `sessionId`, `delivery_ids?` | `{ admitted: [{ delivery_id, kind }] }` | Runs the session's registered inbox drain once. See "Waking a host session (`wake`)" below. |
| `warm` | `cwd?`, `kind?`, `context?` (as on `open_session`; `cwd` MUST be absolute) | `{ state: "warmed" \| "already_warm" \| "unsupported" }` | Loads what the next matching `open_session` needs without opening a session; never listed, never an attachment, idempotent per profile. See "Warming a host" above. Advertised as the `warm` capability by in-process hosts only. |
| every existing command | + `sessionId` (REQUIRED in multi mode) | unchanged | Routed to that session. |

### The folder an open_session works in

`open_session.cwd` is the folder the session works in: its tools run there and its project files are read from there. An open that names one works in it. An open that names none and a `sessionPath` at which a session file exists works in the folder that file's header names, as `--session` does; the host maps a folder the desktop moved to where it lives now. A header folder that is not on this host refuses the open with `open_failed` (`Stored session working directory does not exist: <folder>`): the session is never opened in the host's own folder instead. A folder that exists but is not a directory (a file, a socket), named or taken from a header, refuses the open with `session_cwd_not_directory` (`errorData { cwd }`) before any session is opened or created. Name a `cwd` to open it somewhere else. Any other open without `cwd` (no `sessionPath`, a `sessionPath` no file is at yet, or a file whose header names no folder) works in the folder the host was started in. An open that attaches to a session this host already holds leaves its folder as it is.

An open that names no folder never falls back to the host's own for a session file it could not read: a file that exists but cannot be read, and a moved-path probe whose step timed out, refuse the open (`open_failed`) instead. A `cwd` of `null` means no folder was named, as the host's launch profile already reads it.

Hosts that do this advertise `open_session_header_cwd`. A host without it opens every `sessionPath` that names no `cwd` in its own folder, so a client that reopens a session by path on such a host must pass the folder.

### Live-only attachment and scoped release

#### attach_session

`attach_session { sessionId, durableSessionId, expectedHostInstance? }` attaches the current connection
only to the live session selected by both routing and durable identity. A vanished or non-open target
returns `unknown_session`; a recycled routing id or mismatching host instance returns
`session_identity_mismatch`. A draining or shutting-down host refuses before admission with
`session_busy_lifecycle` and `errorData: { reason: "host_draining" }`; a caller without a connection
receives `session_not_attached` with `errorData: { reason: "no_connection" }`. It never creates or resumes a runtime, and never applies a permission preset,
prompt surface, or browser engine. Each success adds one attachment, connects the event stream, and publishes
`session_status` with `lastChange.cause: "attach"`. Intentional profile-changing attaches through
`open_session { sessionPath, permissionPreset, ... }` retain their existing behavior. Behind
`SENPI_ENGINE_SOCKET_COMPACT_UPDATES`, `admissionId` and `retry: true` make it a compact admission, as on
`open_session` (see "Admission retries").

**Quiet takeover (headless engine).** On a headless engine built with a takeover ledger,
`attach_session { sessionId, durableSessionId, takeover: true, holder }` takes the session over for
`holder`, the taking client's stable identity across its reconnects. The takeover is recorded durably
first; then the caller attaches, and every other connection holding the session receives one
`{ "type": "session_released", "sessionId", "reason": "taken_over" }` record and loses its holds. No
error reaches it, and the session and its running turn go on. The answer adds `holder`, its `generation`
(1 for the session's first holder, one more for each new holder) and `released` (how many connections
were let go). A takeover by the current holder records nothing new. Without `holder` the command
returns `takeover_holder_required`; any other host, the interactive terminal's endpoint included, returns
`takeover_unsupported`. A failed takeover record returns `takeover_failed` with `errorData.reason`. After the
record is written the host checks again before it attaches anyone: a draining host answers `session_busy_lifecycle`
(`reason: "host_draining"`), a caller that disconnected meanwhile gets `session_not_attached`
(`reason: "no_connection"`) and nobody is let go, and a session that closed meanwhile answers `unknown_session`.
The other clients' holds are removed in the same step as the caller's attach, so a client that disconnects or
releases, or a second takeover, while the `session_released` notices go out cannot release a hold twice.
Without `takeover`, `attach_session` behaves as above on every host.

#### release_attachment

`release_attachment { sessionId }` releases exactly one hold this connection owns on this session;
other sessions and repeated remaining holds are untouched. It uses disconnect semantics, not close:
when the final hold of a non-retained session leaves during a streaming turn, physical release waits
for settlement. The turn survives even when its original owner disconnected before a temporary
attacher released. The released hold immediately loses mutation and close authorization.
A retained session remains live at zero attachments. `close_session` remains the destructive release.
An unattached caller cannot release another connection's hold: a connection with no hold on that
session receives `session_not_attached` with `errorData: { reason: "not_attached" }`. These
attachment-command refusals carry `reason` only; only the gate refusal below adds `action`.

### Atomic recovery (`reclaim_session`)

#### reclaim_session

Send `reclaim_session { sessionPath, durableSessionId, expectedHostInstance }` when recovering a known
leftover on this host. Both identities are required; neither is inferred from the path.
Before admission, a draining or shutting-down host refuses with `session_busy_lifecycle` and
`errorData: { reason: "host_draining" }`. Otherwise, before any
await, the host resolves the live path, checks lifecycle state before both identities, refuses
other connections, records a visible attachment for the caller, then claims ALL that caller's holds
(including the newly recorded one) and marks the entry closing. It then aborts and performs normal
finalization. Zero-attachment retained sessions and leftovers with one or several caller holds are
supported in both runtimes.

Lifecycle precedes identity because an opening entry may not have published its runtime identity yet.
An entry that is both busy and identity-mismatched therefore returns `session_busy_lifecycle`.

Refusals change nothing: `session_busy_lifecycle` with `errorData.reason: "host_draining"` while
draining or shutting down, `unknown_session` for an
unheld path, `session_identity_mismatch` for missing or different identities,
`session_busy_lifecycle` for opening/closing targets, `attached_elsewhere`
with `errorData.attachments` counting other holds, and `session_not_attached` with
`errorData.reason: "no_connection"` for a caller without a connection. An attach that wins the synchronous admission race
causes `attached_elsewhere`; an attach after the claim cannot join the closing entry. Reclaim never opens
or resumes an absent path.

A disconnected owner's deferred physical hold still counts as `attached_elsewhere` until its active
turn settles, even though that owner no longer has a live connection. Settlement releases that hold.

### Attachment admission

On a socket host, session-scoped commands require the current connection to be attached unless they are
in the following effect-based read allow-list:

`get_state`, `get_messages`, `get_entries`, `get_tree`, `get_fork_messages`,
`get_last_assistant_text`, `get_media`, `get_commands`, `get_loaded_surfaces`, `get_project_trust`,
`get_project_settings`, `read_project_file`, `get_available_models`, `get_available_thinking_levels`, `get_fast_mode`, `get_session_stats`,
`get_pending_inputs`, `get_steering_messages`, `get_follow_up_messages`, `get_auth_providers`,
`get_provider_accounts`, `resolve_path`, `memory_report`, `eval_cells.list`, `eval_cells.peek`,
and `check_reload_veto`.

`record_user_activity` is gated like any other session command (lead ruling 2026-10-22, senpi#3814). Its only
known caller, the desktop app's prewarm path (omo-desktop-app `apps/server/src/provider/Layers/OmoAdapter.ts:7121`),
sends it on the session's own opener connection: the handle it uses is created from that session's
`open_session` reply (`OmoSessionHandle.ts:397-403`), so the connection is already attached.

Host discovery/control remains available: `get_protocol_info`, `list_sessions`, `subscribe_sessions`,
`unsubscribe_sessions`, `get_subscription_limits`, `warm`, `detach_connection`, `attach_session`,
`reclaim_session`, and `set_client_info` without `sessionId`. `get_effect_status` is a read with
either a routing id or a transcript path. `open_session` is exempt from this gate because its own
admission creates the caller's attachment. Attachment lifecycle commands apply their own admission
rules. `export_html` and `export_jsonl` write files and therefore require attachment.
Every other session-scoped command is gated by default, including abort, wake, release/unload,
message injection, settings/account changes, and extension UI responses/progress.
`resume_session` is gated too: it releases the session's engine holds and starts the held turns.
An `open_session { "attended": false }` is an attachment like any other open: it admits the
connection to gated commands until its own `close_session` or disconnect gives the hold back.
`senpi host session` therefore needs no extra `attach_session` after reopening a parked session.

This release **serves** each new violation and writes exactly one stderr line per violation:

```text
senpi rpc host: <command> on <session> from a connection not attached to it (refused from the next release)
```

Set `SENPI_RPC_REQUIRE_ATTACH=1` to enforce now. Enforcement returns
`errorCode: "session_not_attached"` with `errorData.reason` and
`errorData.action: "attach first with attach_session { sessionId, durableSessionId } or open_session { sessionPath }"`.
Already-refused commands are not relaxed by grace: unattached `close_session` still returns
`unknown_session`, and `set_session_context` keeps its existing `session_not_attached` refusal.
Stdio hosts and host-internal lifecycle calls have no current connection and retain existing behavior.
Worker sessions pass through this same gate before worker dispatch.

### Identities (D6)

Response-level `sessionId` = opaque **routing handle**, unique per process epoch, ephemeral (dies with the child). `state.sessionId` = **durable** JSONL session identity (what a resume cursor stores today). `list_sessions` exposes both. Clients store both, discard routing handles on child exit, and verify only durable ids against cursors.

### Fenced holder attachment

Shared hosts advertise `expected_host_instance`. After discovering a holder,
read `get_protocol_info` through its public RPC socket with the existing socket
authentication, then send `open_session { sessionPath, expectedHostInstance }`.
The field is attach-only: `owner_changed` with
`errorData { reason: "host_instance_mismatch", action: "rediscover_holder" }`
means the generation changed. A matching generation that no longer owns the
path returns `session_not_held` with the same rediscovery action. Neither
refusal constructs a runtime or claims a file. A matching held path attaches
to its existing routing handle and event stream. Without the field, open
retains its existing create/resume behavior. Clients must check the capability
before using this safety fence; older hosts may ignore unknown fields.

Session holder records publish `host_socket` (the public endpoint, not a
supervisor's private child hop) and `host_instance` alongside PID/boot/start
identity. Path reservation claims publish `host_socket` alongside their
existing `instanceId`. `session_held` exposes these optional endpoint fields
on validated live holders; a record that changed during the liveness probe
reports neither the endpoint fields nor `cwd`. They are discovery evidence,
not authorization: this fence protects against stale or other host
generations, not against a malicious same-user process. Any same-user process
can write a holder record naming a live PID and any `host_socket`, and the
fence only compares against the instance ID the endpoint reports about
itself, so a fake same-user socket could echo it back. Validate the process
identity and the endpoint's live protocol identity before attachment, and
fence every attach. A legacy record missing endpoint fields still blocks
another writer while its process is live. An unreachable endpoint or missing
fields never prove that a writer is absent; rediscover through registered
host reservations or a transcript-context candidate and validate that
candidate against the live host. Proven dead/stale process identities
continue to be reclaimed by the existing lease guard.

Attachment creates no input effect receipt. Send ordinary `prompt` with
`clientMessageId`/`clientTurnId` through the attached connection and use the
existing durable input admission/replay machinery below. This adds no second
ledger and uses no process-kernel startup credential. TUI socket sidecar auth,
Windows host handshake auth, and restricted local Unix host sockets retain
their existing contracts.

### Stable error codes

The shared host advertises the exact HOST capability `session_held` in
`get_protocol_info.capabilities`, forwarded in endpoint information, from the same
capability inventory in both `in-process` and `worker` runtimes. Probe it before
enabling in-place binding with an engine pin. Classic bindings do not run this guard
and do not advertise it, even if a client supplies the string in its flags.

Match `errorCode` when present; legacy responses expose machine-matchable
codes or code prefixes in `error`:

- `unknown_session`
- `session_not_attached: <reason>` (`set_session_context` from a connection without an attachment; `errorData { reason, action }` tells the caller to attach with `open_session { sessionPath }` first)
- `eval_cells_unavailable` (the routed session has no eval-cell RPC handler)
- `eval_cell_not_found` (unknown or foreign-session cell ID)
- `invalid_eval_cell_request` (malformed eval-cell identifier or tail budget)
- `session_closing` (an entry whose owner is tearing down). A worker that FAILS while its session is being opened is not that case and reports `open_failed` carrying the worker's own reason, so the code a client matches on always names what actually happened.
- `session_held` (`open_session`, including attach, or any session-writing RPC whose JSONL has a live holder outside this daemon family). The refusal has `errorCode: "session_held"` and `errorData { holders: [{ pid, cwd?, host_socket?, host_instance? }] }`; no boot or process-start metadata is exposed. A single dispatch guard covers prompt/steer/follow-up, continuation/custom messages/wake/compaction, model/thinking changes, bash/results, edits/name/labels, appends and tree/session changes; only explicit read/control commands bypass it. The host queries `liveSessionHolders` afresh, resolves moved paths, ignores stale/dead/reused-pid records, and excludes its own PID and worker threads. Live generation identities registered to the same endpoint are also excluded, preserving the daemon's `session_path_in_use` retry/reclaim protocol. Open is checked again after runtime holder publication, before attachment or success, with rollback on refusal. Retry after the other process exits; no restart is needed. An interactive CLI opening or resuming a held session warns with pid/cwd; lookup filesystem errors warn and continue.
  - **Mid-turn policy:** a turn admitted before the foreign holder appeared finishes and persists its results; subsequent writing RPCs are refused. Read/control requests, including abort, queue clearing, `extension_ui_response` and `extension_ui_progress`, remain available.
  - **Conservative admission:** `new_session`, `fork`, `clone`, and settings or account commands carrying this session's routing handle are also refused while its current file is held. Close the handle and open another session to leave a held file.
  - Holder records are admission evidence, not an exclusive filesystem lock. SessionManager's append API is synchronous and fresh process-identity checks are asynchronous; changing append to asynchronous admission would change the SDK contract and could discard results of already-executed tools.
- `session_path_in_use` (path held by an opening or quarantined owner; a fully-open current owner is attached instead, an owner whose teardown is already in flight is waited out on the in-process runtime, and a detached path an older-build owner has superseded is released rather than held). A path held by ANOTHER GENERATION of the daemon carries `errorData { owner: { instanceId, pid, processStartTime, sessionPath, current, strict_transfer? }, retry_after_ms: 2000 }`: that generation is still writing the file and is parking it, so the open is a retry, not a failure. An open that arrives while ANOTHER open of the same path is still taking that cross-generation claim waits for it - bounded by the close grace window - and then attaches to the session that open is building; a claim that does not settle in that window answers `errorData { reason: "claim_in_progress", retry_after_ms: 2000 }`. When the claim it waited on is refused, the next waiting open takes the claim itself and later ones wait on that, so no racing open answers a bare refusal; a path still reserved by a session past its teardown grace answers `errorData { reason: "path_still_held", retry_after_ms: 2000 }` (senpi#3485). Only a claim whose owner serves the socket (`current: true`) or still has a client attached refuses an open at all - a superseded, attachment-less claim is reclaimed instead
  - On the worker runtime, an `open_session` naming a session whose worker is quarantined (it stopped answering, so the host is ending it) answers `session_path_in_use` with `errorData { reason: "session_quarantined", action: "retry", retry_after_ms: 2000 }`. The refusal releases nothing: the quarantined entry keeps its claim and reservations, because a worker stuck in a system call can still be writing the file. When the worker's thread exits, the host first removes its session claim, waiting at most the close grace window (it carries on when the window ends even if the removal has not settled), and only then drops the entry and its reservations. Until that drop, every open naming the session gets this same refusal, including one sent just after the thread exited. Retry after `retry_after_ms`: the first open after the drop is no longer refused for the quarantine and opens the session from its file in a new worker (senpi#6452).
- `session_reservation_limit` (this worker already holds 64 live session paths; the open or session replacement was refused without disturbing the existing session)
- `missing_session_id` (session-scoped command without `sessionId` in multi mode)
- `multi_session_disabled` (`open_session` in classic mode)
- `host_stopping` (`open_session` refused by a supervised host that is shutting down or draining, including opens previously answered with `host_draining`; `errorData.instanceId` identifies the stopping generation. Re-resolve the public endpoint; a launch-owning caller may wait for this generation's exit within the stop budget and start a successor.)
- `host_draining` (`open_session` on a bare, unsupervised host, or `release_session` forwarded to a child whose generation is parking for a handoff; re-resolve the public path and open or release on the successor rather than retrying this connection)
- `turn_active` (`release_session` while a turn runs or is about to start - a prompt in preflight, an admitted delivery not yet written - without `interrupt: true`; `errorData { attachments, busy }`)
- `session_busy` (`release_session` while other session work runs - bash, compaction, barrier-held work, another request for the session - without `interrupt: true`; `errorData { attachments, busy }`)
- `attached` (`release_session` while OTHER connections are attached, without `force: true`; `errorData { attachments }` counts their holds)
- `session_identity_mismatch` (`attach_session` or `reclaim_session` selected a different durable identity or host instance)
- `session_busy_lifecycle` (`reclaim_session` found an opening or closing target, or `attach_session` / `reclaim_session` reached a draining or shutting-down host: then `errorData.reason` is `host_draining`)
- `attached_elsewhere` (`reclaim_session` found another connection's holds; `errorData.attachments` counts them)
- `takeover_unsupported` (`attach_session { takeover: true }` on a host that is not a headless engine with a takeover ledger)
- `takeover_holder_required` (`attach_session { takeover: true }` without `holder`)
- `takeover_failed` (`attach_session { takeover: true }` could not write its takeover record; `errorData.reason` says why)
- `invalid_release_reason` (`release_session` with a `reason` other than `takeover`)
- `release_unsupported` (`release_session` for a session this host cannot hand over; `errorData.detail` is `worker_runtime` - a worker isolate owns the runtime - or `no_session_file`)
- `release_failed` (`release_session` whose hand-over failed after it began - the release entry could not be written or the teardown threw; `errorData.detail` is the error message, plus `interrupted`/`dropped` after an interrupt)
- `invalid_path` (relative `sessionPath`/`cwd`)
- `session_cwd_not_directory` (`open_session` whose `cwd`, named or taken from a session file's header, exists but is not a directory; `errorData { cwd }`; nothing is opened or created)
- `open_failed: <detail>`. `open_failed: model_unavailable: <reason>` means the open named a model (`provider`/`modelId`) that could not be resolved, for example an unknown provider; the session is not opened, rather than running on the default model. The in-process runtime adds `errorData { reason: "model_unavailable", requestedModel }`; a worker runtime relays the same error text, so match on the prefix
- `invalid_session_context: <detail>` (`open_session.context` past a documented cap: more than 32 keys, a key that does not match `^[a-z][a-z0-9_]*$`, a non-string or >16 KiB value, or more than 32 KiB of JSON in total; the detail names the cap and its byte budget)
- `invalid_subscription: <reason>` (`subscribe_sessions` with a malformed `sessions`, `mirror` or flag; `errorData { reason, action }`)
- `unknown_subscription: <reason>` (`unsubscribe_sessions` naming a subscription this connection does not hold)
- `subscription_limit: <reason>` (`subscribe_sessions` on a connection that already holds the documented maximum of 64 subscriptions; `errorData { reason, action }`)
- `unsupported_transport: <reason>` (`subscribe_sessions` or `unsubscribe_sessions` on the stdio transport, which has no per-connection identity to deliver a subscription to; `errorData { reason, action }`)
- `invalid_session_context: <reason>` from `set_session_context` (a reserved host or lineage key, a bad key or value, or a patched context over 4096 bytes; `errorData { reason, action }`)
- `invalid_session_kind: <detail>` (`open_session.kind` other than `interactive` or `worker`)
- `invalid_session_env: <detail>` (`open_session.env` malformed, or naming a variable outside the host's caller-passable set; see "Caller env per session")
- `invalid_launch_profile: <detail>` (`open_session.auto_title` present but not a boolean, `open_session.promptSurface` other than `terminal`, `app` or `chat`, `open_session.browserEngine` other than `connected`, `builtin` or `none`, a malformed `open_session.retryFallback`, an empty or non-string `open_session.expectedHostInstance`, or `open_session.provider` without `modelId` or the reverse)
- `host_memory_pressure` (sent only by hosts released before #2207, which declined to CREATE a `kind: "worker"` session above `SENPI_RPC_HOST_RSS_REFUSE_MB`; `errorData { rssMb, retry_after_ms }` says when to ask again. Current hosts never refuse an open for memory; a client talking to an older generation waits and retries, it never starts a second host or a per-child process)
- `warm_failed: <detail>` (`warm` could not load its profile, for example a `cwd` that does not exist; not remembered, so a retry loads again)
- `media_not_found` (`get_media` for an unknown `toolCallId`, or a `contentIndex` that does not point at an image block)

### Tagging

Every response/event/`extension_ui_request` belonging to a session carries a top-level `sessionId` (routing handle). `get_protocol_info`/`list_sessions` responses are untagged. Classic mode: nothing tagged (byte-identical).

### Ordering guarantee (D9)

Strict FIFO per session; one total stdout order; cross-session order unspecified; fair round-robin between sessions' queued complete records; NO cross-session batch coalescing (per-session event buffers; the process-wide single-array coalescer in `event-output-buffer.ts` must not merge records of different sessions into one write). Starvation freedom is NOT promised (single pipe); a giant tool record delays others — bounded only by record completion.

### Duplicate/idempotency

If claim removal outlives an in-process close's grace deadline, a reopen waits for that
in-flight removal even after the closing entry has been deleted. This wait uses the
existing bounded pending-claim wait; a stuck removal still refuses with
`session_path_in_use` and `errorData.reason: "claim_in_progress"`.

Duplicate `open_session` while a path reservation is held by a fully-open session → ATTACH (`attached: true`, same handle), including when that session is retained with zero attachments; while held by an `opening` entry (or an internally quarantined one) → `session_path_in_use`. A `closing` entry is a session that is ENDING, not one in use: on the in-process runtime (the `--listen` socket host default) the open WAITS for that teardown - bounded by the close grace window that bounds the teardown itself - and then opens the file fresh, so reopening a path after a close never depends on how long disposal takes. The worker runtime still answers `session_path_in_use` there, because a worker's teardown ends with an OS thread exit that no host deadline bounds. A path whose owner has already replaced it with another session file is no longer held: that open allocates a new worker and resumes the file. `close_session` releases one attachment; the runtime is disposed only when the last attachment closes. A close for an entry already `closing` joins its in-flight teardown. `close_session` on unknown/already-closed → `unknown_session` error, and so is a `close_session` from a connection that never attached to that handle — it releases nothing and leaves the session untouched. The grace window is configurable by the host through `SENPI_RPC_CLOSE_GRACE_MS`. Request `id`s are client-owned; the server echoes them without dedup.

## Protocol Overview

- **Commands**: JSON objects sent to stdin, one per line
- **Responses**: JSON objects with `type: "response"` indicating command success/failure
- **Events**: Agent events streamed to stdout as JSON lines

All commands support an optional `id` field for request/response correlation. If provided, the corresponding response will include the same `id`. `bash_execution_update` events also include the `id` of their originating `bash` command.

### Framing

RPC mode uses strict JSONL semantics with LF (`\n`) as the only record delimiter.

This matters for clients:
- Split records on `\n` only
- Accept optional `\r\n` input by stripping a trailing `\r`
- Do not use generic line readers that treat Unicode separators as newlines
- Send JSON objects only; valid JSON primitives and arrays receive a parse-style error response
- Keep each encoded input record at or below 16,777,216 characters. Oversized records receive one parse-style error,
  are discarded through the next LF, and do not desynchronize following records

In particular, Node `readline` is not protocol-compliant for RPC mode because it also splits on `U+2028` and `U+2029`, which are valid inside JSON strings.

## Commands

### Prompting

#### Durable client identity

Hosts advertising `durable_client_message_id` in `get_protocol_info` accept optional
`clientMessageId` and `clientTurnId` on `prompt`, `steer`, and `follow_up`. Each is a
non-empty string of at most 256 characters. Keep these IDs unchanged when retrying
after a disconnect; the transport `id` and routing `sessionId` may change.

```json
{"id":"request-2","type":"prompt","message":"Hello","clientMessageId":"message-1","clientTurnId":"turn-1"}
```

Admission is deduplicated by the durable session header ID and `clientMessageId`.
Repeating a delivery returns the existing admission without running input handlers,
appending another user message, or starting another answer. Changing the input kind,
text, images, prompt options, or `clientTurnId` under that key fails with
`errorCode: "client_message_id_conflict"`. Recovery `enqueueOrder` is not part of
payload identity; the first admission's order stays authoritative. When present it must
be a finite number; any other value is refused before admission.

Successful responses echo both IDs in `data` and, when `clientMessageId` is present,
include `data.admission`:

```json
{"durableSessionId":"session-id","clientMessageId":"message-1","clientTurnId":"turn-1","state":"running","disposition":"started","turnId":"3"}
```

`state` is `queued`, `running`, or `completed`. Completed means the admission settled,
including handled or cleared input; it is not a claim that a provider answered
successfully. The existing `disposition` remains `started`, `queued`, or `handled`.
Preflight or storage rejection creates no accepted admission, so the same delivery
can be retried after the failure is repaired.

`turnId` is optional and identifies the engine turn at admission, using the same
identifier as `get_state.currentTurnId`. It is independent of the caller's
`clientTurnId`. The recorded value is retained when the admission completes and
when a duplicate is answered after reopening; it is not replaced by a later
running turn's ID. Older admissions and queued or handled inputs omit it.

Accepted queues and their prepared content survive reopening the transcript. They
are restored in the original enqueue order without rerunning input transforms, and a
delivery that arrives while they are being restored is queued behind them. A prompt
that was acknowledged as `started` but displaced into the steering queue by a run that
began first is stored as queued input too, so it survives a host restart. A transcript
entry that does not parse as an admission is ignored rather than blocking the session.
Running or completed admissions are never replayed, and `clear_queue` retires its
admissions before returning. Native steering priority and drain behavior are unchanged.
Durability requires a persistent session; `--no-session` retains deduplication only
for that runtime's lifetime.

The IDs appear on persisted user messages, `turn_start`, message and tool execution
events, `turn_end`, and `agent_end`. A turn consuming several identified inputs adds
`clientMessages` with their identities; top-level IDs identify the most recently
consumed input. `turn_start` identifies the first consumed input. A turn whose input is a custom
message, such as a `send_custom_message` trigger turn, carries no client IDs. The `ordered`
records in `queue_update`, `get_state`, `clear_queue`, `get_steering_messages`, and
`get_follow_up_messages` carry IDs too. The legacy string `messages`, `steering`,
and `followUp` arrays remain available.

#### Effects and receipts

Hosts advertising `effect_ledger` give every effect on a session a durable receipt
written before the effect is applied, and answer for it by id. A receipt is never
execution truth: `get_state.isStreaming` says whether a turn runs now; the receipt's
`outcome` says how an effect ended.

| Kind | Commands | Id field |
| --- | --- | --- |
| `input` | `prompt`, `steer`, `follow_up` | `clientMessageId` (the effect id is the client message id) |
| `abort` | `abort` | `effectId` |
| `set_model` | `set_model` | `effectId` |
| `set_thinking_level` | `set_thinking_level` | `effectId` |

An `effectId` is a client-minted string of 1-256 characters. Keep it unchanged when
retrying: the transport `id` and the routing `sessionId` may change (a reopened session
gets a new handle), and neither is part of the effect's identity.

States: `accepted` (recorded, not yet applied), `applied` (dispatched), `done`, and
`failed`. Input admissions map `queued -> accepted`, `running -> applied`,
`completed -> done`. `failed` and every `outcome` other than `completed` carry
`reason`, plain-words `detail` and, when the caller can act, `action`.
An effect's actor is `by: { connectionId }`. Client names are not part of the
receipt contract.

- `abort { effectId }` on a streaming session answers `applied` and becomes `done` when
  the session reaches `agent_idle`; on an idle session it answers `done` with
  `disposition: "no_active_turn"`. An abort never fails.
- `set_model { effectId }` answers `done` once `model_changed` was emitted; the
  `model_change` transcript entry carries the `effectId`. A model the registry does not
  offer fails with `outcome.reason: "unknown_model"`; missing credentials fail with
  `provider_unavailable`, while a context-budget refusal fails with `context_budget`
  and an action to compact or select a larger model. The immediate budget refusal's
  `errorCode` is `"context_budget"` (`RPC_ERROR_CONTEXT_BUDGET` in the typed API);
  `errorData.effect` carries the failed receipt.
  A switch held for compaction answers `accepted` until the next send applies it.
  Overwriting the hold, selecting a fitting model directly, or cycling onto one fails
  the older receipt with `superseded`; a held target that still cannot fit after repair
  fails with `context_budget`. Replacing the session with `new_session`, `switch_session`
  or `fork` fails a held switch with `dropped_by_replace` in its outgoing transcript.
  Unexpected selection errors record `failed` with `outcome.kind: "error"`, the error detail,
  and an action before propagating the exception. Same-id retries replay those failures rather than switching.
  `set_thinking_level { effectId }` records its own kind and stamps its id on
  `thinking_level_change`, including when the level was already in force.
- An input's `done` receipt carries `outcome.kind`: `completed`, `aborted` (with
  `abortSource` and `abortedBy: { connectionId }` when a client's `abort` or matching `interrupt` reached the
  turn), or `error`. A queued input dropped because the session was replaced
  (`new_session`, `switch_session`, `fork`) reads `failed` with
  `outcome.kind: "dropped_by_replace"`. A host stop or an unload is not a replacement:
  a queued input keeps its `accepted` receipt and is restored when the session reopens.

Replay: the same id with the same request answers the stored status with
`replayed: true` and performs nothing. The same id with a different request is refused
with `errorCode: "effect_id_conflict"` and `errorData: { effectId, reason, action }`
(inputs keep `client_message_id_conflict`). The comparison covers only the semantic
fields: `abort { awaitIdle, clearQueue, graceMs }`, `set_model { provider, modelId, scope }`,
`set_thinking_level { level, scope }`.

Reopen seal: a reopened session (or a restarted host) has no live turn and no pending
switch, so every unfinished receipt is sealed before any command reads it. A running
input becomes `done` with `outcome.kind: "interrupted_by_reopen"`; an abort becomes
`done` with `disposition: "no_active_turn"`; a `set_model` becomes `failed` with
`reason: "interrupted_by_reopen"` and `action: "send set_model again with a new
effectId"` unless its `model_change` entry is already in the transcript, in which case
it is `done`. The model a session runs is read from its transcript, never from a receipt.
An unfinished `set_thinking_level` similarly becomes `done` if its stamped
`thinking_level_change` exists, otherwise `failed` with an action to send
`set_thinking_level` again with a new effect id. An unfinished `dequeue` or `edit_queued`
becomes `failed` with `reason: "interrupted_by_reopen"` and an action to re-read
`queue_update.ordered` and retry with a new effect id.

An `abort` without `effectId` writes nothing and behaves as before.

The host never writes `uncertain`. A client whose request timed out, or whose
connection dropped before the response, treats the effect as uncertain locally and
resolves it with [get_effect_status](#get_effect_status): `found: false` means the
effect never landed and the same id can be sent again.

#### prompt

Send a user prompt to the agent. The command response is emitted after the prompt is accepted, queued, or handled. Events continue streaming asynchronously after acceptance.

```json
{"id": "req-1", "type": "prompt", "message": "Hello, world!"}
```

With a session-only thinking level:
```json
{"id": "req-1", "type": "prompt", "message": "Solve this carefully", "thinkingLevel": "high"}
```

With images:
```json
{"type": "prompt", "message": "What's in this image?", "images": [{"type": "image", "data": "base64-encoded-data", "mimeType": "image/png"}]}
```

**During streaming**: If the agent is already streaming, you must specify `streamingBehavior` to queue the message. A prompt without it is refused with `errorCode: "streaming"`:

```json
{"type": "prompt", "message": "New instruction", "streamingBehavior": "steer"}
```

- `"steer"`: Queue the message while the agent is running. It is delivered after the current assistant turn finishes executing its tool calls, before the next LLM call.
- `"followUp"`: Wait until the agent finishes. Message is delivered only when agent stops.

If the agent is streaming and no `streamingBehavior` is specified, the command returns an error.
Queued prompts cannot include `thinkingLevel`; wait for the current turn to complete before changing it.

**Steering a specific turn**: a steer or follow-up (`prompt` with `streamingBehavior`, or the `steer` and `follow_up` commands) may name the turn it is meant for with `expectedTurnId`, the id `get_state` reports as `currentTurnId`. The name is checked when the steer enters the turn's queue, in the same step, after any `input` extension handlers and pending-input bookkeeping, so the steer is queued only if that turn is still running at that moment. If no turn is running, or a different one is, it is refused with `errorCode: "turn_conflict"`, and `errorData.currentTurnId` names the running turn when there is one, so a steer meant for one turn is never queued into the next. The check holds at the moment of enqueue: an accepted steer whose turn then fails or is aborted stays queued for the next prompt, as any queued steer does. A refused steer is never queued and never held for a later turn, also while a Stop or a parent's run keeps the session paused, and a command-text steer is refused before the command runs. A refused steer's `clientMessageId` stays free: send it again under the same id, naming the turn that runs now or as a plain prompt. `expectedTurnId` must be a non-empty string of at most 256 characters, and on `prompt` it needs `streamingBehavior` (`"steer"` or `"followUp"`); anything else is refused before the session sees it. A steer that names a turn is always delivered as its own text: the bare `.` continue shortcut does not apply to it.

```json
{"type": "prompt", "message": "Use the other file", "streamingBehavior": "steer", "expectedTurnId": "3"}
```

**Prompting from a specific leaf**: `prompt` may name the session leaf it was decided at with `expectedLeafId` (the id `get_tree` or the edit commands report as the current leaf). If the session's current leaf differs when the command is admitted, it is refused with `errorCode: "stale_leaf"` (the same code and message the edit commands use), and nothing is appended or sent to the model. As with the edit commands, session-lifecycle bookkeeping entries written after the leaf (for example the `done` marker a finished turn appends) do not count as a move. The check runs at admission, so `expectedLeafId` cannot be combined with `streamingBehavior` (`steer` or `followUp`): such a prompt would run later, at a leaf the check never saw, and is refused with `errorCode: "invalid_argument"`. For the same reason it is refused with `errorCode: "invalid_argument"` from a connection without the `interactive_user` role while the user's Stop or a parent's run hold is live: such a prompt would otherwise be kept as a notice that a later turn consumes at another leaf, and nothing is stored. A session whose leaf is the root (no entries yet) has no leaf id to name, so it cannot be guarded this way; the edit commands have the same limit. Omitting the field keeps the old behaviour.

```json
{"type": "prompt", "message": "Run this again", "expectedLeafId": "a1b2c3d4"}
```

**Model not ready**: A prompt that would start a turn is refused before the model is called when the session
cannot run one. The `error` text is the same guidance the TUI shows; the `errorCode` says why:

| `errorCode` | Meaning | `errorData` |
|---|---|---|
| `provider_credentials_missing` | The selected model's provider has no credentials | `{ provider }` |
| `provider_credentials_expired` | The provider signs in with OAuth and its credentials could not be refreshed | `{ provider }` |
| `no_model_selected` | No model is selected | none |

```json
{"type": "response", "command": "prompt", "success": false, "error": "No API key found for openai. ...", "errorCode": "provider_credentials_missing", "errorData": {"provider": "openai"}}
```

**Sealed session**: A `prompt`, `steer` or `follow_up` into a session file that is read-only because it was moved away or revoked (see [Moving a session to another device](#moving-a-session-to-another-device-move_session)) is refused with `errorCode: "session_moved_away"` and `errorData.state`: `moving` while the move is still in flight, `moved` once it finished or the copy was revoked. Nothing is written; the session stays readable, and a copy under a new session id is writable.

```json
{"type": "response", "command": "prompt", "success": false, "error": "This session was moved to another device; it is read-only here. ...", "errorCode": "session_moved_away", "errorData": {"state": "moved"}}
```

**Extension commands**: If the message is an extension command (e.g., `/mycommand`), it executes immediately even during streaming. Extension commands manage their own LLM interaction via `pi.sendMessage()`.

**Input expansion**: Leading skill tokens (`/skill:name`, `$name`, or `$skill:name`), inline explicit
desktop skill tokens (`$skill:name`), and prompt templates (`/template`) are expanded before
sending/queueing. Bare inline dollar text remains literal.

**Unknown commands**: When the message's first token looks like a command (`/name`, letters, digits,
`:`, `_`, `-`; a second `/` as in `/tmp/a.txt` makes it a path) and neither extension `input`
handlers nor expansion changed the text, a name that is not a registered extension command, prompt
template, or loaded `skill:<name>` is refused before the model sees it. The failure carries
`errorCode: "unknown_command"` and `errorData: {"command", "suggestions", "reason"}`: `command` and
`suggestions` (up to three close names) omit the leading `/`, and `reason` is `"unknown"` or
`"interactive_only"` for a TUI builtin such as `/model`. A message that starts with whitespace
(`" /foo bar"`) is sent as text, as in the TUI. The failure message names the confirm step; resend the
same message with `"unknownCommandAsText": true` to send it to the model unchanged:

```json
{"type": "prompt", "message": "/etc is where the config lives", "unknownCommandAsText": true}
```

Response:
```json
{"id": "req-1", "type": "response", "command": "prompt", "success": true, "data": { "disposition": "started", "turnId": "3" }}
```

The prompt success response carries `data.disposition` (`"started"` | `"queued"` | `"handled"`), captured from the host session's own disposition callback so proxied clients can resolve optimistic-echo contracts exactly like the local path. Older hosts omit `data`; clients must then degrade to canonical-only rendering (treat the echo as rejected). The response is emitted before the user `message_start` event on the same connection, and disposition callbacks registered through the client run synchronously inside response-frame dispatch — never through the resolved promise's microtask.

`success: true` means the prompt was accepted, queued, or handled immediately. `success: false` means the prompt was rejected before acceptance. Failures after acceptance are reported through the normal event and message stream, not as a second `response` for the same request id.

For a started input, optional `data.turnId` is captured after the engine admits the
turn and before the user `message_start`. Identified inputs also retain it in
`data.admission.turnId`. This applies to `steer` and `follow_up` with
`whenIdle: "start"` too. A duplicate returns the original admission's ID, even if
another turn is now running. If an older host or admission omits the field, the
client cannot infer it from `clientTurnId` or a later `get_state` response.

The `images` field is optional. Each image uses `ImageContent` format: `{"type": "image", "data": "base64-encoded-data", "mimeType": "image/png"}`.
The `message` field for `prompt`, `steer`, and `follow_up` is limited to 1,000,000 characters;
image payloads are not counted toward this text limit.

**Tool barrier** (capability `tool_barrier`): a client that captures a pre-turn workspace checkpoint can send the prompt at once and hold the turn's workspace-changing tools until its capture is done. `toolBarrier: {"id", "deadlineMs"}` arms the barrier for the turn this prompt starts; `id` is 1-256 characters and `deadlineMs` a whole number in 1..600000.

```json
{"id": "req-1", "type": "prompt", "message": "Fix the bug", "toolBarrier": {"id": "turn-42", "deadlineMs": 35000}}
{"id": "req-1", "type": "response", "command": "prompt", "success": true, "data": {"disposition": "started", "toolBarrier": "armed"}}
```

- While the barrier is armed, a tool whose definition is not `workspaceEffect: "read"` waits after its `tool_execution_start` and before it runs, and the session emits `tool_barrier_waiting` once per waiting call. The built-in read-only tools (`read`, `grep`, `find`, `glob`, `ls`, `todo`, `web_search`, `webfetch`, `tool_search`, and the ask-user question tools) run at once; everything else, MCP and extension tools included, waits.
- `data.toolBarrier` is `"armed"` when the prompt started its own turn (the barrier is armed before the response is written) and `"ignored"` when the prompt was queued into a running turn as steering or follow-up content, or handled by a command. Nothing is armed in the ignored case.
- The barrier opens on `release_tool_barrier`, when its turn ends (the run's final `agent_end`, or a queued follow-up starting the next turn), or when `deadlineMs` passes, which emits `tool_barrier_expired`. A Stop (`abort`) ends the wait and settles the turn as aborted.
- `steer` and `follow_up` never carry a barrier, and a prompt without `toolBarrier` behaves exactly as before.
- A malformed `toolBarrier` is refused before the prompt is accepted.

#### release_tool_barrier

Open the tool barrier armed under `barrierId` (capability `tool_barrier`). It is idempotent: an id that was never armed, was already released, belonged to a turn that ended, or expired answers `released: false` and still succeeds.

```json
{"id": "req-2", "type": "release_tool_barrier", "barrierId": "turn-42"}
{"id": "req-2", "type": "response", "command": "release_tool_barrier", "success": true, "data": {"released": true}}
```

#### steer

Queue a steering message while the agent is running. It is delivered after the current assistant turn finishes executing its tool calls, before the next LLM call. Skill commands and prompt templates are expanded. Extension commands are not allowed (use `prompt` instead). Like `prompt`, queued input runs extension `input` handlers with `source: "rpc"`.

```json
{"type": "steer", "message": "Stop and do this instead"}
```

With images:
```json
{"type": "steer", "message": "Look at this instead", "images": [{"type": "image", "data": "base64-encoded-data", "mimeType": "image/png"}]}
```

The `images` field is optional. Each image uses `ImageContent` format (same as `prompt`).

Response:
```json
{"type": "response", "command": "steer", "success": true, "data": {"disposition": "queued"}}
```

`data.disposition` is `"handled"` if an input handler consumed this steer, or `"queued"` if senpi queued it (including after a handler transformed it). It does not guarantee the message stays queued. Like the prompt response, `data` is optional: older hosts omit it.

On an idle session a plain `steer` only queues; it waits for the next turn. Pass `whenIdle: "start"` (capability `steer_when_idle`) to start a turn with the message when no turn is running or starting. The session decides atomically, through the same path as `prompt` with `streamingBehavior`: an idle session answers `"started"` (the admission records `started`), and a session that is running or already starting a turn answers `"queued"`. Two `whenIdle: "start"` inputs that arrive together start one turn; the other is queued into it. If the input that claimed the start never starts its turn (it is rejected, or an extension or command handles it), the input that joined it starts the turn instead, so nothing is left queued on an idle session. The message runs through `prompt` handling (input handlers, templates, slash and unknown-command handling); `enqueueOrder` is kept when it ends up queued. `whenIdle: "queue"` (the default) keeps today's behavior; any other value is refused with an error that names the valid values.

```json
{"type": "steer", "message": "Look at the failing test", "clientMessageId": "m-7", "whenIdle": "start"}
{"type": "response", "command": "steer", "success": true, "data": {"disposition": "started", "clientMessageId": "m-7"}}
```

`steer` and `follow_up` accept `expectedTurnId` with the same check as a `prompt` steer (see [Steering a specific turn](#prompt)): an input that names a turn which is not running when it enters the queue is refused `turn_conflict` and queued nowhere.

**Thread chains**: `prompt`, `steer` and `follow_up` accept `chainCount`, a positive integer, when the input is a thread call from another session: the hop count of its chain (1 for the first call, one more per hop; a chain may come back to a session it already visited). It is checked against the user's `threads.chainCountLimit` setting before anything of the input is recorded. A `chainCount` that is not a positive integer is refused with `errorCode: "invalid_chain_count"` and `errorData: { chainCount }`. With no limit set every valid count is admitted; past the limit the input is refused with `errorCode: "chain_count_limit"` and `errorData: { count, limit }`. An admitted count is reported on the session's `input` event as `chainCount`, so a thread call that session sends next carries one more. The limit holds while a run hold keeps automatic input as a notice: an over-limit call is refused, never held. A terminal's session-control endpoint cannot carry a hop count through its text-only admission and refuses `chainCount` with `unsupported_field`.

```json
{"type": "prompt", "message": "Review the plan", "chainCount": 2}
```

```json
{"type": "steer", "message": "Use the other file", "expectedTurnId": "3"}
```

See [set_steering_mode](#set_steering_mode) for controlling how steering messages are processed.

#### follow_up

Queue a follow-up message to be processed after the agent finishes. Delivered only when agent has no more tool calls or steering messages. Skill commands and prompt templates are expanded. Extension commands are not allowed (use `prompt` instead). Extension `input` handlers run with `source: "rpc"`.

```json
{"type": "follow_up", "message": "After you're done, also do this"}
```

With images:
```json
{"type": "follow_up", "message": "Also check this image", "images": [{"type": "image", "data": "base64-encoded-data", "mimeType": "image/png"}]}
```

The `images` field is optional. Each image uses `ImageContent` format (same as `prompt`).

Response:
```json
{"type": "response", "command": "follow_up", "success": true, "data": {"disposition": "queued"}}
```

`data.disposition` has the same optional `"handled"` or `"queued"` meaning as for `steer`, applied to this follow-up. `follow_up` accepts the same `whenIdle: "start"` (answering `"started"` on an idle session, `"queued"` otherwise).

See [set_follow_up_mode](#set_follow_up_mode) for controlling how follow-up messages are processed.

#### abort

Abort the current operation. A plain `abort` is acknowledged once the abort is dispatched, before the
turn has stopped; pass `awaitIdle` to answer only once it has.

```json
{"type": "abort"}
```

Response:
```json
{"type": "response", "command": "abort", "success": true}
```

With `effectId` (capability `effect_ledger`) the abort is recorded before it is
dispatched and the response carries the receipt; see
[Effects and receipts](#effects-and-receipts):

```json
{"type": "abort", "effectId": "stop-1"}
{"type": "response", "command": "abort", "success": true, "data": {"effectId": "stop-1", "state": "applied", "effect": {"effectId": "stop-1", "kind": "abort", "state": "applied", "durableSessionId": "session-id"}}}
```

Quiesce and queue options (both optional, combinable with `effectId`):

- `awaitIdle: true` answers once the session is idle or `graceMs` (integer, 0 to 60000, default 10000) has
  passed (`graceMs` is validated but has no effect without `awaitIdle`). The answer adds `stopped` and `idle`: both `true` only when idle was reached. On grace expiry they
  are `false`, the abort keeps going, and an `effectId` receipt stays `applied` until the turn ends (`done`).
  A `graceMs` outside the range is refused with `errorCode: "invalid_argument"` and `errorData`
  `{ reason: "invalid_grace_ms", action }`.
- `clearQueue: true` drains the steering and follow-up queues atomically before the abort, emits
  `queue_update`, and gives each drained input with a `clientMessageId` a `failed` receipt with outcome
  `cleared` (with `reason`, `detail` and `action`). 2026.10.16-2 wrote this outcome as `cleared_by_abort`;
  receipts stored under that name are still read and reported unchanged, so accept both. The answer's `cleared` counts the drained inputs.
  `clear_queue` and `unload_session { clearQueue: true }` close drained input with the same `cleared` outcome; a
  session release does not (its queued deliveries stay unwritten so the sender redelivers them).
  It also empties the queue of an idle session.

```json
{"type": "abort", "effectId": "stop-2", "awaitIdle": true, "clearQueue": true}
{"type": "response", "command": "abort", "success": true, "data": {"effectId": "stop-2", "state": "done", "effect": {"effectId": "stop-2", "kind": "abort", "state": "done", "durableSessionId": "session-id"}, "stopped": true, "idle": true, "cleared": 1}}
```

The typed `RpcClient` sends these with `abort({ effectId, awaitIdle, clearQueue, graceMs })` and returns the answer; `abort()` with no options keeps the old fire-and-forget contract. `getEffectStatus(effectId, { sessionPath? })` reads a receipt.

An aborted turn's `agent_end` carries `aborted: true`, `abortSource` and, when an RPC client aborted it,
`abortedBy: { connectionId, effectId? }`; a `session_abort` caused by a client carries the same `abortedBy`. `interrupt` records its caller the same way. An abort that reached no turn is forgotten once it settles, and a new turn starts with none, so a later system or extension abort never inherits an old client's `abortedBy`.
Every attached client sees it. `abortSource` is `user` for a client or user abort, `provider` when the
provider retry watchdog gave up, and `system` for a host-side stop such as a turn deadline.


#### interrupt

Stop the running turn and only that one, with the terminal control endpoint's contract (see "Interactive sessions
expose a control endpoint"). `turnId` (the `turn_epoch` of `get_state`) is optional.

```json
{"type": "interrupt", "turnId": "3"}
```

Response: `{ interrupted: true, turnId }` once the turn has stopped; `{ interrupted: false }` when the session is
idle; `{ interrupted: false, turnId }` (the running turn) when `turnId` names another turn. Unlike `abort`, it
answers after the turn settled.

```json
{"type": "response", "command": "interrupt", "success": true, "data": {"interrupted": true, "turnId": "3"}}
```

With `"background": "stop"` the command also stops the background jobs the interrupted turn started: each bash
session that turn ran with `run_in_background`, or that auto-detached from the foreground, while that turn was running.
Sessions an earlier turn started keep running. The stop happens after the turn settled, and the answer then carries
`background: { stopped, failed }`: `stopped` names each job as `{ kind: "bash", id, description? }`, and `failed`
names a job it could not stop with its `reason` (a session on the tool child under `--tool-runtime child`, or one
still running after TERM then KILL). An idle session, or a `turnId` naming another turn, answers both lists empty.
A stopped session's exit notice does not start a turn: the model reads `Background terminal session <id> was stopped
when turn <turnId> was interrupted` at its next turn. Without the field nothing but the turn stops, as before.

```json
{"type": "interrupt", "turnId": "3", "background": "stop"}
{"type": "response", "command": "interrupt", "success": true, "data": {"interrupted": true, "turnId": "3", "background": {"stopped": [{"kind": "bash", "id": "bash_1", "description": "sleep 60"}], "failed": []}}}
```

With `"intent": "stop"` (on `abort` or `interrupt`) the command is a user Stop: the session is paused before the
turn is stopped, and automatic wakes that arrive later (terminal and monitor notices, detached eval cells, goal
continuations, task and team deliveries) are kept as notices instead of starting a turn. Only a connection that
declared the `interactive_user` capability with `set_client_info` may send it; any other connection gets
`stop_requires_interactive_client`. The capability is fixed at its first declaration on a connection. `interrupt`
with `"intent": "stop"` also stops an automatic turn that started after the one `turnId` named, and pauses an
idle session. Human input (`prompt`, `steer`, `follow_up` on an `interactive_user` connection) or `resume_session` releases the pause. The same commands from any other connection are automatic: while a Stop or a run hold is live they answer `heldAsNotice: true` and are delivered as a notice when the session resumes (an `unattended` hold alone is released by any prompt, as before); `get_state`
reports `paused`, `pausedNoticeCount` and `pausedHeldInputCount`.

```json
{"type": "set_client_info", "width": 120, "capabilities": ["interactive_user"]}
{"type": "abort", "intent": "stop", "awaitIdle": true}
```

#### hold_input

Hold human input for a paused session and deliver it at the start of the turn that resumes it. An interactive
connection may hold input. A `task_parent` connection may relay a person's run guidance into the child it paused for
that run: it sends `parentSessionId` (the session that sent `pause_for_run`), and another parent is refused with
`wrong_parent`. `origin` is optional; when present it must be `"human"`. Any other connection is refused with
`hold_input_requires_interactive_client`. Idempotent by `inputId`: the same id and `revision` answers the existing
entry, an id that was already delivered answers `alreadyDelivered: true`, and the same id with another revision is
refused with `input_id_conflict`.

```json
{"type": "hold_input", "inputId": "g-1", "revision": 1, "text": "Use the staging database"}
```

```json
{"type": "response", "command": "hold_input", "success": true, "data": {"entryId": "a1b2c3", "duplicate": false}}
```

#### withdraw_held_input

Withdraw held input before it is delivered. Interactive connections only.

```json
{"type": "withdraw_held_input", "inputId": "g-1"}
```

```json
{"type": "response", "command": "withdraw_held_input", "success": true, "data": {"withdrawn": true}}
```

#### pause_for_run

Pause this session because its parent's run was paused (a task child of a stopped session). Only a connection that
declared the `task_parent` capability may send it. The child keeps every automatic wake as a notice and holds human
input instead of starting a turn; its own `resume_session` is refused until the parent resumes the run. A later call
with a higher `parentPauseSeq` raises the hold; a different `parentSessionId` is refused with `wrong_parent`.
`childSeq` is this session's own pause sequence, which the parent passes back as `childSeqCutoff` on resume.

```json
{"type": "pause_for_run", "parentSessionId": "s-parent", "parentPauseSeq": 2, "runRef": {"kind": "dag", "id": "r1"}}
```

```json
{"type": "response", "command": "pause_for_run", "success": true, "data": {"held": true, "childSeq": 4}}
```

#### resume_for_run

Release a run-owned pause and start this child's resumed turn: held human input first, then the notices held while
paused, then a directive about the interrupted turn. `task_parent` connections only. A `parentPauseSeq` other than
the newest one this child saw (older or newer) answers `released: false, reason: "stale"`. A Stop the user gave this
child directly is released only when its sequence is at or below `childSeqCutoff`; a newer one survives
(`otherHoldLive: true`) and no turn starts. `turnId` is absent when the resumed turn did not start (a Stop landed while
it was admitted). Held input and notices are consumed only by a resumed turn that no newer Stop aborted.

```json
{"type": "resume_for_run", "parentSessionId": "s-parent", "parentPauseSeq": 2, "resumeId": "rs-1", "childSeqCutoff": 4}
```

```json
{"type": "response", "command": "resume_for_run", "success": true, "data": {"released": true, "otherHoldLive": false, "turnId": "7"}}
```

#### dequeue_message

Every queued input carries a session-unique `queuedId` (`q_<n>`) in `get_state.ordered` and `queue_update.ordered`. `dequeue_message` removes one queued input before it reaches a turn. It acts on the visible lists (`steering`, `followUp`) and the queue the agent drains, so a removed input is never delivered. With `effectId` (capability `effect_ledger`) it is a ledger effect (`kind: "dequeue"`) and a same-id retry replays.

```json
{"type": "dequeue_message", "queuedId": "q_3", "effectId": "dq-1"}
{"type": "response", "command": "dequeue_message", "success": true, "data": {"queuedId": "q_3", "status": "removed", "effectId": "dq-1", "state": "done", "effect": {"effectId": "dq-1", "kind": "dequeue", "state": "done", "disposition": "removed"}}}
```

#### edit_queued_message

`edit_queued_message` replaces a queued input's text in place, keeping its order, mode and `clientMessageId`, in the visible lists and the queue the agent drains alike. With `effectId` it is a ledger effect (`kind: "edit_queued"`).

```json
{"type": "edit_queued_message", "queuedId": "q_4", "text": "use the staging database"}
```

A `steer` or `follow_up` sent **without** a `clientMessageId` is still recorded durably under a host-minted id (`host:<durableSessionId>:<uuid>`), so it survives a host restart and a reopen restores it exactly once. No client-facing record carries that id: the send response, `get_state.ordered`, `queue_update.ordered`, `get_steering_messages` / `get_follow_up_messages` and event correlation (`clientMessageId` / `clientMessages` on events) all leave it out, and it never switches on event correlation for a client that sends no ids, before or after a restart. It stays on the stored user message in the transcript, and `get_effect_status` / `effect_status` report it as the input's `effectId`. An edit of such an input survives a restart too. A queued `prompt` sent without an id (`streamingBehavior` while busy) is not durable.

For both commands, `status` is `removed` / `edited`, or `already_delivered` (the input was already handed to the agent) or `not_found` (no such id in this session); those two also carry `reason` and `action`, and an `effectId` receipt ends `failed` with that outcome. A missing or over-long `queuedId` is refused, and so is an edit whose `text` is empty or longer than `MAX_RPC_MESSAGE_CHARACTERS` (use `dequeue_message` to remove an input). An edited input that has a `clientMessageId` (its own or, for input sent without one, the host's) keeps the edit across a reopen, and a retry of its original send still replays.

**Expected revision** (capability `queued_message_revision`): every entry in `get_state.ordered` and `queue_update.ordered` also carries `revision`, 1 when queued and +1 on every successful edit. Both commands accept an optional `expectedRevision` (a whole number of at least 1). When it is present and the input's current revision is different, the answer is `status: "conflict"` with `currentRevision`, `reason` and `action`, and nothing is changed; the check and the change happen in one step, so no other client's edit or a delivery can land between them. With `effectId` the receipt ends `failed` with outcome `conflict`, and a same-id retry replays that conflict. An input that is gone answers `already_delivered` or `not_found` as above, never `conflict`. An `edited` answer carries the resulting `text` and `revision`. A same-id retry answers with exactly the fields the live call returned (the receipt stores them). Revisions, like `queuedId`, hold only for the session's current lifetime: a reopen restores queued inputs at revision 1 under new ids, so re-read `get_state` after a reopen.

```json
{"type": "edit_queued_message", "queuedId": "q_4", "text": "use the staging database", "expectedRevision": 1}
{"type": "response", "command": "edit_queued_message", "success": true, "data": {"queuedId": "q_4", "status": "conflict", "currentRevision": 2, "reason": "conflict", "action": "read the input's current text and revision from get_state or queue_update, then retry with that expectedRevision if the change still applies"}}
```

#### get_pending_inputs

What the engine holds for every pending input, and the outcome of each id a client sent, read in one consistent step (senpi#3549). `inputs` lists every input still queued, sending or failed, each as a projection: `clientMessageId`, `state` (`queued`, `edited`, `sending`, `failed`), `text`, `requestedMode`, `revision`, `statusCode`, `statusText`, `actions` and `pendingDecoration`. `knownClientMessageIds` (at most 64 non-empty ids of at most 256 characters) asks for an outcome per id: `admitted` with its projection, including `delivered` and `removed`, or `not_admitted`. Absence from `inputs` is never an outcome; read the id's outcome instead.

The answer is consistent through `throughCursor`. To follow changes without a gap, subscribe first, apply the snapshot, then apply only `pending_input_update` events whose `cursor` is later. Each event carries every input one committed change touched, under that change's single `cursor`, with the same `lifetimeId`. A different `lifetimeId` means the session reopened: read the snapshot again.

```json
{"type": "get_pending_inputs", "knownClientMessageIds": ["c-7"]}
{"type": "response", "command": "get_pending_inputs", "success": true, "data": {"lifetimeId": "5b0c…", "throughCursor": 4, "inputs": [{"clientMessageId": "c-7", "state": "queued", "text": "also run the tests", "requestedMode": "followUp", "revision": 1, "statusCode": "queued_follow_up", "statusText": "Queued - sent after this turn", "actions": ["edit", "remove", "copy"], "pendingDecoration": true, "supersededVersions": []}], "outcomes": [{"clientMessageId": "c-7", "status": "admitted", "projection": {"clientMessageId": "c-7", "state": "queued"}}]}}
{"type": "pending_input_update", "lifetimeId": "5b0c…", "cursor": 5, "changes": [{"clientMessageId": "c-7", "state": "sending"}]}
```

#### clear_queue

Remove queued steering and follow-up messages and return their text.

```json
{"type": "clear_queue"}
```

Response:
```json
{
  "type": "response",
  "command": "clear_queue",
  "success": true,
  "data": {
    "steering": ["Change direction"],
    "followUp": ["Summarize when finished"]
  }
}
```

To implement interactive Esc behavior, send `clear_queue` before `abort`, then restore the returned text in the client editor. `abort` continues queued messages when they remain in the session.

#### new_session

Start a fresh session. Can be cancelled by a `session_before_switch` extension event handler.

```json
{"type": "new_session"}
```

With optional parent session tracking:
```json
{"type": "new_session", "parentSession": "/path/to/parent-session.jsonl"}
```

Response:
```json
{"type": "response", "command": "new_session", "success": true, "data": {"cancelled": false}}
```

If an extension cancelled:
```json
{"type": "response", "command": "new_session", "success": true, "data": {"cancelled": true}}
```

### State

#### get_snapshot

Atomic snapshot cursor (capability `snapshot_cursor`). Subscribe with `mirror` before taking a snapshot to cut the live record stream at a source-issued cursor rather than at response arrival. Terminal control endpoints support the same command.

`get_snapshot {sessionId, tail?, maxBytes?, observe?: true}` returns `{state, entries, next_before, history_truncated, markerId}`. `state` uses the existing `get_state` projection, including `pendingDialogs` and `pendingQuestions`. `entries` is the newest tail, in chronological order. `tail` defaults to 100 and accepts non-negative integers; `maxBytes` defaults to 8 MiB and accepts positive integers, capped at 48 MiB. The byte bound applies to serialized history entries. An entry that does not fit ends the tail; it is never silently skipped. `history_truncated` reports omitted history; `next_before` is the oldest returned entry's id when older history remains, otherwise null (also null when no entry fits).

State capture, history capture, and enqueueing `{type: "snapshot_marker", sessionId, markerId}` are one synchronous operation. The marker goes only to the requesting connection, only when a matching subscription has `mirror` enabled (including a list of selected record types). Other subscribers never receive that marker. Apply the snapshot and then records after its marker; a post-marker record can arrive **before** the correlated response. A reader without a mirrored subscription receives the snapshot response but no marker record. `observe: true` does not attach or refresh activity.

#### get_state

Get current session state.

```json
{"type": "get_state"}
```

Response:
```json
{
  "type": "response",
  "command": "get_state",
  "success": true,
  "data": {
    "model": {...},
    "thinkingLevel": "medium",
    "thinkingLevelSource": "session",
    "sessionModelThinkingLevels": {"anthropic/<model>": "medium", "openai/<model>": "high"},
    "serviceTier": "priority",
    "fastMode": true,
    "isStreaming": false,
    "isCompacting": false,
    "currentTurnId": "3",
    "steeringMode": "all",
    "followUpMode": "one-at-a-time",
    "sessionFile": "/path/to/session.jsonl",
    "sessionId": "abc123",
    "sessionName": "my-feature-work",
    "autoCompactionEnabled": true,
    "messageCount": 5,
    "pendingMessageCount": 0,
    "pendingDialogs": [],
    "permissionPreset": "ask",
    "permissionPresetSource": "client",
    "permissionPresetStatus": "applied",
    "effectivePermissionPreset": "ask"
  }
}
```

`permissionPreset`, `permissionPresetSource`, `permissionPresetStatus` and `effectivePermissionPreset` report the approval mode the session enforces. `permissionPresetSource` is `client` when a client named a valid preset for this session (`open_session.permissionPreset`, an attach naming one, or `set_permission_preset`) and `host_default` when the host's own default applies (its `--permission-preset` flag, then project and global settings, then `full-access`). `permissionPresetStatus` is `invalid` when the named preset or the host's setting cannot be parsed: the open is still accepted, but every gated tool call is refused, and an invalid preset never counts as one the client set. `effectivePermissionPreset` is the preset the next permission decision uses, `null` while the status is `invalid`. A client confirms a mode it asked for only when `permissionPreset` equals it and `permissionPresetStatus` is `applied`. The `open_session` reply carries the first three fields in `data` as well as in `data.state`.

A preset a client named is recorded in the session file as a `permission_mode` entry. The entry is a record only: a later open that names no preset still uses the host's own default, and the launch flag always wins.

Each gated decision picks its preset in this order:

1. A preset a client named for the session (`open_session.permissionPreset`, an attach naming one, or `set_permission_preset`) wins.
2. Work a remote device started asks: a turn started by a `prompt`, `follow_up` or `steer` (`whenIdle: "start"`) from a delegated connection, and engine-started work (extension messages, goal and loop turns, `continue_from_leaf`, `wake`, restored input) on a session a remote device has driven. A session counts as remote-driven once a delegated connection sends it any record whose method class is `drive` or `device_admin`; the engine's method-class table decides, so every run starter is covered. That includes records that start no turn, such as `abort`, `set_session_name` or `clear_queue`, and the mark lasts for the session's lifetime on purpose: telling which drive records can shape later engine-started work would need a second hand-kept list beside the table, and a wrong guess there would run remote-influenced work without asking, so the engine errs toward asking. When the operator named no `--permission-preset`, it uses the preset a client recorded in the session file instead. An embedder's host-level preset is the host default, not a launch flag. This rule is decided before `spawnedBy`: a parent named in `open_session`, real or not, never takes a remote device's work off it.
3. A child session (`spawnedBy`) follows its live parent's current mode, including later changes to it. A child whose parent is not live in this process asks, unless the operator named a preset for it with `--permission-preset`.
4. Everything else uses the host's own default. A local connection's turn keeps the host default even on a session a remote device has driven, and a `steer` never changes the origin of the turn it joins.

`currentTurnId` is the id of the running turn, present only while one runs; a steer or follow-up names it as `expectedTurnId` (on `prompt`, `steer` or `follow_up`).

The `model` field is a full [Model](#model) object or `null`. `pendingModelSwitch` is always present: `null` means no held switch, while an object with `provider` and `id` identifies a switch that applies after the next compaction. The `sessionName` field is the display name set via `set_session_name`, or omitted if not set.

`pendingDialogs` contains the live `extension_ui_request` frames for select, confirm, input and editor dialogs, or `[]` when none await an answer. Still-open dialogs remain listed after session replacement; resolved, cancelled and timed-out requests are removed. Use these frames to reconcile dialogs during event recovery, separately from `pendingQuestions`.

Each model keeps its own thinking level per session. `sessionModelThinkingLevels` maps `provider/id` to the level that model last ran at in this session, rebuilt from the session file on resume. A model switch (`set_model`, `cycle_model`, the TUI's `/model`) restores, in order: this session's level for the model, a favorite's `:level`, the model's last level in any session (`modelThinkingLevels` in settings), the model's own default, then the configured default, always clamped to the levels the model supports. `thinkingLevelSource` says which one applies: `explicit` (set directly), `session`, `global`, `model-default`, `default`, `fallback` (a retry fallback's temporary level) or `clamped` (a requested or restored level the model cannot run, replaced by the nearest one it can). Hosts before this change omit both fields.

`serviceTier` is the tier a request would carry right now (`"auto"`, `"flex"`, or `"priority"`), omitted when no tier applies. `fastMode` is `true` when the active model is served at the priority ("fast") tier — either because fast mode is on for this session or because the model selection itself pins `priority`. The two never disagree: whenever `fastMode` is `true`, `serviceTier` is `"priority"`.

`lastProviderDiagnostic` is present after a failed turn whose provider supplied structured evidence: `{"category": "rate_limit", "httpStatus": 429, "code": "rate_limit_error", "evidence": "structured_code"}`. `category` is one of `auth`, `rate_limit`, `quota`, `context_limit`, `invalid_request`, `provider_unavailable`, `network`, `unknown` (`network` comes from a structured transport error code such as `ECONNRESET`, with `"evidence": "structured_transport"`); `httpStatus` is absent for errors delivered inside a streamed response. It describes the same failure as the latest assistant `errorMessage` and is replaced or cleared with it. The failed assistant message in `message_end`, `agent_end`, `get_messages` and the session file carries the same object as `providerDiagnostic`. See [Provider failure diagnostics](sdk.md#provider-failure-diagnostics) for how it is derived.

#### get_subscription_limits

Every subscription account's latest limit windows (capability `subscription_limits`). In interactive and
RPC modes (not print mode or `--offline`) the engine polls each signed-in Claude and ChatGPT subscription
account's usage endpoint (Claude every 5 minutes, ChatGPT every 2.5, `Retry-After` honoured, one request
per account per interval across every senpi process on the machine), so an account's windows are known
before its first turn; responses and the Claude SDK update the same record between polls. An account
nothing has reported for is absent - unknown, never 0%. The command only reads and may be sent with
`observe: true`.

```json
{"type": "get_subscription_limits"}
{"type": "response", "command": "get_subscription_limits", "success": true, "data": {"accounts": [{"provider": "chatgpt-subscription", "account": "default", "windows": [{"id": "codex:primary", "label": "7d", "windowMinutes": 10080, "usedPercent": 99, "resetsAt": "2026-10-21T03:29:11.000Z"}], "reportedAt": "2026-10-15T02:58:10.412Z"}]}}
```

`account` is the credential slot that served the request: a stored account's name, `env` for an
environment key, `default` for a single credential; it never carries key material. Each window has an `id`
stable within the account (`<limit>:<slot>`, for example `codex:primary` or `claude:5h`), a `label`
(`5h`, `7d`, `7d opus`), the window length in minutes when the provider sent it, `usedPercent` (0-100) and
`resetsAt` (ISO) when known. ChatGPT subscriptions report them in `x-codex-primary-*`/`x-codex-secondary-*`
response headers (one family per metered limit); Claude subscriptions in `anthropic-ratelimit-unified-*`
headers, and through the Claude SDK lane in its `rate_limit_event` messages. A window the latest response did not mention keeps its last value. A poll answers with the account's whole window set and replaces it. `plan` is the plan the usage endpoint names (ChatGPT), when it names one; `error` says why the last poll failed (`auth stale - run /login`, `rate limited`, `HTTP <status>`, `timed out`, `unreachable`), and the windows beside it are the last ones reported. The next successful report clears it. Every connection also hears a
`subscription_limits` record (below) when an account's windows change.

#### get_effect_status

The newest receipt of one effect (capability `effect_ledger`). For inputs `effectId` is the
`clientMessageId`. The command only reads: it never resets a host's or session's idle window,
works on a session another process holds, and may be sent with `observe: true`.

With `sessionId` it answers from the loaded session. With `sessionPath` and no `sessionId` it
reads that transcript from disk, so a session that was unloaded or whose host restarted is
answered without being loaded again:

```json
{"type": "get_effect_status", "effectId": "stop-1", "sessionId": "rpc-1"}
{"type": "get_effect_status", "effectId": "stop-1", "sessionPath": "/path/to/session.jsonl"}
```

Response:
```json
{"type": "response", "command": "get_effect_status", "success": true, "data": {"found": true, "effect": {"effectId": "stop-1", "kind": "abort", "state": "done", "disposition": "no_active_turn", "durableSessionId": "session-id"}}}
{"type": "response", "command": "get_effect_status", "success": true, "data": {"found": false, "searched": "complete"}}
```

`found: false` is answered only after the whole transcript was searched (the read starts with
the last 4 MiB and continues to the header), so it is proof the effect never landed: send the
same id again. A transcript that cannot be read is refused with
`errorCode: "transcript_unreadable"` and `errorData: { path, reason, action }`, never with
`found: false`.

#### get_messages

Account-scoped usage failures are projected as recovery advice with `errorCause: {"type":"usage_limit","scope":"account"}` in `message_*`, `agent_end`, `entry_appended`, `get_messages`, `get_entries`, and `get_tree`. The engine message and session file retain the original provider error for diagnostics; these raw stored messages are not the user-facing RPC representation. Entry ids, parent links, timestamps, tree labels, and provider diagnostics are preserved by the projection.

Get all messages in the conversation.

```json
{"type": "get_messages"}
```

Response:
```json
{
  "type": "response",
  "command": "get_messages",
  "success": true,
  "data": {"messages": [...]}
}
```

Messages are `AgentMessage` objects (see [Message Types](#message-types)).

#### get_media

Fetch one media block that was omitted for a [`media_placeholders`](#media_placeholders) client. The
parameters are exactly the placeholder's `ref`.

```json
{"type": "get_media", "toolCallId": "call_abc123", "contentIndex": 1}
```

Response:
```json
{
  "type": "response",
  "command": "get_media",
  "success": true,
  "data": {
    "toolCallId": "call_abc123",
    "contentIndex": 1,
    "content": {"type": "image", "data": "<base64>", "mimeType": "image/png"}
  }
}
```

`content` is the original `ImageContent` block, byte-for-byte. `contentIndex` indexes the tool
result's `content` array. The host looks the tool call up in the durable session entries first (so a
block stays fetchable after the live message window moved on), then in the current messages for a
result that has not been persisted yet.

When the tool call is unknown, the index is out of range, or the index points at a non-image block,
the response fails with `error` and `errorCode` both set to `media_not_found`:

```json
{
  "type": "response",
  "command": "get_media",
  "success": false,
  "error": "media_not_found",
  "errorCode": "media_not_found"
}
```

The command is answered in classic and multi-session mode alike; in multi-session mode it takes the
usual `sessionId` envelope. It is answerable regardless of whether the connection advertised
`media_placeholders`.

### Model

#### set_model

Switch to a specific model. A provider/model pair the session's registry does not offer is refused with
`errorCode: "model_not_found"`.

```json
{"type": "set_model", "provider": "anthropic", "modelId": "claude-sonnet-4-20250514"}
```

Without a scope, the switch also becomes the device's default model (written to the settings file), so new
sessions open on it. `"scope": "session"` switches only this session: the switch is recorded in its history and
restored on resume, extensions see the same `model_select`, and the default model and every other session are left
as they were. The engine's method-class table classes the scoped form as `drive` and the unscoped form as
`device_admin`. An engine that honours the scope advertises `session_model_scope` in
`get_protocol_info.capabilities` (host and classic connection alike); an older engine ignores the field and also moves
the default model, so send the scope only when that capability is listed.

```json
{"type": "set_model", "provider": "anthropic", "modelId": "claude-sonnet-4-20250514", "scope": "session"}
```

An optional `effectId` records the switch as an effect: the response adds `effectId`,
`state` and `effect` beside the model, a retry with the same id answers
`replayed: true` without switching again, and a refusal also records the receipt as
`failed`. See [Effects and receipts](#effects-and-receipts).

Response contains the full [Model](#model) object:
```json
{
  "type": "response",
  "command": "set_model",
  "success": true,
  "data": {...}
}
```

#### cycle_model

Cycle to the next available model. Returns `null` data if only one model available.

```json
{"type": "cycle_model"}
```

Response:
```json
{
  "type": "response",
  "command": "cycle_model",
  "success": true,
  "data": {
    "model": {...},
    "thinkingLevel": "medium",
    "isScoped": false
  }
}
```

The `model` field is a full [Model](#model) object.

#### get_available_models

List all configured models, refreshing credential availability on each request so credentials added or removed by another session take effect without reopening this session.

```json
{"type": "get_available_models"}
```

Response contains an array of full [Model](#model) objects with supported thinking levels. A row's `serviceTier` and `upstreamModelId` are the values the session resolves for that model, including ones declared only in `models.json` or by an extension provider, so a `-fast` priority alias names its base model there and a client can tell a child opened on the base model is the alias it asked for. Each row also carries `supportsAssistantPrefill`: whether the model accepts a request ending with an assistant message, given the session's current thinking level. It is `false` for every model today, so clients continue an edited answer with `continue_from_leaf`:
```json
{
  "type": "response",
  "command": "get_available_models",
  "success": true,
  "data": {
    "models": [...]
  }
}
```

### Thinking

#### set_thinking_level

Set the reasoning/thinking level for models that support it.

```json
{"type": "set_thinking_level", "level": "high"}
```

Levels: `"off"`, `"minimal"`, `"low"`, `"medium"`, `"high"`, `"xhigh"`, `"max"`

`"xhigh"` and `"max"` are exposed only when supported by the selected model. Some models, including GPT-5.6, expose both.

Response:
```json
{"type": "response", "command": "set_thinking_level", "success": true}
```

Pass `"scope": "turn"` to change only the current session level without rewriting the model's remembered level. The
command returns an error when the active model cannot apply the requested level, and a rejected request leaves the
session level unchanged — a failed `set_thinking_level` never mutates state.

```json
{
  "type": "response",
  "command": "set_thinking_level",
  "success": false,
  "error": "Thinking level low is not supported by the active model."
}
```

#### cycle_thinking_level

Cycle through available thinking levels. Returns `null` data if model doesn't support thinking.

```json
{"type": "cycle_thinking_level"}
```

Response:
```json
{
  "type": "response",
  "command": "cycle_thinking_level",
  "success": true,
  "data": {"level": "high"}
}
```

#### get_available_thinking_levels

List the thinking levels supported by the current model. Returns `["off"]` for a model without reasoning support.

```json
{"type": "get_available_thinking_levels"}
```

Response:
```json
{
  "type": "response",
  "command": "get_available_thinking_levels",
  "success": true,
  "data": {
    "levels": ["off", "minimal", "low", "medium", "high"]
  }
}
```

#### get_model_thinking_level

The thinking level one model runs at in this session, without switching to it. For the active model it is the current level; for any other model it is the level `set_model` would restore (see `thinkingLevelSource` under [get_state](#get_state) for the order). A client shows a model's effort with it before the user sends anything, instead of keeping its own per-model copy. The command only reads and does not count as session activity.

```json
{"type": "get_model_thinking_level", "provider": "openai", "modelId": "<model>"}
```

Response:
```json
{
  "type": "response",
  "command": "get_model_thinking_level",
  "success": true,
  "data": {"level": "high", "source": "session", "availableLevels": ["off", "low", "medium", "high"]}
}
```

An unknown model answers `success: false` with `errorCode: "model_not_found"`; a missing `provider` or `modelId` answers `errorCode: "invalid_argument"`.

### Fast mode

#### set_fast_mode

Turn fast mode (the ChatGPT Subscription `priority` service tier) on or off for the active model. The choice is remembered
per model, so a later session on the same model starts the same way; `enabled: false` records an explicit `"auto"`
so it also overrides a tier inherited from the model catalog.

```json
{"type": "set_fast_mode", "enabled": true}
```

Response:
```json
{
  "type": "response",
  "command": "set_fast_mode",
  "success": true,
  "data": {
    "enabled": true,
    "serviceTier": "priority",
    "provider": "chatgpt-subscription",
    "modelId": "gpt-5.6-sol"
  }
}
```

`serviceTier` is the tier just recorded for the model (`"priority"` on, `"auto"` off). `provider`/`modelId` identify
the model the preference was stored under: a `-fast` catalog variant and its base model share one entry, so the
reported id can be the base model rather than the model that was active.

The command returns an error instead of a silent no-op when the request cannot be applied:

| Situation | `error` |
|-----------|---------|
| Active model is not a ChatGPT Subscription model | `Fast mode is only available for ChatGPT Subscription models.` |
| `enabled: false` while the model selection pins `:priority` | `Fast mode is fixed by the active model selection's priority tier.` |
| `enabled` is not a boolean | `set_fast_mode requires a boolean 'enabled' field.` |

A successful call emits a [`service_tier_changed`](#service_tier_changed) event.

#### get_fast_mode

Read the current fast-mode state.

```json
{"type": "get_fast_mode"}
```

Response:
```json
{
  "type": "response",
  "command": "get_fast_mode",
  "success": true,
  "data": {"enabled": true, "serviceTier": "priority"}
}
```

`serviceTier` is `null` when no tier applies. It matches `get_state.serviceTier`.

### Queue Modes

#### set_steering_mode

Control how steering messages (from `steer`) are delivered.

```json
{"type": "set_steering_mode", "mode": "one-at-a-time"}
```

Modes:
- `"all"`: Deliver all steering messages after the current assistant turn finishes executing its tool calls
- `"one-at-a-time"`: Deliver one steering message per completed assistant turn (default)

Response:
```json
{"type": "response", "command": "set_steering_mode", "success": true}
```

#### set_follow_up_mode

Control how follow-up messages (from `follow_up`) are delivered.

```json
{"type": "set_follow_up_mode", "mode": "one-at-a-time"}
```

Modes:
- `"all"`: Deliver all follow-up messages when agent finishes
- `"one-at-a-time"`: Deliver one follow-up message per agent completion (default)

Response:
```json
{"type": "response", "command": "set_follow_up_mode", "success": true}
```

### Compaction

#### compact

Manually compact conversation context to reduce token usage.

```json
{"type": "compact"}
```

With custom instructions:
```json
{"type": "compact", "customInstructions": "Focus on code changes"}
```

Response:
```json
{
  "type": "response",
  "command": "compact",
  "success": true,
  "data": {
    "summary": "Summary of conversation...",
    "firstKeptEntryId": "abc123",
    "tokensBefore": 150000,
    "estimatedTokensAfter": 32000,
    "usage": {
      "input": 32000,
      "output": 1200,
      "cacheRead": 0,
      "cacheWrite": 0,
      "totalTokens": 33200,
      "cost": {"input": 0.01, "output": 0.02, "cacheRead": 0, "cacheWrite": 0, "total": 0.03}
    },
    "details": {}
  }
}
```

`estimatedTokensAfter` is a heuristic estimate over the rebuilt message context immediately after compaction, not a provider-exact token count. `usage` reports the LLM call or calls that generated the summary and may be omitted by custom compaction handlers.

#### set_auto_compaction

Enable or disable automatic compaction when context is nearly full for this session only. The persisted `compaction.enabled` setting is left untouched, and `get_state` reports the effective value. Disabling it stops proactive threshold compaction; a provider-rejected context overflow still triggers the one-shot compact-and-retry recovery.

```json
{"type": "set_auto_compaction", "enabled": true}
```

Response:
```json
{"type": "response", "command": "set_auto_compaction", "success": true}
```

#### set_permission_preset

Move this session to another approval mode. It works on a classic `--mode rpc` connection, which refuses `open_session`, and on a multi-session host with the `sessionId` envelope, so a client on another device can change a live session's mode without knowing its session file. It is classed `device_admin`: it changes what the agent may do without asking. Hosts that take it advertise `set_permission_preset_v1`.

```json
{"type": "set_permission_preset", "permissionPreset": "ask"}
```

Response:
```json
{"type": "response", "command": "set_permission_preset", "success": true, "data": {"permissionPreset": "ask", "permissionPresetSource": "client", "permissionPresetStatus": "applied"}}
```

The new preset applies from the next permission decision, and the session file records it like a preset named at open. An unknown preset is refused with `errorCode` `invalid_launch_profile` and changes nothing, so the session keeps the mode it had. Extensions hear a change on the `permission_preset_changed` event and read the enforced preset with `pi.getPermissionPreset()`.

### Retry

#### set_auto_retry

Enable or disable automatic retry on transient errors (overloaded, rate limit, 5xx).

```json
{"type": "set_auto_retry", "enabled": true}
```

Response:
```json
{"type": "response", "command": "set_auto_retry", "success": true}
```

#### abort_retry

Abort an in-progress retry (cancel the delay and stop retrying).

```json
{"type": "abort_retry"}
```

Response:
```json
{"type": "response", "command": "abort_retry", "success": true}
```

#### set_retry_fallback

A single-session `--mode rpc` process has no `open_session`. A caller that spawns one process per session (e.g. a task
child that runs as its own process) gives it its fallback policy with `set_retry_fallback`:

```json
{"type": "set_retry_fallback", "retryFallback": {"modelFallback": true, "fallbackChains": {"provider/model": ["provider/spare"]}}}
```

Response:
```json
{"type": "response", "command": "set_retry_fallback", "success": true}
```

The profile is the same shape, with the same limits, as `open_session.retryFallback`, and it has the same effect. It
overrides the session's `retry.modelFallback` and `retry.fallbackChains` in memory only, it is never written to a
settings file, and the process's later sessions (`new_session`, `switch_session`, `fork`) keep it.

It is a launch-time setting:
- It is accepted only before the session's first turn. It is refused once this connection has asked for a turn
  (`prompt`, `steer`, `follow_up`, `continue_from_leaf`, `send_custom_message` with `triggerTurn`), even one that has
  not started yet, while a turn streams (an extension's included), and once the session holds turn history (a resumed
  session's). So a chain never changes under a provider request or a retry already in flight. Context messages added
  before the first turn (role `custom`, from an extension on `session_start` or a `send_custom_message` without
  `triggerTurn`) are not a turn and do not block it.
- Send it on its own and await its response: a `set_retry_fallback` pipelined while a `new_session`, `switch_session`
  or `fork` is still being created can answer success while the session being created runs without it.
- A malformed profile is refused with the `open_session` shape message, and nothing is applied.
- A multi-session host refuses the command on its session connections; a host session takes its policy from
  `open_session.retryFallback`.

Probe `retry_fallback_command` in `get_protocol_info` before sending it. Only a single-session process advertises it.
Unlike an environment variable, the profile reaches this process only, never what its tools spawn. Unlike argv, it has
no command-line length limit and is not visible in a process listing.

### Bash

#### bash

Execute a shell command and add output to conversation context. Output streams as `bash_execution_update` events while the command runs; the response contains the final result.

```json
{"id": "req-1", "type": "bash", "command": "ls -la"}
```

Include an `id` to associate streamed `bash_execution_update` events with this command.

Response:
```json
{
  "id": "req-1",
  "type": "response",
  "command": "bash",
  "success": true,
  "data": {
    "output": "total 48\ndrwxr-xr-x ...",
    "exitCode": 0,
    "cancelled": false,
    "truncated": false
  }
}
```

If output was truncated, includes `fullOutputPath`:
```json
{
  "type": "response",
  "command": "bash",
  "success": true,
  "data": {
    "output": "truncated output...",
    "exitCode": 0,
    "cancelled": false,
    "truncated": true,
    "fullOutputPath": "/tmp/pi-bash-abc123.log"
  }
}
```

**How bash results reach the LLM:**

The `bash` command executes immediately and returns a `BashResult`. Internally, a `BashExecutionMessage` is created and stored in the agent's message state.

When the next `prompt` command is sent, all messages (including `BashExecutionMessage`) are transformed before being sent to the LLM. The `BashExecutionMessage` is converted to a `UserMessage` with this format:

````
Ran `ls -la`
```
total 48
drwxr-xr-x ...
```
````

This means:
1. Bash output is included in the LLM context on the **next prompt**, not immediately
2. Multiple bash commands can be executed before a prompt; all outputs will be included

#### abort_bash

Abort a running bash command.

```json
{"type": "abort_bash"}
```

Response:
```json
{"type": "response", "command": "abort_bash", "success": true}
```

### Session

#### get_session_stats

Get token usage, cost statistics, and current context window usage.

```json
{"type": "get_session_stats"}
```

Response:
```json
{
  "type": "response",
  "command": "get_session_stats",
  "success": true,
  "data": {
    "sessionFile": "/path/to/session.jsonl",
    "sessionId": "abc123",
    "userMessages": 5,
    "assistantMessages": 5,
    "toolCalls": 12,
    "toolResults": 12,
    "totalMessages": 22,
    "tokens": {
      "input": 50000,
      "output": 10000,
      "cacheRead": 40000,
      "cacheWrite": 5000,
      "total": 105000
    },
    "cost": 0.45,
    "contextUsage": {
      "tokens": 60000,
      "contextWindow": 200000,
      "percent": 30
    },
    "failures": {
      "requests": 6,
      "erroredRequests": 1,
      "abortedRequests": 0,
      "failureShare": 0.16666666666666666,
      "failedDurationMs": 4200,
      "postFailureRequests": 1,
      "postFailureFullMissRequests": 1,
      "postFailureFullMissInputTokens": 48000
    }
  }
}
```

`cost` sums the provider-reported cost of every turn. `costUnknown: true` appears when at least one turn ran on a model with no known price (senpi#3844): `cost` is then a lower bound, not the full spend. The field is absent otherwise.

`failures` reports what failed provider requests cost the session. Every assistant response is one request; `erroredRequests` and `abortedRequests` count responses that ended with stop reason `error` or `aborted`, and `failedDurationMs` sums their time from request start to the recorded response. `postFailureRequests` counts the first successful response after one or more failed ones within the same user turn (a user message resets it); `postFailureFullMissRequests` counts those that read nothing from the prompt cache on a prompt of at least 2048 tokens, and `postFailureFullMissInputTokens` sums their uncached prompt tokens (input plus cache writes). The token counts are the provider's usage report; attributing the cache miss to the preceding failure is an inference from the turn's sequence. Hosts older than this field omit it.

`tokens` and `cost` include assistant messages, usage reported by tools, and compaction/branch-summary generation across the full session. `contextUsage` contains the actual current context-window estimate used for compaction and footer display.

`contextUsage` is omitted when no model or context window is available. `contextUsage.tokens` and `contextUsage.percent` are `null` immediately after compaction until a fresh post-compaction assistant response provides valid usage data.

#### resolve_path

Resolve a path from a message to the file it means, with the same rule the TUI uses for links. A relative `path` is tried against the session's working directory first, then the project root (the nearest ancestor of the working directory holding `.git`, else the nearest project marker); the first candidate that exists wins. An absolute path or `~/...` is only resolved. The answer is the realpath (symlinks and `..` resolved). It says which file a link means, not whether a client may read it.

```json
{"type": "resolve_path", "path": "docs/plan.md"}
```

Response when a candidate exists (`kind` is `file` or `directory`; `base` is `cwd`, `project-root` or `absolute`):
```json
{
  "type": "response",
  "command": "resolve_path",
  "success": true,
  "data": {"status": "found", "realpath": "/repo/docs/plan.md", "kind": "file", "base": "project-root"}
}
```

When nothing is there, `tried` lists every candidate in order:
```json
{
  "type": "response",
  "command": "resolve_path",
  "success": true,
  "data": {"status": "not_found", "tried": ["/repo/packages/app/docs/plan.md", "/repo/docs/plan.md"]}
}
```

An empty `path` or one with a NUL byte answers `not_found` with no candidates; a non-string or longer than 4096 characters is a payload error.

#### memory_report

Write a per-layer memory report for this session on demand. Available only when the host process runs with `SENPI_MEMORY_REPORT=1`; without it nothing is installed and the request fails with `memory_report_disabled`. On POSIX the same report is also written when the process receives `SIGUSR2`, for every live session registered in that process: a TUI, print, or single-session RPC host, or a multi-session host with the in-process runtime (`--listen`, the shared daemon default), reports all of its sessions. On a worker-runtime multi-session host (the stdio default), sessions live in worker isolates the signalled main isolate cannot see, so the signal writes nothing; send the `memory_report` request to each session instead. Nothing runs on a timer.

```json
{"type": "memory_report"}
```

Response:
```json
{
  "type": "response",
  "command": "memory_report",
  "success": true,
  "data": { "path": "/path/to/session-artifacts/memory/2026-10-02T11-30-00.000Z.json" }
}
```

The file is written to `<session>-artifacts/memory/<iso>.json` beside the session file and holds:

- `main`: the process's main-thread memory: `jscHeapSize` (Bun only), `heapUsed`, `external`, and `footprint` (`bytes`, `measure`).
- `kernels`: every live eval kernel in the process with `language`, `measure` (`heap` or `footprint`), `lastLiveBytes`, and `stale: true` when a cell was running so the reading predates the cell.
- `residentStore`: `entries` and `approxBytes` of the session's in-memory resident strings.
- `tuiRenderCache` (terminal UI only): `components`, `cachedLines`, `images` across live tool cards.
- one object per extension memory reporter, under its registered name (for example `taskChildren`), and `reporterErrors` for reporters that threw.

With `SENPI_MEMORY_REPORT_SNAPSHOT=1` a heap snapshot of the main thread is written beside the report and `data.heapSnapshot` (and the report's `heapSnapshot`) names it. A report that cannot be written answers `memory_report_failed: <reason>`, logs one stderr line, and leaves the session running.

#### export_html

Export session to an HTML file.

```json
{"type": "export_html"}
```

With custom path:
```json
{"type": "export_html", "outputPath": "/tmp/session.html"}
```

Response:
```json
{
  "type": "response",
  "command": "export_html",
  "success": true,
  "data": {"path": "/tmp/session.html"}
}
```

#### switch_session

Load a different session file. Can be cancelled by a `session_before_switch` extension event handler.

```json
{"type": "switch_session", "sessionPath": "/path/to/session.jsonl", "cwdOverride": "/path/to/project"}
```

`cwdOverride` is optional. When supplied, the replacement session and its cwd-bound settings and runtime state are rebuilt for that directory instead of using the session file's stored cwd. The host also resolves `projectTrusted` from its saved project trust store for the replacement cwd; an absent or false decision keeps project-scoped settings and resources disabled.

Response:
```json
{"type": "response", "command": "switch_session", "success": true, "data": {"cancelled": false}}
```

If an extension cancelled the switch:
```json
{"type": "response", "command": "switch_session", "success": true, "data": {"cancelled": true}}
```

#### fork

Create a new fork from a previous user message on the active branch. Can be cancelled by a `session_before_fork` extension event handler. Returns the text of the message being forked from.

```json
{"type": "fork", "entryId": "abc123"}
```

Response:
```json
{
  "type": "response",
  "command": "fork",
  "success": true,
  "data": {"text": "The original prompt text...", "cancelled": false}
}
```

If an extension cancelled the fork:
```json
{
  "type": "response",
  "command": "fork",
  "success": true,
  "data": {"text": "The original prompt text...", "cancelled": true}
}
```

#### navigate_tree

Move the session leaf to another point in the tree without creating a new file: the RPC equivalent of `/tree` (see [Branching with `/tree`](sessions.md#branching-with-tree)). Nothing is deleted; the branch you leave stays in the file. Emits `session_before_tree` (cancellable) and `session_tree`.

The target is addressed in one of two ways. Send exactly one of them; a request with both, or neither, is refused.

**`entryId`: select like the TUI by default.** Unless `intent: "resume"` is supplied, the host applies the `/tree` selection rule from [Selection Behavior](sessions.md#selection-behavior), so a client never computes a parent id:

- A user or custom message moves the leaf to that entry's **parent** and returns the entry's text as `editorText`, the text the TUI would put back in the editor for you to edit and resubmit.
- Any other kind (assistant, tool, compaction, ...) moves the leaf **to** the entry. No `editorText`.
- The root user message resets the leaf to an empty conversation. `leafId` is `null` and `editorText` carries the original prompt.

```json
{"type": "navigate_tree", "entryId": "u2", "expectedLeafId": "a3"}
```

Response:

```json
{"type": "response", "command": "navigate_tree", "success": true, "data": {"outcome": "navigated", "leafId": "a1", "editorText": "Let's try approach A..."}}
```

Other outcome: `{"outcome": "cancelled", "leafId": "...", "aborted": true}` when an extension cancelled the navigation or the summary was aborted. With a summary, `summaryEntryId` names the new `branch_summary` entry.

**`targetId`: select with the legacy response.** The original spelling, kept for the TUI and every shipped client. It applies the same selection rule as `entryId`: user/custom messages select their parent and return `editorText`, other entries select themselves, and the root user message resets the leaf to `null`. The difference is the response shape, not where selection moves the leaf: `targetId` answers the legacy payload, while `entryId` answers the richer `outcome`-tagged payload.

```json
{"type": "navigate_tree", "targetId": "u2", "expectedLeafId": "a3"}
```

Response:

```json
{"type": "response", "command": "navigate_tree", "success": true, "data": {"cancelled": false, "leafId": "a1", "editorText": "Let's try approach A..."}}
```

`editorText`, `aborted` and `summaryEntry` (the full `branch_summary` entry) appear on this shape when they apply. With either spelling, selecting a user/custom message that is already the current leaf still moves to its parent and returns its text. In particular, retrying the most recent prompt removes it from the active context before resubmission; selecting a root prompt leaves an empty conversation.

**`intent: "resume"`: resume the exact leaf.** With either address, this explicitly moves the leaf **to the requested entry itself**, including a user, root user, or custom message. No `editorText` is returned: no prompt is being selected for editing. Use this to switch back to an edit-only branch whose tail is the edited user message. Resuming the current leaf keeps it in place. No turn starts, no entry is copied, and the abandoned branch remains intact. The address still determines only the response shape.

```json
{"type": "navigate_tree", "entryId": "edited-u2", "intent": "resume", "expectedLeafId": "a3"}
```

Response:

```json
{"type": "response", "command": "navigate_tree", "success": true, "data": {"outcome": "navigated", "leafId": "edited-u2"}}
```

Using `targetId` with the same intent instead returns `{"cancelled": false, "leafId": "edited-u2"}`. Omitting `intent`, or specifying `"select"`, preserves the released retry-selection behavior and payloads described above; changing address alone never requests resumption.

Resumption uses the same core navigation lifecycle, cancellation, streaming guard, and summary generation. When `summarize` or `label` is supplied, their entries are still recorded, but the active leaf stays on the requested entry rather than the generated metadata. A summary is stored as a child of that entry and returned through `summaryEntryId` / `summaryEntry`; it is not part of the resumed active context. Labels remain visible on the tree. Metadata appended by lifecycle handlers is preserved too, without replacing the exact leaf when navigation returns.

Options, common to both spellings:

- `intent` (optional): `"select"` (default) or `"resume"`. Any other value is refused before navigation rather than silently selecting a prompt.
- `expectedLeafId` (optional): the leaf you last observed (from `get_tree`, `get_entries`, or the `entry_appended` stream). Forwarded unchanged for either intent, including an empty string. When the session's current leaf differs, the command fails with `errorCode: "stale_leaf"` before anything is written, so a client with a stale view can't move a conversation another client already moved.
- `summarize` (optional): summarize the abandoned branch and attach the summary at the new position, as described under [Branch Summaries](sessions.md#branch-summaries). Requires a model.
- `customInstructions` (optional): extra guidance for the summary. With `replaceInstructions: true` it replaces the default summarization prompt instead of extending it.
- `label` (optional): a label to set on the new position.

`leafId` is present on every success payload of either spelling and is `null` when the session was left on an empty conversation. Read it back rather than predicting the leaf: one round trip resynchronizes a client.

Navigation failures for either address and either intent carry a typed `errorCode`:

| `errorCode` | Meaning |
|-------------|---------|
| `streaming` | A response is in flight; retry once the turn ends |
| `not_found` | No entry with that id |
| `stale_leaf` | `expectedLeafId` no longer matches the session leaf |

The human-readable `error` text is also retained for older clients. Malformed addressing or intent is refused with `error` text and the current `errorData.leafId`, without a typed `errorCode`.

#### edit_assistant_message

Replace an assistant response with an edited copy. The session leaf moves to the target entry's parent and the edited copy is appended there as the new leaf, so the original response and everything after it stay in the file on an abandoned branch. The copy keeps only the new text (tool calls and thinking blocks are dropped; `stopReason` is `stop`) and preserves the original's model, provider and usage. Emits `session_before_tree` (cancellable) and `session_tree` like tree navigation.

```json
{"type": "edit_assistant_message", "entryId": "abc123", "text": "The corrected answer.", "expectedLeafId": "def456"}
```

- `expectedLeafId` (optional): the leaf you last observed (from `get_tree`, `get_entries`, or the `entry_appended` stream). When the session's current leaf differs, the command fails with `errorCode: "stale_leaf"` before anything is written - this is how a client with a stale view is refused instead of overwriting a conversation another client moved. The check runs before the unchanged comparison, so identical text still reports `stale_leaf` from a stale client.
- `summarize` / `customInstructions` (optional): summarize the abandoned branch like `navigate_tree`. With a summary, the edited copy's parent is the new `branch_summary` entry (its id is returned as `summaryEntryId`).

Response:

```json
{"type": "response", "command": "edit_assistant_message", "success": true, "data": {"outcome": "edited", "entry": {"type": "message", "id": "ghi789", "parentId": "u1", "message": {"role": "assistant", "content": [{"type": "text", "text": "The corrected answer."}]}}, "leafId": "ghi789"}}
```

Other outcomes: `{"outcome": "unchanged", "leafId": "..."}` when the text matches the original (nothing written) and `{"outcome": "cancelled", "leafId": "...", "aborted": true}` when an extension cancelled the navigation or the summary was aborted.

Failures carry a typed `errorCode`:

| `errorCode` | Meaning |
|-------------|---------|
| `streaming` | A response is in flight; retry once the turn ends |
| `not_found` | No entry with that id |
| `not_assistant` | The entry is not an assistant message |
| `empty` | The replacement text is blank |
| `stale_leaf` | `expectedLeafId` no longer matches the session leaf |

Message identity: RPC mode emits `entry_appended` right after every persisted `message_end`, carrying the full session entry (`entry.id`, `entry.parentId`, `entry.message`). Clients should record `entry.id` from that stream as the identity of each rendered message instead of inferring it by position, and pass it as `entryId` here.

#### continue_from_leaf

Start a new turn from the session's current leaf without a new user prompt. A typical use is after `edit_assistant_message`: the agent carries on from the edited answer as if it were its own words. Default models do not accept a request that ends with an assistant message, so the turn is driven by a hidden custom message (`customType: "continue-from-leaf"`, `display: false`). It is persisted, but clients must never render it. Only hosts that advertise the `continue_from_leaf` capability in `get_protocol_info` accept this command.

```json
{"type": "continue_from_leaf"}
```

Response (the turn then streams like any other):

```json
{"type": "response", "command": "continue_from_leaf", "success": true}
```

Failures carry a typed `errorCode`:

| `errorCode` | Meaning |
|-------------|---------|
| `streaming` | A response is in flight; retry once the turn ends |
| `nothing_to_continue` | The session has no messages yet |
| `leaf_not_assistant` | The conversation ends on a user message (for example an edited prompt): there is no answer to continue. Send or retry it instead |

A provider error during the continued turn is reported through the usual turn events, as for a prompt.

#### edit_user_message

Replace a user message with an edited copy, in place. This is the `/tree` flow for selecting a prompt (see [Selection Behavior](sessions.md#selection-behavior)) with the edited text written into the session instead of into an editor: the leaf moves to the target's parent and the edited copy is appended there as the new leaf. The original prompt and every reply after it stay in the file on an abandoned branch. Nothing is deleted.

The copy keeps the new text, trimmed, and carries every non-text block of the original (images, attachments) over verbatim. Those are the user's own input and the model still needs them.

No turn starts. After the call the active tail is a prompt with no reply; send `prompt`, or continue however your client normally runs a turn, when you want one. Emits `session_before_tree` (cancellable) and `session_tree` like `navigate_tree`.

```json
{"type": "edit_user_message", "entryId": "u2", "text": "Let's try approach C instead.", "expectedLeafId": "a3"}
```

- `expectedLeafId` (optional): the leaf you last observed (from `get_tree`, `get_entries`, or the `entry_appended` stream). When the session's current leaf differs, the command fails with `errorCode: "stale_leaf"` before anything is written. The check runs before the unchanged comparison, so identical text still reports `stale_leaf` from a stale client.
- `summarize` / `customInstructions` (optional): summarize the abandoned branch like `navigate_tree`. With a summary, the edited copy's parent is the new `branch_summary` entry (its id is returned as `summaryEntryId`).

Response:

```json
{"type": "response", "command": "edit_user_message", "success": true, "data": {"outcome": "edited", "entry": {"type": "message", "id": "u4", "parentId": "a1", "message": {"role": "user", "content": [{"type": "text", "text": "Let's try approach C instead."}]}}, "leafId": "u4"}}
```

Other outcomes: `{"outcome": "unchanged", "leafId": "..."}` when the text matches the original (nothing written) and `{"outcome": "cancelled", "leafId": "...", "aborted": true}` when an extension cancelled the navigation or the summary was aborted. `leafId` is reported on every outcome and is `null` when the session was left on an empty conversation.

Failures carry a typed `errorCode`:

| `errorCode` | Meaning |
|-------------|---------|
| `streaming` | A response is in flight; retry once the turn ends |
| `not_found` | No entry with that id |
| `not_user` | The entry is not a user message |
| `empty` | The replacement text is blank |
| `stale_leaf` | `expectedLeafId` no longer matches the session leaf |

Message identity: as with `edit_assistant_message`, record `entry.id` from the `entry_appended` stream as the identity of each rendered message and pass it as `entryId` here. Don't infer it by position; after an edit the positions on screen no longer match the file.

#### clone

Duplicate the current active branch into a new session at the current position. Can be cancelled by a `session_before_fork` extension event handler.

```json
{"type": "clone"}
```

Response:
```json
{
  "type": "response",
  "command": "clone",
  "success": true,
  "data": {"cancelled": false}
}
```

If an extension cancelled the clone:
```json
{
  "type": "response",
  "command": "clone",
  "success": true,
  "data": {"cancelled": true}
}
```

#### get_fork_messages

Get user messages available for forking.

```json
{"type": "get_fork_messages"}
```

Response:
```json
{
  "type": "response",
  "command": "get_fork_messages",
  "success": true,
  "data": {
    "messages": [
      {"entryId": "abc123", "text": "First prompt..."},
      {"entryId": "def456", "text": "Second prompt..."}
    ]
  }
}
```

#### get_entries

Get all session entries in append order (excluding the session header). The session is an append-only tree of entries with stable ids, so an entry id works as a durable cursor: pass the last entry id you have seen as `since` to get only entries strictly after it, even across client restarts. Unlike `get_messages`, this includes pre-compaction history and abandoned branches.

```json
{"type": "get_entries"}
```

With a cursor (an id that names no entry is refused with `errorCode: "not_found"`):
```json
{"type": "get_entries", "since": "abc123"}
```

Response:
```json
{
  "type": "response",
  "command": "get_entries",
  "success": true,
  "data": {
    "entries": [
      {"type": "message", "id": "def456", "parentId": "abc123", "timestamp": "...", "message": {"role": "user", "...": "..."}}
    ],
    "leafId": "def456"
  }
}
```

`leafId` is the id of the current leaf entry (`null` for an empty session), so a client can tell in one round trip whether the active branch moved. If `since` does not match any entry id, the response is `success: false`.

**Pages.** One answer travels as one line on the connection's event queue, which closes the connection past 64 MiB. Pass `limit` (entries) and/or `maxBytes` (serialized bytes, capped at 48 MiB; 8 MiB when only `limit` is given) to read a long history in pages. A paged answer carries `hasMore`, and `nextSince` (the last entry id it returned) while more entries follow; ask again with `since: nextSince` until `hasMore` is `false`. A page always holds at least one entry, so it always moves forward. Both bounds must be positive integers, otherwise the request fails with `errorCode: "invalid_argument"`.

```json
{"type": "get_entries", "limit": 500, "maxBytes": 8388608}
{"type": "get_entries", "limit": 500, "maxBytes": 8388608, "since": "<nextSince>"}
```

An unpaged request (neither bound) answers exactly as before while the whole history fits in 48 MiB. A longer history is refused with `errorCode: "response_too_large"` instead of an answer that would close the connection; read it in pages.

**Tail pages** (capability `entries_tail`). Pass `tail` (a positive integer) to read the NEWEST entries first: the answer holds the newest `tail` entries of the range, in append order, under the same `maxBytes` rule (8 MiB when only `tail` is given, capped at 48 MiB), and always at least the newest one. While older entries remain it carries `hasMore: true` and `next_before`, the id of the oldest entry it returned; ask again with `before: next_before` to walk back until `hasMore` is `false`. `before` (an entry id) limits any read to entries strictly before it; an id that names no entry is refused with `errorCode: "not_found"`. `since` is unchanged, and `since` and `before` may bound one range together. `tail` and `limit` cannot be combined (`invalid_argument`): `limit` pages forward from the range's start, `tail` backward from its end.

```json
{"type": "get_entries", "tail": 200, "observe": true}
{"type": "get_entries", "tail": 200, "before": "<next_before>", "observe": true}
```

`get_entries` and `get_state` may carry `observe: true`: on a host such a read never counts as an attachment (see the idle-exit window).

A single entry larger than 48 MiB cannot travel in any answer, so a read whose next entry is that large (paged or not) is refused with `response_too_large` naming the entry. While a walk has more pages, the host keeps the session's full history in memory for the next page; it lets it go 30 s after the last page request, so a client that stops mid-walk does not pin the history.

#### get_tree

Get the session as a tree of entries. Each node is `{entry, children, label?, labelTimestamp?}`. A well-formed session has a single root; orphaned entries (broken parent chain) also appear as roots.

```json
{"type": "get_tree"}
```

Response:
```json
{
  "type": "response",
  "command": "get_tree",
  "success": true,
  "data": {
    "tree": [
      {
        "entry": {"type": "message", "id": "abc123", "parentId": null, "...": "..."},
        "children": [
          {"entry": {"type": "message", "id": "def456", "parentId": "abc123", "...": "..."}, "children": []}
        ]
      }
    ],
    "leafId": "def456"
  }
}
```

#### get_last_assistant_text

Get the text content of the last assistant message.

```json
{"type": "get_last_assistant_text"}
```

Response:
```json
{
  "type": "response",
  "command": "get_last_assistant_text",
  "success": true,
  "data": {"text": "The assistant's response..."}
}
```

Returns `{"text": null}` if no assistant messages exist.

#### set_session_name

Set a display name for the current session. The name appears in session listings and helps identify sessions.

```json
{"type": "set_session_name", "name": "my-feature-work"}
```

Response:
```json
{
  "type": "response",
  "command": "set_session_name",
  "success": true
}
```

The current session name is available via `get_state` in the `sessionName` field. To set the initial name when starting RPC mode, pass `--name <name>` or `-n <name>` to the `senpi --mode rpc` process.

#### set_session_archived

Archive or unarchive the session (method class `drive`). The flag is written into the session file as a `custom` entry (`customType: "session_archived"`, `data: { archived, sessionId }`), so every surface that reads the file (the desktop app, the CLI, the terminal, a relay listing on another device) sees the same value; the newest such entry wins and a session without one is not archived. Archiving changes nothing else: the session stays open, listed and drivable.

An entry counts only for the session id it names. A fork or clone (`fork`, `clone`, `move_session` `op: "copy"`, `senpi --fork`) is a new thread under a new id: it copies the source's entries but starts unarchived, while the source keeps its flag. Reopening or moving a session keeps its id, so it keeps its flag. Reading the flag never loads the session's history: the host keeps it current as entries are appended, so listing an idle compacted session leaves its trimmed history on disk.

```json
{"type": "set_session_archived", "sessionId": "rpc-1", "archived": true}
```

Response:
```json
{
  "type": "response",
  "command": "set_session_archived",
  "success": true
}
```

Every attached connection then receives `session_archived_changed { archived }`, and every matching `subscribe_sessions` subscriber, attached or not, receives a `session_status` with `archived` set and `lastChange.cause: "archive"`. `list_sessions` reports the flag on each row as `archived`. Like every custom entry, the flag reaches the file with the session's next persisted write: a session that has never had a message stays unsaved, so its flag lasts only as long as the session is open.

#### set_session_settled

Mark the session Done, or reopen it (method class `drive`). The flag is written into the session file as a `custom` entry (`customType: "session_settled"`, `data: { settled, by?, at, sessionId }`, `at` an ISO timestamp), so every surface that reads the file sees the same value; the newest such entry wins and a session without one is not settled. Done is a flag, not a state: the session stays open, listed and drivable, and Done does not hide it.

`by` says how the session reached Done. It is one of `{ kind: "user" }`, `{ kind: "agent", threadId?, threadTitle? }`, `{ kind: "pr-merged", pullRequestNumber? }`, `{ kind: "pr-closed", pullRequestNumber? }` or `{ kind: "inactivity", days }` (the desktop app's `ThreadSettledBy`): `pullRequestNumber` is an integer of at least 1, `days` an integer of at least 0, and `threadId` and `threadTitle` non-empty strings, stored trimmed; fields a kind does not carry are dropped. An unknown kind or a malformed field is refused with `invalid_argument`, and nothing is written. `by` is optional, and it is ignored when `settled` is false.

As with `set_session_archived`, an entry counts only for the session id it names: a fork or clone starts not settled while the source keeps its flag, a reopen or move keeps it, and reading it never loads the session's history.

```json
{"type": "set_session_settled", "sessionId": "rpc-1", "settled": true, "by": {"kind": "pr-merged", "pullRequestNumber": 42}}
```

Response:
```json
{
  "type": "response",
  "command": "set_session_settled",
  "success": true
}
```

Every attached connection then receives `session_settled_changed { settled, settledBy? }`, and every matching `subscribe_sessions` subscriber, attached or not, receives a `session_status` with `settled` (and `settledBy`) set and `lastChange.cause: "settle"`. `list_sessions` reports the flag on each row as `settled` and `settledBy`. Like every custom entry, the flag reaches the file with the session's next persisted write.

#### record_user_activity

Reports that the user started typing a draft in this session's composer (capability `user_activity`). It feeds the same first-activity signal the interactive editor sends, so a session with prompt-cache keep-alive enabled and an eligible model warms the first turn's prefix once while the user is still typing. Repeated reports are no-ops after the first, and nothing is sent to a provider when keep-alive is disabled or the model is ineligible. Only `kind: "draft"` is accepted: prompt activity is recorded by the prompt itself, and any other kind is refused with `invalid_argument` and the fixed message `record_user_activity: kind must be "draft"` (the refusal never repeats the value the client sent). On a multi-session host the command is session-scoped and passes the session-writer guard, so a session held by another writer answers `session_held`. It requires the connection to be attached to the session, as every session command does (see Attachment admission).

```json
{"type": "record_user_activity", "sessionId": "rpc-1", "kind": "draft"}
```

Response:
```json
{
  "type": "response",
  "command": "record_user_activity",
  "success": true
}
```

#### wake

Runs the session's registered inbox drain once (multi-session hosts: session-scoped; terminal control endpoints: the endpoint's one session). See "Waking a host session (`wake`)".

```json
{"type": "wake", "sessionId": "rpc-1", "delivery_ids": ["d2"]}
```

Response:
```json
{
  "type": "response",
  "command": "wake",
  "success": true,
  "data": { "admitted": [{ "delivery_id": "d2", "kind": "started" }] }
}
```

`kind` is the admission outcome (`started`, `queued`, `steered`, `already_admitted`, `held_draft`, `held`, `turn_conflict`); `admitted` is `[]` when no drain is registered.

#### admit_external_message

Admits a message another agent sent this session (a relayed peer delivery) exactly as `pi.session.admitExternalMessage` does in process (multi-session hosts: session-scoped). The engine writes its own `session_control_delivery` custom entry, with `details.sender` and `details.display_text` for human surfaces: never a `role: "user"` message, never the extension `input` event, and a `/`-led `text` is not dispatched as a command or expanded as a template. Method class `drive`.

```json
{"type": "admit_external_message", "sessionId": "rpc-1", "deliveryId": "d7", "text": "[from peer] build is green", "sender": {"kind": "agent", "session_id": "s-42", "name": "reviewer"}, "displayText": "build is green", "deliverAs": "followUp"}
```

Response:
```json
{
  "type": "response",
  "command": "admit_external_message",
  "success": true,
  "data": { "kind": "started", "turnId": "0" }
}
```

- `deliveryId` (1-256 chars), `text` (non-empty) and `deliverAs` (`steer` | `followUp`) are required. `sender` is `{ kind: "agent", session_id, name? }`, `{ kind: "command_line", user? }` or `{ kind: "external", platform, author? }` with no other field.
- `whenIdle`: `start` (default) starts a turn on an idle session; `queue` holds it for the next turn.
- `expectedTurnId` is `get_state.currentTurnId` (a string). A steer whose `expectedTurnId` is not the current turn, or a mid-turn steer that names none, answers `kind: "turn_conflict"` and admits nothing. The reply's `turnId` is the session's turn at admission, in the same form.
- `chainCount` is a thread call's hop count, checked against `threads.chainCountLimit` before anything is admitted (refused with `chain_count_limit` / `invalid_chain_count`, as on `prompt`/`steer`/`follow_up`); the admitted hop is written as `details.chain_count`.
- `kind` is the same outcome `wake` reports (`held_draft`: retry; nothing was queued). `held` (senpi#6490): the session is idle under a hold a peer cannot release (a person's Stop, an interrupted run, a parent's run hold); the delivery is kept as a held notice and starts once that hold is released, and `holds` lists the hold kinds, for example `{ "kind": "held", "turnId": "0", "holds": ["session_hold"] }`. An `unattended` hold alone is released by the delivery, which answers `started`. A caller that predates `held` must treat it as neither success nor a refusal to retry: the delivery is admitted and waits on that device for its person. The ledger keys a local connection's `deliveryId` as `rpc:local/<deliveryId>` and a remote device's as `device:<deviceId>/<deliveryId>`, so RPC ids never collide with in-process deliveries or with another device's. An id the runtime already holds, or that the transcript already holds an entry for (after a restart too), answers `already_admitted`.
- On a connection that speaks for a remote device (a delegated connection, or one whose `set_client_info` declared `remoteOrigin`), the engine stamps that device as `details.remote_origin` and writes `text` unchanged, so the model reads exactly what a delivery on a local connection carries and no device (senpi#6250). It keeps `text` as `details.display_text` when no `displayText` is given, and refuses a `command_line` sender (`sender_not_allowed`). A delegated connection that names no remote device is refused (`delegated_origin_unknown`), never admitted as a local delivery. A record that names `remote_origin` is refused on every connection. The turn that consumes the delivery takes the connection's origin, so a remote device's follow-up runs under the delegated approval-mode rule even inside a local turn.
- Once `release_session` has closed the session's admission, the record answers `success: false` with the release's message: the delivery stays with its sender.

#### release_session

Multi-session hosts only. Hands the session to a runtime outside the host; see "Handing a session over (`release_session`)".

```json
{"type": "release_session", "sessionId": "rpc-1", "reason": "takeover"}
```

Response:
```json
{
  "type": "response",
  "command": "release_session",
  "success": true,
  "data": {
    "released": true,
    "session_path": "/path/to/session.jsonl",
    "attachments": 0,
    "dropped": { "deliveries": [], "user_messages": [] }
  }
}
```

`dropped` is non-empty only after `"interrupt": true` took queued input out of the session: redeliver the ids in `deliveries` to the next owner, and hand `user_messages` to the adopting client, which decides what to do with them (for example, resubmit them in order as queued prompts).

Refusals carry `error` = `turn_active` or `session_busy` with `errorData.busy` (pass `"interrupt": true` to abort the work first), `attached` with `errorData.attachments` (pass `"force": true`), `invalid_release_reason`, `release_unsupported`, `release_failed` (`errorData.detail`; the session stays hosted when its entry could not be written), `host_draining`, `session_closing` or `unknown_session`.

#### find_session

Which session file of this host carries a durable session id, for a client whose session is closed and unlisted.

```json
{"type":"find_session","durableSessionId":"0197…"}
```

Every other command that takes a durable id works on a session the host still has open: `list_sessions` lists what is open, `claim_session` consumes a ready park, `resume_session` is the pause and resume of a user Stop, and `open_session` needs the path. A client that binds a thread to a session on another machine keeps the routing key and the durable id, not the path, so when that session closes (a move given back after its release leaves the file writable and the session not open) the key names nothing and there is no path to reopen by. This answers that path.

`data` is exactly one of:

```json
{"found":{"sessionPath":"/abs/sessions/--folder--/<file>.jsonl","cwd":"/abs/folder/the/header/names","open":false}}
{"ambiguous":true}
{"unknown":true}
```

`open` says an engine of this host holds that session now, so a client knows whether its next step is an `open_session` or an attach. `ambiguous` is the answer when two session files carry one durable id (a caller-minted id reused while the first was parked); it names neither, and the client picks by another means. `unknown` is the answer when no session file of this host carries it.

The command is a read: it opens, claims, unloads, seals and rewrites nothing, and touches no move record. It reads only this host's own session folder (`<agentDir>/sessions/<folder>/`), never a path from the request, which carries the durable id alone. Of each session file only the first line, its header, is read.

It needs the standing a path-naming `open_session` needs, so on a delegated connection it needs `device_admin`. A caller without that standing is refused before the lookup runs, and the refusal is the same for an id this host knows and one it does not, so it learns nothing either way.

It is bounded: a host holding more than 20,000 session files answers `find_session_too_many` instead of a partial answer, and no file is read before that bound is decided. A `durableSessionId` that is missing, empty or not a string is `invalid_argument`. Every host this package starts keeps an agent directory, whichever runtime its sessions use, so all of them answer `find_session`, a host that runs its sessions in workers included. `find_session_unsupported` remains for a host built with no agent directory at all; no host this package starts answers it.

After a `found`, open the session with `open_session { sessionPath, cwd }` and compare the answer's `state.sessionId` with the durable id before binding to it: the id is the proof, the path only a hint.

#### detach_connection

Multi-session hosts that advertise the `detach_connection` capability only. Meant as a connection's last request before it closes: the host releases every session attachment this connection holds and answers only after that, so another connection's next `list_sessions` no longer counts it. Closing the socket afterwards releases nothing more. The host does not refuse later requests on the connection; a later `open_session` attaches as usual.

```json
{"type": "detach_connection"}
```

Response:
```json
{"type": "response", "command": "detach_connection", "success": true, "data": {"deferred": []}}
```

`deferred` lists the sessions that still count this connection when the answer is sent:

- a session that is not retained, whose turn is still running, and of which this connection holds the last attachment. Releasing it would end the session and abort the turn, so the attachment is released when the turn settles.
- every session the connection holds while the host is draining; the drain releases them once their work settles.

While another attachment remains on a session, this connection's attachment is released before the answer, even mid-turn. The same applies when a connection simply closes.

`senpi host session` sends it before closing and waits at most 5 s; when no answer comes it prints one line and closes anyway. Against a host that does not advertise the capability it sends nothing and relies on the release at socket close.

### Commands

#### get_commands

Get the ordered command surface (extension commands, prompt templates, and skills). Extension and prompt rows are
invoked through `prompt` with `/name`; skill rows use `$name` or the compatibility form `/skill:name`.

```json
{"type": "get_commands"}
```

Response:
```json
{
  "type": "response",
  "command": "get_commands",
  "success": true,
  "data": {
    "commands": [
      {"name": "session-name", "description": "Set or clear session name", "source": "extension", "syntax": "slash", "sourceInfo": {"path": "/home/user/.senpi/agent/extensions/session.ts", "source": "auto", "scope": "user", "origin": "top-level"}},
      {"name": "fix-tests", "description": "Fix failing tests", "source": "prompt", "syntax": "slash", "sourceInfo": {"path": "/home/user/myproject/.senpi/prompts/fix-tests.md", "source": "auto", "scope": "project", "origin": "top-level"}},
      {"name": "skill:brave-search", "description": "Web search via Brave API", "source": "skill", "syntax": "dollar", "sourceInfo": {"path": "/home/user/.senpi/agent/skills/brave-search/SKILL.md", "source": "auto", "scope": "user", "origin": "top-level"}}
    ]
  }
}
```

Each command has:
- `name`: Command identity without its leading invocation marker
- `description`: Human-readable description (optional for extension commands)
- `syntax`: Canonical marker clients should insert (`"slash"` for extension/prompt rows, `"dollar"` for skills)
- `source`: What kind of command:
  - `"extension"`: Registered via `pi.registerCommand()` in an extension
  - `"prompt"`: Loaded from a prompt template `.md` file
  - `"skill"`: Loaded from a skill directory (name is prefixed with `skill:`)
- `sourceInfo`: Provenance metadata for the owning resource (present for all sources, including extensions):
  - `path`: Absolute file path to the command source
  - `source`: Source identifier string (for example `"auto"` for auto-discovered locations, `"local"` for settings entries, `"cli"` for CLI paths, `"builtin"`, `"sdk"`, or a package source)
  - `scope`: `"user"`, `"project"`, `"temporary"`, or `"system"` (harness-provided: builtin and bundled extensions, command-line packages declaring `pi.system`, and what they contribute)
  - `origin`: `"package"` or `"top-level"`
  - `baseDir`: Base directory of the owning resource (optional)

**Note**: Built-in TUI commands (`/settings`, `/hotkeys`, etc.) are not included. They are handled only in interactive mode and would not execute if sent via `prompt`.

#### get_loaded_surfaces

Get the extensions and MCP servers loaded by the active runtime. Skills remain available through `get_commands`, where each loaded skill is represented by one `source: "skill"` row.

An MCP server with a failed configuration reference reports `status: "degraded"`
and an optional `lastError` naming the field and failure reason, never the resolved
value. Other connection diagnostics also use `lastError` when present.
Every resolved reference value is treated as sensitive and redacted from outbound
text, even non-secret values such as paths and values from earlier rotations.
Values shorter than four characters are not redacted. Structured snapshots retain
their keys, numbers, booleans, nulls and array/object shape; redaction changes only
string values. For MCP secrets use `env.*` or `headers`, not `args[]`, whose
resolved values are visible in the server's process list.

```json
{"type": "get_loaded_surfaces"}
```

Response:

```json
{
  "type": "response",
  "command": "get_loaded_surfaces",
  "success": true,
  "data": {
    "extensions": [
      {
        "name": "my-extension",
        "path": "/home/user/.senpi/agent/extensions/my-extension.ts",
        "sourceInfo": {
          "path": "/home/user/.senpi/agent/extensions/my-extension.ts",
          "source": "auto",
          "scope": "user",
          "origin": "top-level"
        },
        "enabled": true
      }
    ],
    "mcpServers": [
      {
        "name": "filesystem",
        "toolCount": 12,
        "status": "connected",
        "authStatus": "unsupported"
      }
    ]
  }
}
```

Extension rows come directly from the session's loaded resource inventory, not from registered slash commands. A commandless extension therefore appears once, and an extension registering several commands is not duplicated. MCP rows come from the live session-owned MCP service and expose its current server state, listed tool count, and non-secret auth status.

In multi-session mode this is a session-scoped command and requires the routing `sessionId`.

### Workspace trust and project settings

A project folder's settings file, skills, prompt templates, extensions, themes and MCP servers load only when the
project is trusted. The terminal asks when a session opens; an RPC session is never asked, so it stays untrusted
until a client saves a decision with `set_project_trust`. These four commands act on the routed session's working
directory (in multi-session mode each requires the routing `sessionId`) and use the same storage and rules as
the terminal: the device's `trust.json` and the project's own settings file.

#### get_project_trust

```json
{"type": "get_project_trust"}
```

```json
{
  "type": "response",
  "command": "get_project_trust",
  "success": true,
  "data": {
    "cwd": "/home/user/project",
    "projectTrusted": false,
    "requiresTrust": true,
    "saved": null,
    "locked": false,
    "choices": [
      { "choice": "trust", "label": "Trust", "trusted": true, "path": "/home/user/project" },
      { "choice": "trust_parent", "label": "Trust parent folder (/home/user)", "trusted": true, "path": "/home/user" },
      { "choice": "do_not_trust", "label": "Do not trust", "trusted": false, "path": "/home/user/project" }
    ]
  }
}
```

- `projectTrusted`: whether this session runs with the project trusted now. (`get_state.projectTrusted` reports
  only a decision saved for the folder itself.)
- `requiresTrust`: whether the folder has anything trust gates; a folder without such files counts as trusted.
- `saved`: the nearest decision saved at or above the folder, or `null`.
- `locked`: the engine was launched with `--approve` or `--no-approve`; that flag outranks every saved decision,
  so `set_project_trust` is refused.
- `choices`: exactly the choices the terminal's `/trust` command offers. `set_project_trust` also takes
  `no_inherit`, which is never listed here.

#### set_project_trust

Saves one of the `/trust` choices and applies it to the session at once: project resources load (or unload)
as they would on `reload`, and the next session opened in the folder gets the same decision. It is never
implied by `open_session` or by a permission preset; only this explicit request saves a decision.

```json
{"type": "set_project_trust", "choice": "trust", "expectedCwd": "/home/me/project"}
```

`expectedCwd` is optional, as on every project write: see [The folder a project write is for](#the-folder-a-project-write-is-for). `choice` is `trust` (this folder), `trust_parent` (the parent folder; clears this folder's own entry, as `/trust`
does), `do_not_trust`, or `no_inherit`. The response carries the same `data` as `get_project_trust`, read after the change.

`no_inherit` is for clients, not people, and `get_project_trust` never lists it: it saves an explicit `null` for the
folder in `trust.json`, an entry that holds no decision. The folder then inherits no decision from a folder above it or,
for a linked git worktree, from its main checkout, so it is decided as if nothing were saved: a Full access session
trusts it, and a session that may ask asks; an answer the host process gave the folder before the entry was
saved does not apply either. `saved` reads `null` afterwards. It never adds trust to the session it is
sent in: a trust that came only from Full access stays, any other trust goes, unless a `project_trust` handler decides
the folder is trusted (that handler is not overruled, so it never refuses `no_inherit`). An engine older than this
answers `invalid_argument`, and reads such an entry as no entry at all, so the folder inherits there as before.
A later `trust`, `trust_parent` or `do_not_trust` replaces the entry.
Errors: `invalid_argument` for an unknown choice or an `expectedCwd` that is not a string, `project_cwd_mismatch` when `expectedCwd` names another folder than the session's (nothing is saved or applied), `project_trust_locked` when the launch named the trust, and
`project_trust_extension_decided` when a `project_trust` handler of an extension loaded before trust (never a
project extension) decides the other way: such a handler decides before any saved choice when a session opens, so
the request is refused and nothing is saved or applied. A folder with nothing trust gates stays trusted whatever is
chosen.

#### get_project_settings

Reads the project settings file as stored. Reading runs nothing, so it works while the project is untrusted.

```json
{"type": "get_project_settings"}
```

```json
{
  "type": "response",
  "command": "get_project_settings",
  "success": true,
  "data": {
    "cwd": "/home/user/project",
    "path": "/home/user/project/.senpi/settings.json",
    "exists": true,
    "projectTrusted": true,
    "settings": { "defaultThinkingLevel": "high" },
    "error": null
  }
}
```

`settings` is `null` when the file does not exist or does not parse; `error` then names the parse failure.

#### set_project_setting

Writes one top-level key of the project settings file through the same locked, merge-on-write path the
terminal's project setters use; `"value": null` removes the key. The value is stored as given, like an edit to
the file: values the session reads when it starts (default model and thinking level, steering and follow-up
modes) apply after `reload` or in the next session.

```json
{"type": "set_project_setting", "key": "defaultThinkingLevel", "value": "high", "expectedCwd": "/home/me/project"}
```

The response carries the same `data` as `get_project_settings`, read after the write. Errors:
`invalid_argument` when `key` is not an identifier (`[A-Za-z][A-Za-z0-9_]*`), `value` is missing or `expectedCwd` is
not a string, `project_cwd_mismatch` when `expectedCwd` names another folder (nothing is written),
`project_not_trusted` while the project is untrusted (trust it first), `project_settings_unreadable` when the
existing file does not parse (nothing is written), and `project_settings_write_failed` when writing the file fails
(permissions, a held lock).

`get_project_trust` is an `observe` read; `set_project_trust`, `get_project_settings` and `set_project_setting`
are `device_admin` (a saved trust decision decides whether project code runs on the device, and the settings
commands read and write a file in the session's folder).

#### read_project_file

Reads one of the workspace's project files: `AGENTS.md` or `CLAUDE.md` at the session's folder or in any folder
below it, a file under `.omo/rules/`, or the folder's OmO config `.omo/omo.jsonc` (per-agent and per-category model
routing; at the folder itself only). Reading runs nothing, so it works while the project is untrusted.

```json
{"type": "read_project_file", "path": "AGENTS.md"}
```

```json
{
  "type": "response",
  "command": "read_project_file",
  "success": true,
  "data": {
    "cwd": "/home/user/project",
    "path": "AGENTS.md",
    "exists": true,
    "content": "# Project rules\n",
    "etag": "sha256-…",
    "projectTrusted": true
  }
}
```

`path` is relative to the session's folder, `/`-separated and canonical: no empty, `.` or `..` segment, no `\\`, `:`
or NUL, and never through `.git` or `node_modules`. A file that does not exist yet is a success with `exists: false`
and `content`/`etag` `null`. `etag` is an opaque version of the stored bytes: compare it, never parse it.
Errors: `invalid_argument` when `path` is not a string, `project_file_not_allowed` (`errorData: { path, reason }`):
`reason` is `not_listed` for any other path and `unsafe` when a folder on the way or the file itself is a symlink or
not a regular file and folder (an engine before `.omo/omo.jsonc` was listed sends no `reason`), and
`project_file_too_large` (`errorData: { limitBytes }`) for a stored file over 512 KiB.

#### The folder a project write is for

`set_project_trust`, `set_project_setting`, `write_project_file`, `set_project_mcp_servers` and
`write_project_skill_file` take an optional `expectedCwd`: the folder the
caller means. A client that reaches a session by a key that can since name another session (a remote desktop, through
a relay) states it, so the write lands only in that folder's project. When it is given and the session's working
directory is another folder, the write is refused with `project_cwd_mismatch` and nothing is written or applied. Both
paths are compared with only trailing separators of the path's own style dropped (`/` for a POSIX path; `\` or `/`
for a drive or UNC path) and a Windows drive letter in either case; nothing is trimmed and the rest of the path is
compared as written. A present `expectedCwd` that is not a string is refused with `invalid_argument`. Without it, a
write behaves as before.

#### write_project_file

Replaces (or creates) one of the files `read_project_file` reads, naming the version it replaces.

```json
{"type": "write_project_file", "path": "AGENTS.md", "content": "# Project rules\n", "ifEtag": "sha256-…", "expectedCwd": "/home/me/project"}
```

`ifEtag` is required: the `etag` last read, or `null` to create a file that must not exist yet. Missing parent
folders are created. The file lands by a temporary file and a rename, so a reader never sees a partial write, and
writes to one file are applied one at a time. The response carries the same `data` as `read_project_file`, read
after the write. The session reads its instruction files when they are next loaded (a new session or `reload`).
Errors: `invalid_argument` when `content` is not a string, `ifEtag` is neither a string nor `null`, or `expectedCwd` is
not a string, `project_cwd_mismatch` when `expectedCwd` names another folder (nothing is written),
`project_not_trusted` while the project is untrusted (read again when the write commits),
`project_file_permission_denied` when this machine's own permission rules for an edit of that path refuse it (the same
decision the write tool gets), `project_file_not_allowed` as for `read_project_file`,
`project_file_too_large` (`errorData: { limitBytes }`) for content over 512 KiB or a stored file over 512 KiB (its
version cannot be checked without reading it), `project_file_conflict` when
`ifEtag` is not the file's current version (`errorData: { currentEtag, exists }`; nothing is written; read again
and retry), and `project_file_write_failed` when the write fails (permissions, disk).

Both are `device_admin`: they read and write a file in the session's folder.

#### get_project_mcp_servers

Reads the session folder's project MCP file (`.omo/mcp.json`) as stored.
Reading runs nothing, so it works while the project is untrusted.

```json
{"type": "get_project_mcp_servers"}
```

```json
{
  "type": "response",
  "command": "get_project_mcp_servers",
  "success": true,
  "data": {
    "cwd": "/home/user/project",
    "path": ".omo/mcp.json",
    "exists": true,
    "mcpServers": { "docs": { "command": "docs-mcp" } },
    "parseError": null,
    "etag": "sha256-…",
    "projectTrusted": true
  }
}
```

`mcpServers` holds the entries as stored (placeholders unexpanded); it is `null` when the file is missing or does
not parse. `parseError` says why a stored file does not parse (not JSON, not a JSON object, or `mcpServers` not an
object). Errors: `project_file_not_allowed` when the config folder or the file is a symlink or not a regular
file and folder, and `project_file_too_large` for a stored file over 512 KiB.

#### set_project_mcp_servers

Edits the servers of the project MCP file in one write, naming the version it replaces.

```json
{"type": "set_project_mcp_servers", "patch": {"old": null, "new": {"command": "docs-mcp"}}, "ifEtag": "sha256-…"}
```

The merge is one level deep: each `patch` entry replaces the server of that name, `null` removes it, and every other
server and top-level key stays as stored, so a rename is one atomic write. The merged file is checked with the
engine's own MCP config loader before anything is written. The write needs the folder to be trusted at the moment it
commits and gets the same permission decision a `write` of that file gets in the session (rules, preset, saved
answers, or a prompt). In an RPC session that prompt goes to the session's client, as it does for the session's own
`write` tool, so the client that sent the write answers it. The response carries the same `data` as
`get_project_mcp_servers`, read after the write.
Errors: `invalid_argument` when `patch` is not an object, `ifEtag` is neither a string nor `null`, or `expectedCwd`
is not a string, `project_cwd_mismatch` when `expectedCwd` names another folder (nothing is written),
`project_not_trusted`, `project_file_conflict` (`errorData: { currentEtag, exists }`),
`project_mcp_config_unparseable` (`errorData: { parseError }`; a file that does not parse is never written over),
`project_mcp_config_invalid` when the loader rejects the merged file, `project_file_permission_denied`,
`project_file_not_allowed`, `project_file_too_large`, and `project_file_write_failed`.

#### read_project_skill_file

Read the file of a skill the engine lists for the session, by skill name.

```json
{"type": "read_project_skill_file", "skill": "deploy"}
```

#### write_project_skill_file

Replace the file of a skill the engine lists for the session, by skill name. `ifEtag` is the `etag` the last read
answered.

```json
{"type": "write_project_skill_file", "skill": "deploy", "content": "---\nname: deploy\n…", "ifEtag": "sha256-…"}
```

For both, `data` is `{ cwd, skill, path, exists, content, etag, projectTrusted }`, with `path` relative to the session's folder.
Only a listed skill whose file lies inside the session's folder is reachable; a skill that lives elsewhere (a global
skill, also when the agent's directory lies inside the session's folder) or is reached through a folder link or a
file link is refused. A write passes the same trust and permission
gates as `set_project_mcp_servers` and answers the read after it. Errors: `project_skill_not_listed`
(`errorData: { skill }`), `project_file_not_allowed`, `invalid_argument`, `project_cwd_mismatch` (a write whose
`expectedCwd` names another folder), `project_not_trusted`,
`project_file_conflict`, `project_file_permission_denied`, `project_file_too_large`, and
`project_file_write_failed`.

All four are `device_admin`: they read and write files in the session's folder.

#### read_user_skill_file

Read the file of a user-global skill the engine lists for the session (one in the agent directory's `skills` folder
or in `~/.agents/skills`), by skill name. The same verb serves this machine and another device of the account.

```json
{"type": "read_user_skill_file", "skill": "deploy"}
```

#### write_user_skill_file

Replace the file of a user-global skill the engine lists for the session, by skill name. `ifEtag` is the `etag` the
last read answered.

```json
{"type": "write_user_skill_file", "skill": "deploy", "content": "---\nname: deploy\n…", "ifEtag": "sha256-…"}
```

`data` is `{ skill, path, exists, content, etag }`, with `path` the file's real absolute path. The file must lie inside
a user skills folder, taken from that folder's real path and resolved without following any link; a skill outside,
behind a link or reached through `..` is refused with `user_skill_file_not_allowed`.

A write from this machine's own connection commits at once. A write from a connection that speaks for another
device (a delegated connection, or one that declared `remoteOrigin`) commits only after someone on this machine
approves it: the engine asks the session's local grant presentation (an attached local client with `grant_select`,
never a remote or delegated connection), and the question names the origin device, the file's path and the diff
of the change (the whole content for a new file). The choices are "Allow this change" and "Deny"; there is no
"always". Every write attempt from another device appends exactly one line to
`<agentDir>/audit/user-skill-writes.jsonl`: `{ at, originDeviceId, originDeviceName?, path, sha256Before,
sha256After, decision, reason? }` with `decision` one of `approved`, `denied`, `unconfirmed`, or `refused` for an
attempt refused before the question (`reason` is its error code; `path` and the hashes are `null` unless the file
was located inside a user skills folder). An audit line that cannot be written never changes the write's outcome:
the answer carries `auditError` beside it (in `data` on success, in `errorData` on a refusal). A connection that
speaks for another device never presents or answers this question (nor any grant select), on the in-process and the
worker session runtime alike, even when it advertises `grant_select`.

Errors: `user_skill_not_listed` (`errorData: { skill }`), `user_skill_file_not_allowed`, `user_skill_write_declined`
(denied on this machine), `user_skill_write_unconfirmed` (no local presenter, or no answer within 120 s),
`project_file_conflict` (`errorData: { currentEtag, exists }`), `project_file_too_large`, `project_file_write_failed`,
and `invalid_argument`. Both are `device_admin`.

### extension_request

Invoke a request handler registered by an extension through `pi.rpc.handle(name, handler)`:

```json
{
  "id": "req-42",
  "type": "extension_request",
  "name": "acme.job.cancel",
  "data": {
    "jobId": "job-42"
  }
}
```

Success returns the extension-owned structured value:

```json
{
  "id": "req-42",
  "type": "response",
  "command": "extension_request",
  "success": true,
  "data": {
    "cancelled": true
  }
}
```

The request `name` must resolve to exactly one handler in the active extension generation.
Unknown names, duplicate names, stale generations, handler failures, and empty names return the
normal `{ type: "response", success: false, error }` envelope. Senpi treats request and response
data as opaque; the owning extension and client must validate their payloads.

In multi-session mode this command requires the owning routing `sessionId`. The response receives
the same `sessionId`, and another session's extension handlers are never consulted.

## Events

Events are streamed to stdout as JSON lines during agent operation. Events do not generally include an `id` field; `bash_execution_update` includes the `id` of its originating `bash` command when one was provided.

### Event Types

| Event | Description |
|-------|-------------|
| `agent_start` | Agent begins processing |
| `agent_end` | One low-level agent run completes (may still be followed by retry, compaction, or queued continuations) |
| `agent_settled` | Agent run is fully settled; no automatic retry, compaction retry, or queued continuation remains. Extension `agent_settled` handlers may still be running: wait for `agent_idle` before tearing a session down |
| `turn_start` | New turn begins |
| `turn_end` | Turn completes (includes assistant message and tool results) |
| `message_start` | Message begins |
| `message_update` | Streaming update (text/thinking/toolcall deltas) |
| `message_end` | Message completes |
| `entry_appended` | A durable session entry was appended, including goal and engine self-stop custom entries |
| `bash_execution_update` | Direct RPC bash command output chunk |
| `tool_execution_start` | Tool begins execution |
| `tool_execution_update` | Tool execution progress (streaming output) |
| `tool_execution_end` | Tool completes |
| `tool_barrier_waiting` | A workspace-changing tool call started waiting on the turn's tool barrier (`id`, `toolCallId`, `toolName`) |
| `tool_barrier_expired` | The tool barrier's `deadlineMs` passed before a release; it opened by itself (`id`, `deadlineMs`) |
| `queue_update` | Pending steering/follow-up queue changed |
| `compaction_start` | Compaction begins |
| `compaction_end` | Compaction completes |
| `auto_retry_start` | Auto-retry begins (after transient error) |
| `auto_retry_end` | Auto-retry completes (success or final failure) |
| `retry_fallback_exhausted` | Every model in the fallback chain failed this turn (`chainKey`, `lastError`, optional `primaryError`, `failures`) |
| `summarization_retry_scheduled` | Retry scheduled for a transient compaction or branch-summary summarization error |
| `summarization_retry_attempt_start` | Retried summarization request starts |
| `summarization_retry_finished` | Summarization retry loop completes |
| `extension_error` | Extension threw an error |
| `transcript_write_failed` | The session file refused a message of the running turn (`role`, `errorMessage`) |
| `extension_event` | Capability-gated extension-owned event (`extension_events` clients only) |
| `commands_changed` | Ordered command/skill candidate snapshot changed |
| `session_recovered` | An interrupted write (a full disk) left the session file's last record incomplete; it was set aside (`cause`, `backupPath`, `droppedBytes`, `notice`) |
| `command_invocation` | Accepted extension-command or prompt-template invocation metadata |
| `skill_invocation` | Ordered explicit skill metadata after prompt expansion |
| `loaded_surfaces_changed` | Loaded skills, extensions, or MCP inventory changed; re-read `get_commands` and `get_loaded_surfaces` |
| `model_changed` | Active model changed (any source), with the thinking level in force afterwards |
| `model_change_cancelled` | A held model switch ended without applying: `origin` carries its source and optional `effectId`, `reason` is `superseded`, `context-budget` or `error`, and optional `detail` describes the failure |
| `service_tier_changed` | Effective service tier or fast-mode state changed |
| `session_closed` | Multi-session host: a routing handle ended. Optional `reason`: `client_close`, `idle_evicted`, `host_shutdown`, `replaced`, `handoff_parked`, `session_dir_removed`, `error` |
| `session_parked` | Multi-session host: a retained session was released to disk at the idle window (`sessionId`, `sessionPath`). Replaces `session_closed` for that handle |
| `session_released` | Headless engine: a quiet takeover let this connection go (`sessionId`, `reason: "taken_over"`); the session runs on for its new holder. Sent to that connection only |
| `host_stalled` | Multi-session host: the event loop was blocked past `SENPI_RPC_LOOP_LAG_ERROR_MS`, with the drift and the session/tool blamed for it |
| `host_memory_pressure` | Multi-session host: the memory footprint is above `SENPI_RPC_HOST_RSS_WARN_MB`, with RSS beside it and the live session count |
| `subscription_limits` | A subscription account reported new limit windows: `{ provider, account, windows, reportedAt }`, the same shape as one `get_subscription_limits` account; every connection hears it once per report |
| `host_trimmed` | Multi-session host: it collected (at zero sessions, or at 2 GB+ after a session-count drop), with the footprint before and after, the sessions still open and the pause |
| `session_opened` | Multi-session host: a session was created on this host (`sessionId`, `durableSessionId`, `sessionPath`, `kind`, `cwd`); a worker's reaches only attached connections and `subscribe_sessions` subscribers with `include_workers` |
| `session_status` | Multi-session host: a `subscribe_sessions` subscription's per-session status change; see [Session status stream](#session-status-stream-subscribe_sessions) |
| `session_closed` | Multi-session host: a routing handle ended, with an optional `reason` (`handoff_parked` = a generation handoff put the session back on disk; reopen it by `sessionPath`) |
| `session_parked` | Multi-session host: a retained session's handle was released while the session itself stays on disk (`{ sessionId, sessionPath }`); reopen it with `open_session { sessionPath }` |
| `session_replaced` | The live session was swapped by `new_session`, `switch_session` or `fork`, carrying the new `durableSessionId` |

Event types are additive: a client that does not recognise a type must ignore that record rather than fail. `model_changed`
and `service_tier_changed` were added after the initial protocol and are safe to ignore. `session_parked`, `host_stalled`,
`host_memory_pressure`, `host_trimmed` and `subscription_limits` are the same: ignore them if unknown. `session_closed.reason` is optional; ignore an unknown
value the same way.

### session_closed.reason

When a multi-session host ends a routing handle it may name why:

```json
{ "type": "session_closed", "sessionId": "rpc-1", "reason": "client_close" }
```

| `reason` | When |
| --- | --- |
| `client_close` | An attached client sent `close_session` |
| `idle_evicted` | The idle sweep ended a session that was not retained |
| `session_dir_removed` | The session's transcript directory was deleted and nothing can reopen it: the idle sweep ended it because no client held it (whatever the idle window), or a generation handoff drain ended it instead of parking it. No `sessionPath` |
| `host_shutdown` | The host process is exiting (SIGTERM, idle-exit, empty-host). A retained session on a socket host is parked instead (`session_parked { reason: "host_shutdown" }`) |
| `replaced` | The routing handle ended because the live session behind it was replaced |
| `handoff_parked` | A generation handoff drained this host; reopen with `open_session { sessionPath }` |
| `released` | `release_session` handed the session to a runtime outside this host. Carries `sessionPath`, the file that runtime now writes: do NOT reopen it here |
| `error` | The session failed (worker death, output overflow) and the host sealed it |

The field is absent on older hosts and on older records. Decoders must not require it. A retained session that hits the
idle window emits `session_parked` instead of `session_closed`.

### session_parked

```json
{ "type": "session_parked", "sessionId": "rpc-1", "sessionPath": "/path/to/session.jsonl" }
```

The routing handle is gone; the session file is not. `open_session { sessionPath }` opens it as a new handle.

### host_stalled

```json
{ "type": "host_stalled", "driftMs": 6120, "sessionId": "rpc-1", "tool": "bash" }
```

Informational. The host does not abort or refuse anything because of a stall. `sessionId` and `tool` are omitted when
the stall cannot be attributed to a session.

### host_memory_pressure

```json
{ "type": "host_memory_pressure", "rssMb": 4910, "footprintMb": 4608, "measure": "phys_footprint", "sessions": 12 }
```

Informational. Capacity is memory, never a refusal: the host reports the pressure and parks idle sessions sooner.
`footprintMb` is the number compared with the threshold and `measure` names its kernel counter (`phys_footprint`,
`rss_anon`, `private_usage`, or `rss` where none is readable); `rssMb` is what `ps` shows and can stay high after
the memory was returned. Hosts released before senpi#2261 send `rssMb` and `sessions` only.

### host_trimmed

```json
{ "type": "host_trimmed", "footprintBeforeMb": 442, "footprintAfterMb": 237, "measure": "phys_footprint", "collected": true, "sessions": 0, "pauseMs": 41 }
```

Informational, at most once a minute: the host's last session closed, or a 2 GB+ host's session count dropped
(`sessions` above 0), and it ran one full collection that blocked the loop for `pauseMs`. `collected` is
`false` where the runtime exposes none (Node without `--expose-gc`); the record is still sent, with the two readings.

### model_changed

Emitted after the session's active model changed, whatever caused it: a `set_model` or `cycle_model` command, a slash
command, a retry fallback, or a session restore.

```json
{
  "type": "model_changed",
  "model": {"provider": "chatgpt-subscription", "id": "gpt-5.6-sol", "...": "..."},
  "thinkingLevel": "xhigh",
  "source": "cycle"
}
```

`model` is a full [Model](#model) object. `thinkingLevel` is the level in force **after** the switch — each model
remembers its own level, so this is that model's restored level (clamped to what it supports), not the level the
previous model was using. `source` is one of `"set"`, `"cycle"`, `"restore"`, `"fallback"`, or `"fallback-revert"`.

Clients that previously inferred the active model from `entry_appended` records can consume this instead.

### service_tier_changed

Emitted when the tier requests would carry, or the fast-mode indicator, changes — a `set_fast_mode` command, the
`/fast` slash command, or a model switch that resolves a different tier.

```json
{"type": "service_tier_changed", "tier": "priority", "fastMode": true}
```

`tier` is omitted when no tier applies. The pair matches `get_state.serviceTier` / `get_state.fastMode`.

### extension_event

Emitted when an extension calls `pi.rpc.emit(name, data)` and the client advertised
`extension_events`:

```json
{
  "type": "extension_event",
  "name": "acme.job.updated",
  "data": {
    "jobId": "job-42",
    "status": "running"
  }
}
```

`name` is extension-owned and `data` is opaque to Senpi. Consumers should validate the payload for
the specific event name before applying it. In multi-session mode the record also includes the
routing `sessionId`; delivery preserves the owning session and per-session event order.

Events are not replayed: a client receives those emitted after it starts receiving extension events
(by its handshake capabilities or a `set_client_info` that declares `extension_events`). At that
moment Senpi emits `senpi:extension-rpc-subscribed` (no data) on the in-process `pi.events` bus, so an
extension that keeps a state snapshot can send it once instead of waiting for its next change; other
subscribed clients may then receive the same snapshot again.

The terminal builtin emits `terminal_monitor_state` on this path whenever the active monitor set
changes. `data` is `{ activeCount, monitors }`, where each monitor entry has `id`, `description`,
`paused`, and `startedAtMs`. The matching in-process `pi.events` channel is unchanged and is not
forwarded. Clients receive the wire record only when they advertise the `extension_events`
capability:

```json
{
  "type": "extension_event",
  "name": "terminal_monitor_state",
  "data": {
    "activeCount": 1,
    "monitors": [
      {
        "id": "bash_1",
        "description": "watch checks",
        "paused": false,
        "startedAtMs": 1710000000000
      }
    ]
  }
}
```

#### Background session age

The terminal builtin emits `terminal_background_age` on the same path, and on the in-process `pi.events`
bus, when a background bash session is still running at 10 minutes and then every 30 minutes (10, 40,
70, ...), and when the opt-in auto-reap (`terminal.backgroundAutoReapMinutes` or the `bash` parameter
`auto_reap_minutes`) has stopped one, or once when its stop did not end the session. `data` has `kind`
(`running`, `reaped`, or `reap_failed`), `id` (the `bash_id`), `description`, optional `command`,
`startedAtMs`, `ageMs`, `ageMinutes`, `autoReapMinutes` (the age at which the session is stopped
automatically, or `null` when nothing will stop it), `reason` (on `reap_failed` only: why the stop did not
end it), and `stop`, the call that stops it. After `reap_failed` the session is still running, the
`running` reports go on, and the auto-reap does not try again. Nothing is stopped by this event; a client that wants the session gone calls `kill_bash`
with `stop.args`. A report that came due while the host slept arrives once, not once per missed interval.

```json
{
  "type": "extension_event",
  "name": "terminal_background_age",
  "data": {
    "kind": "running",
    "id": "bash_3",
    "description": "npm run dev",
    "command": "npm run dev",
    "startedAtMs": 1710000000000,
    "ageMs": 600000,
    "ageMinutes": 10,
    "autoReapMinutes": null,
    "stop": { "tool": "kill_bash", "args": { "bash_id": "bash_3" } }
  }
}
```

#### Job widgets

The `job-widgets` builtin emits `job_widget_state` on the same path: live, display-ready widgets for the
session's long background jobs (bash sessions started with `run_in_background` or auto-detached, and jobs a
host registers, such as background tasks). Clients receive it only when they advertise `extension_events`;
the in-process `pi.events` channel carries the same payload. It is sent at most once per second per session
and only when what a client draws changed, so a timestamp moving alone sends nothing. A client that starts
receiving extension events gets the session's current state once (within a second) when some job is shown,
so a frozen `done` widget reaches a late client too. `jobWidgets.enabled:
false` ([settings](settings.md#job-widgets)) turns it off.

`data` is `{ v: 1, sessionId, jobs }`. Each job has `id` (`bash_N` or a task id), `kind` (`bash` or `task`),
`state` (`pending`, `live`, `done`, `skipped`, `fallback`), `updatedAtMs`, and, except for `skipped`, a
`view`: `title`, optional `headline` (`text`, `label`, `trend`), optional `stage`, up to four `blocks`
(`spark`, `bars`, `meter`, `stat`, `grid`, `text`) whose numbers arrive formatted, and `lines` for
`pending` and `fallback`. A job appears once its widget is being built; `done` keeps the last view frozen
after the job exits. Ignore a payload whose `v` you do not know and any block `kind` you do not draw.

```json
{
  "type": "extension_event",
  "name": "job_widget_state",
  "data": {
    "v": 1,
    "sessionId": "session_1",
    "jobs": [
      {
        "id": "bash_3",
        "kind": "bash",
        "state": "live",
        "updatedAtMs": 1710000000000,
        "view": {
          "title": "Blender render",
          "headline": { "text": "120", "label": "rendered" },
          "blocks": [{ "kind": "meter", "label": "frames", "value": 0.48, "text": "120 / 250" }]
        }
      }
    ]
  }
}
```

Extensions that run their own long jobs offer them through the root package export:
`registerJobWidgetSource({ sessionId, id, kind, sources, brief, startedAtMs })` returns a handle (`notify`,
`update`, `settle`, `dispose`), or `undefined` when the session has no widgets; a source is any
`JobTextSource`, for example a `TextTap` the extension appends text to. `setJobWidgetAuthorResolver(resolver)`
routes spec writing to a host-chosen model (behind an explicit `jobWidgets.model`), and
`getJobWidgetState(sessionId)` reads the current state.

### agent_start

Emitted when the agent begins processing a prompt.

```json
{"type": "agent_start", "runId": "run-id"}
```

`runId` is the same optional engine-run identifier carried by lifecycle snapshots and
state readback. It is captured at run start, before asynchronous delivery; a later run
cannot replace the ID on a queued start event. Older engines omit this additive field.

### agent_end

Emitted when one low-level agent run completes. Contains all messages generated during this run. If `willRetry` is true, an automatic retry will follow. A run stopped because its session was replaced also carries `abortCause: { kind: "session_replaced", reason, targetSessionFile?, targetSessionId? }` (see `session_replaced`); a run the host's own stop cut short ends with `aborted: true`, `abortSource: "system"` and `abortCause: { kind: "host_shutdown" }`, never `abortSource: "user"` (senpi#6190); extensions' own `agent_end` does not carry it, they learn of the replacement from `session_shutdown`.

```json
{
  "type": "agent_end",
  "messages": [...],
  "willRetry": false
}
```

When the run ended with a provider error (the last assistant message has `stopReason: "error"`), `agent_end` also carries `failure`; it is absent on success and on abort:

```json
{
  "type": "agent_end",
  "messages": [...],
  "willRetry": false,
  "failure": {
    "category": "rate_limit",
    "provider": "anthropic",
    "model": "claude-sonnet-4-5",
    "httpStatus": 429,
    "code": "rate_limit_error",
    "reason": "the provider is rate limiting requests",
    "action": "retry later or set a fallback model"
  }
}
```

`failure` is built only from the failed message's structured `providerDiagnostic`, never from `errorMessage` text. `httpStatus` and `code` are copied from it when present. `provider` and `model` are the ids of the request that failed. When that request ran on a model other than the one the user selected (a fallback rung, or the model a virtual model routed to), `selectedProvider` and `selectedModel` name the selected one; both are absent otherwise. Every category carries a `reason` and an `action`:

| `category` | `action` |
| --- | --- |
| `auth` | re-authenticate the provider |
| `request_refused` | send the message again or choose another model; if it keeps failing, re-authenticate `<provider>` |
| `model_unavailable` | choose another model, or check that your plan or key includes this model |
| `rate_limit` | retry later or set a fallback model |
| `quota` | check the plan or credits |
| `context_limit` | compact or shorten the conversation |
| `invalid_request` | send the message again; if it repeats, choose another model or start a new session |
| `provider_unavailable` | retry or switch provider |
| `network` | check connectivity |
| `unknown` | send the message again; if it repeats, choose another model |

`unknown` is used when the error carries no diagnostic or its metadata matches no row; its `reason` is the generic `the provider returned an unexpected error`, and the provider's code or status, when it sent one, is only in `httpStatus` and `code`. No `reason` or `action` text carries a code or status. When `resetsAt` is set, `reason` ends with that time in the host's local time zone. A bare 429 stays `unknown` because status alone cannot tell a rate limit from exhausted quota. An `unknown` failure the provider answered with HTTP 404 is `model_unavailable` instead: a model endpoint returns 404 for a model id this account cannot use, as the ChatGPT subscription backend does for a model not yet rolled out to the plan. Retry and fallback decisions do not read `failure`.

A `network` failure whose `code` is a TLS chain-verification code (`UNABLE_TO_GET_ISSUER_CERT_LOCALLY`, `UNABLE_TO_GET_ISSUER_CERT`, `UNABLE_TO_VERIFY_LEAF_SIGNATURE`, `SELF_SIGNED_CERT_IN_CHAIN`, `DEPTH_ZERO_SELF_SIGNED_CERT` or `CERT_UNTRUSTED`), in an engine that adopted a fallback trust generation (its operating-system certificate import failed), also carries `trust`:

```json
{
  "category": "network",
  "provider": "anthropic",
  "model": "claude-sonnet-4-5",
  "code": "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
  "reason": "the connection to the provider failed",
  "action": "check connectivity",
  "trust": { "code": "trust-tls-failed-under-fallback", "reason": "helper-missing", "action": "reinstall-omo" }
}
```

`reason` is the generation's fallback reason and `action` the id of its repair action. A hostname mismatch, an expired certificate, any other network failure, and an engine whose import completed never carry `trust`. The code comes from the transport error's structured `code`, never from its message. The first such failure for each reason in a process also appends one record to `diagnostics.jsonl` beside the generation file; neither the record nor `trust` holds a host name, a path or a certificate.

A turn that never reached the provider because no API key or sign-in is saved for it (the message carries auth resolution's `Provider is not configured: <id>` sentinel) reports `auth`, with a `reason` naming the provider and an `action` to connect it or choose another model; it carries no `httpStatus` or `code`.

`request_refused` is an `auth` failure whose credential (same provider, endpoint and key) served a response within the last 10 minutes: the provider refused this one request, and the key may still be valid. If failures persist, re-authenticate the named provider: a recently working key may have been revoked. The failed assistant message carries `credentialServedRecently: true` and keeps the provider's own `errorMessage`. The in-memory record drops expired entries on each record/check and retains at most 1,024 credentials, evicting the least recently served first. Header-based, ADC and SigV4 authentication do not supply an `apiKey`, so their fingerprint reduces to provider + baseUrl; different credentials on that endpoint share the record.

The fallback chain conservatively skips every other model on that provider for the rest of the turn, including models with a different endpoint or key; models on other providers are still tried. This skip is provider-wide, not fingerprint-matched: the synchronous candidate scan cannot resolve the request's asynchronously prepared credentials. An `auth` failure with no recent success on the credential stays `auth`. A `request_refused` failure follows normal goal provider recovery rather than blocking the goal with login guidance.

### agent_settled

Emitted after the full session-level run settles. At this point senpi will not continue automatically through retry, compaction retry, or queued follow-up messages.

```json
{"type": "agent_settled"}
```

A multi-session host that closes, parks or releases a session mid-turn first publishes the settle that turn will now
never write, with `"reason": "session_closed"`, on the same broadcast as every `agent_settled`: whoever counted the
`agent_start` (the supervisor's idle-exit observer included) sees it end. Older hosts never send `reason`.

### entry_appended: goal and engine stops

`entry_appended` carries the full durable session entry in `entry`. For `entry.type: "custom"`, self-stops use these `entry.customType` values:

- `goal-continuation-stopped`: `entry.data` contains `goalId`, `reason` (`stale`, `repetition`, `cap`, `no-progress`, `length-exhausted`, or `context-overflow`; older sessions may carry the retired `unattended`), `consecutiveContinuations`, `unattendedContinuations`, `noProgressContinuations`, and `at`.
- `engine-paused`: `entry.data` contains `reason` (`repetition`, `goal-repeat`, `cap-per-message`, `cap-per-minute`, or `goal-stale`), `at`, and optional `rule`, `customType`, and `count`.

`at` is epoch milliseconds. These records survive session reopen and are available through the session-entry history. A goal stop is historical: accepted user input or `/goal resume` resets the stop, rather than deleting the entry. See [Session File Format](session-format.md#goal-and-engine-self-stop-entries) for the reason mapping and stale measurement-window behavior. Existing limit/rule entries and UI notices are preserved.

### turn_start / turn_end

A turn consists of one assistant response plus any resulting tool calls and results.

```json
{"type": "turn_start"}
```

```json
{
  "type": "turn_end",
  "message": {...},
  "toolResults": [...]
}
```

### message_start / message_end

Emitted when a message begins and completes. The `message` field contains an `AgentMessage`.

An assistant message's `diagnostics` also carries recovery notices. For
`claude_sdk_oauth_long_context_fallback`, `details.contextWindow` is `200000`
and `details.message` is displayable notice text. Render it as a muted notice
for that turn, alongside any session-continuity notice, rather than as an error.
The fallback applies only to that request; it does not change the selected
model or its default 1M window. Saved assistant messages retain the diagnostic.

```json
{"type": "message_start", "message": {...}}
{"type": "message_end", "message": {...}}
```

### message_update (Streaming)

Emitted during streaming of assistant messages. Contains a delta event without a cumulative message snapshot.

```json
{
  "type": "message_update",
  "usage": {
    "input": 100,
    "output": 1,
    "cacheRead": 0,
    "cacheWrite": 0,
    "totalTokens": 101,
    "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "total": 0}
  },
  "assistantMessageEvent": {
    "type": "text_delta",
    "contentIndex": 0,
    "delta": "Hello "
  }
}
```

The `assistantMessageEvent` field contains one of these delta types:

| Type | Description |
|------|-------------|
| `text_start` | Text content block started |
| `text_delta` | Text content chunk |
| `text_end` | Text content block ended |
| `thinking_start` | Thinking block started |
| `thinking_delta` | Thinking content chunk |
| `thinking_end` | Thinking block ended |
| `toolcall_start` | Tool call started (includes `id` and `toolName`) |
| `toolcall_delta` | Tool call arguments chunk |
| `toolcall_end` | Tool call ended (includes full `toolCall` object) |

Example streaming a text response:
```json
{"type":"message_update","usage":{...},"assistantMessageEvent":{"type":"text_start","contentIndex":0}}
{"type":"message_update","usage":{...},"assistantMessageEvent":{"type":"text_delta","contentIndex":0,"delta":"Hello"}}
{"type":"message_update","usage":{...},"assistantMessageEvent":{"type":"text_delta","contentIndex":0,"delta":" world"}}
{"type":"message_update","usage":{...},"assistantMessageEvent":{"type":"text_end","contentIndex":0,"content":"Hello world"}}
```

The top-level `usage` field contains the latest cumulative provider-reported usage. It may remain
zero until completion when a provider does not report usage during streaming.

Example starting a tool call:
```json
{"type":"message_update","usage":{...},"assistantMessageEvent":{"type":"toolcall_start","contentIndex":1,"id":"call_abc123","toolName":"write"},"resolvedToolName":"write"}
```

`toolcall_start` and `toolcall_end` records carry a top-level `resolvedToolName`: the tool the call
will run, by the same rule the agent applies before executing it. A gateway-namespaced or recased
call such as `mcp__1a2b__Edit` streams with `toolName: "mcp__1a2b__Edit"` and `resolvedToolName: "edit"`;
an exact or unresolvable name reports itself. Title and render the call by `resolvedToolName`, which is
also the `toolName` of its `tool_execution_*` events.

`message_update` intentionally omits the former cumulative `message` field and
`assistantMessageEvent.partial`. Clients that need a live partial message must assemble it
from `message_start` and subsequent events using `contentIndex`. Treat `message_end.message`
as authoritative. For tool calls, `toolcall_start` provides the call `id` and `toolName`;
buffer `toolcall_delta.delta` for arguments. `toolcall_end.toolCall` contains the completed
call.

### bash_execution_update

Emitted once for each output chunk from a direct `bash` command. `id` matches the command's `id`, allowing clients to associate output with the correct command.

Events stream all output while the command runs, even if the final `bash` response's `output` is truncated.

```json
{
  "type": "bash_execution_update",
  "id": "req-1",
  "delta": "total 48\n"
}
```

### tool_execution_start / tool_execution_update / tool_execution_end

Emitted when a tool begins, streams progress, and completes execution.

```json
{
  "type": "tool_execution_start",
  "toolCallId": "call_abc123",
  "toolName": "bash",
  "args": {"command": "ls -la"}
}
```

During execution, `tool_execution_update` events stream partial results (e.g., bash output as it arrives):

```json
{
  "type": "tool_execution_update",
  "toolCallId": "call_abc123",
  "toolName": "bash",
  "args": {"command": "ls -la"},
  "partialResult": {
    "content": [{"type": "text", "text": "partial output so far..."}],
    "details": {"truncation": null, "fullOutputPath": null}
  }
}
```

When complete:

```json
{
  "type": "tool_execution_end",
  "toolCallId": "call_abc123",
  "toolName": "bash",
  "result": {
    "content": [{"type": "text", "text": "total 48\n..."}],
    "details": {...}
  },
  "isError": false
}
```

Use `toolCallId` to correlate events. The `partialResult` in `tool_execution_update` contains the accumulated output so far (not just the delta), allowing clients to simply replace their display on each update.

### queue_update

Emitted whenever the pending steering or follow-up queue changes.

```json
{
  "type": "queue_update",
  "steering": ["Focus on error handling"],
  "followUp": ["After that, summarize the result"]
}
```

### compaction_start / compaction_end

Emitted when compaction runs, whether manual or automatic.

```json
{"type": "compaction_start", "reason": "threshold"}
```

The `reason` field is `"manual"`, `"threshold"`, or `"overflow"`.

```json
{
  "type": "compaction_end",
  "reason": "threshold",
  "result": {
    "summary": "Summary of conversation...",
    "firstKeptEntryId": "abc123",
    "tokensBefore": 150000,
    "estimatedTokensAfter": 32000,
    "usage": {
      "input": 32000,
      "output": 1200,
      "cacheRead": 0,
      "cacheWrite": 0,
      "totalTokens": 33200,
      "cost": {"input": 0.01, "output": 0.02, "cacheRead": 0, "cacheWrite": 0, "total": 0.03}
    },
    "details": {}
  },
  "aborted": false,
  "willRetry": false
}
```

If `reason` was `"overflow"` and compaction succeeds, `willRetry` is `true` and the agent will automatically retry the prompt.

If compaction was aborted, `result` is `null` and `aborted` is `true`.

If compaction failed (e.g., API quota exceeded), `result` is `null`, `aborted` is `false`, and `errorMessage` contains the error description.

### auto_retry_start / auto_retry_end

Emitted when automatic retry is triggered after a transient error (overloaded, rate limit, 5xx).

```json
{
  "type": "auto_retry_start",
  "attempt": 1,
  "maxAttempts": 3,
  "delayMs": 2000,
  "errorMessage": "529 {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"}}"
}
```

```json
{
  "type": "auto_retry_end",
  "success": true,
  "attempt": 2
}
```

On final failure (max retries exceeded):
```json
{
  "type": "auto_retry_end",
  "success": false,
  "attempt": 3,
  "finalError": "529 overloaded_error: Overloaded"
}
```

### retry_fallback_exhausted

Emitted when the turn's model fallback chain runs out: the primary and every fallback rung failed.

```json
{
  "type": "retry_fallback_exhausted",
  "chainKey": "anthropic/claude-opus",
  "lastError": "Connection error.",
  "primaryError": { "model": "anthropic/claude-opus", "reason": "billing", "error": "400 out of extra usage" },
  "failures": [
    { "model": "anthropic/claude-opus", "reason": "billing", "error": "400 out of extra usage" },
    { "model": "openai/gpt", "reason": "transient", "error": "Connection error." }
  ]
}
```

- `chainKey`: the `provider/model` key of the fallback chain that ran out.
- `lastError`: the error of the rung that ran last.
- `primaryError` (optional): the failure that started the fallback walk, the turn's first failed rung, as `{ model, reason, error }`. `reason` is `transient`, `refusal`, `hard-error` or `billing`.
- `failures` (optional): every rung that failed this turn, in the order it ran, the primary first. An exact repeat of the previous entry is dropped.

`primaryError` and `failures` are present together when the session recorded at least one rung failure, and absent otherwise. Account usage-limit text in `lastError` and in each `error` is replaced by its account-limit description. Clients that ignore unknown fields keep working with `chainKey` and `lastError`.

### summarization_retry_scheduled / summarization_retry_attempt_start / summarization_retry_finished

Emitted when compaction or branch-summary summarization retries after a transient provider error. These events use the same retry settings as automatic assistant-turn retries.

```json
{
  "type": "summarization_retry_scheduled",
  "attempt": 1,
  "maxAttempts": 3,
  "delayMs": 2000,
  "errorMessage": "terminated"
}
```

```json
{
  "type": "summarization_retry_attempt_start",
  "source": "compaction",
  "reason": "threshold"
}
```

For branch summaries, `source` is `"branchSummary"` and no `reason` is present.

```json
{
  "type": "summarization_retry_finished"
}
```

### skill_invocation

Emitted once after one or more explicit skill tokens are expanded. `skills` preserves invocation order.
`syntax` reports the token form that selected the skill; `path` is the resolved `SKILL.md` path.

```json
{
  "type": "skill_invocation",
  "skills": [
    {
      "name": "debugging",
      "path": "/project/.agents/skills/debugging/SKILL.md",
      "syntax": "dollar"
    },
    {
      "name": "review",
      "path": "/project/.agents/skills/review/SKILL.md",
      "syntax": "slash"
    }
  ]
}
```

In multi-session mode the normal routing `sessionId` is added. This event does not mutate loaded
surfaces; clients continue to use `loaded_surfaces_changed` plus `get_loaded_surfaces` for MCP reveal.

### commands_changed

Emitted whenever a post-bind runtime reload changes the ordered command surface. The initial surface is available
through `get_commands` and does not emit this invalidation event. The `commands` payload has the same shape and
ordering as `get_commands`; identical snapshots are not re-emitted.

```json
{
  "type": "commands_changed",
  "commands": [
    {"name": "session-name", "source": "extension", "syntax": "slash", "sourceInfo": {"path": "/project/extensions/session.ts", "source": "auto", "scope": "project", "origin": "top-level"}},
    {"name": "skill:debugging", "source": "skill", "syntax": "dollar", "sourceInfo": {"path": "/project/.agents/skills/debugging/SKILL.md", "source": "auto", "scope": "project", "origin": "top-level"}}
  ]
}
```

### command_invocation

Emitted exactly once after the session resolves an extension command, or after a prompt template survives extension
input interception and prompt acceptance. Unknown, transformed, or rejected commands do not produce this event;
skills continue to use `skill_invocation`.

```json
{
  "type": "command_invocation",
  "command": {
    "name": "session-name",
    "source": "extension",
    "syntax": "slash",
    "sourceInfo": {"path": "/project/extensions/session.ts", "source": "auto", "scope": "project", "origin": "top-level"}
  }
}
```

### loaded_surfaces_changed

Emitted without a request id when the loaded skill, extension, or MCP inventory changes. A multi-session host sends one per connection per inventory change on either session runtime (in-process or worker isolate), tagged with the first session that reported that transition: sessions moving from the same digest to the same new one share a single event, while a session converging from a different start still announces its own change, because `get_commands` and `get_loaded_surfaces` are read per session. The event carries no inventory payload; clients re-read `get_commands` for skills and `get_loaded_surfaces` for extensions/MCP.

```json
{"type": "loaded_surfaces_changed"}
```

**MCP startup window.** Every MCP attach of a session (session start, a new, resumed or forked session, a reload) opens a startup window. It stays open until every MCP server connect that attach started has settled: connected with its tools registered, failed, or timed out by the server's `connectTimeoutMs`. The count of startup events is fixed by this contract, not by how parallel connects interleave or how often the client reads:

- While the window is open, MCP inventory changes emit no `loaded_surfaces_changed`. `get_loaded_surfaces` still answers with the current inventory, which may show servers still connecting.
- When the window closes after starting at least one connect, each connection attached to the session receives exactly one `loaded_surfaces_changed`, even when its last `get_loaded_surfaces` already showed the final inventory. Re-reading after it gives the settled startup inventory. A multi-session host applies the per-connection dedupe above: sessions that settle onto the same inventory share one event.
- An attach that starts no connect (no server configured, servers disabled, or every connection reused) emits no startup event; if its inventory changed, that change is announced once, like any other.
- A connection that attaches after the window closed receives no startup event; it reads the inventory.
- After the window, each MCP inventory change emits as before. Skill and extension changes are not held by the window.

`get_loaded_surfaces` never emits `loaded_surfaces_changed`: a read answers with the inventory and records nothing, so polling during startup adds no events.

### transcript_write_failed

Emitted when the session file refuses to save a message of the running turn (permission denied, a full disk, a removed
session directory). The message is not in the transcript and will not be in a reloaded session. The next prompt that starts a run while the
session is idle leaves it out of the model context too; a steer or follow-up queued (`streamingBehavior`) during the
refused run still sends it to the model on its turn. A prompt accepted with `success: true` reports this failure only
through this event.

```json
{
  "type": "transcript_write_failed",
  "role": "assistant",
  "errorMessage": "EACCES: permission denied, open '/path/to/session.jsonl'"
}
```

### extension_error

Emitted when an extension throws an error.

```json
{
  "type": "extension_error",
  "extensionPath": "/path/to/extension.ts",
  "event": "tool_call",
  "error": "Error message..."
}
```

## OAuth login

Logins are fire-command-then-subscribe: the command answers as soon as the flow has started, and the URL plus the terminal result arrive as events.

- `login_start` `{provider, slotId?}`: responds immediately with `success: true` (flow started). A second `login_start` for the same provider aborts the earlier attempt. With `slotId`, reauthorizes that immutable OAuth account through the shared runtime, preserving its registration and siblings. A selected SIWC account uses its saved client ID and identity rather than offering a legacy route switch. Omit `slotId` to add an account.
- `auth_login_url` `{provider, url}`: the URL (or device-code verification URL) the user must open.
- `auth_login_progress` `{provider, text}`: a status line while the login prepares or runs, for example an extension's `provider_login_start` handler reporting `Downloading Claude Code 2.1.306: 10% of 200 MB`. Zero or more per login, always before `auth_login_end`. Every provider progress and info line is forwarded as written, so `text` may name the local callback address a login listens on (for example `Listening for OpenRouter OAuth callback on http://<host>:<port>/<path>`), the same redirect address the `auth_login_url` already carries; the URL the user must open arrives only in `auth_login_url`. Built-in providers put no authorization code or token in these lines.
- `auth_login_end` `{provider, success, error?, replaced?, backupPath?}`: exactly one per login; `error` is a non-secret message. When a successful login replaced the provider's credential of the other kind (an OAuth login over a stored API key), `replaced` names that kind (`"api_key"` or `"oauth"`) and `backupPath` is the copy of `auth.json` taken before it (absent when the credential store is not a file). A login of the same kind adds an account and carries neither field. A successful `anthropic-subscription` sign-in through the Claude CLI also carries `account` `{name}` (the account it signed in) and `check` `{model, outcome: "ok"|"failed", reason?, at}`, the one-turn connection test run right after sign-in; a failed test keeps the account.
- `login_cancel` `{provider}`: aborts the in-flight login; the client then sees `auth_login_end` with `success: false`.

`logout` `{provider, slotId?}` invokes the shared runtime revocation path. With `slotId`, only that account is signed out. A provider with remote revocation (ChatGPT Subscription) keeps the signed-out registration for later reauthorization. A provider without it (such as Anthropic Subscription, whose Claude CLI accounts hold no tokens to clear) signs the account out by removing it. For SIWC, the response carries `data: {status: "revoked" | "remote_revocation_unconfirmed"}`. The latter must be shown as "remote revocation not confirmed; disconnect the app in ChatGPT Settings". For ChatGPT Subscription, tokens are cleared locally while the registration remains available for later reauthorization. `account_remove` remains explicit registration deletion. Terminal equivalents are `/gpt-account reauthorize <id>` and `/gpt-account signout <id>`.

Some providers need input mid-flow (a pasted authorization code, a text or secret value, a choice between accounts). Those prompts reuse the extension UI dialog channel described in the next section:

- `text`, `secret`, and `manual_code` prompts arrive as an `extension_ui_request` with `method: "input"`. `title` is the provider's prompt message and `placeholder` is present when the provider supplied one.
- `select` prompts arrive with `method: "select"`; `options` holds the option labels.

Answer with `extension_ui_response` `{id, value}`. For `select`, `value` is the chosen label and is mapped back to the option id in-process. Sending `{id, cancelled: true}` cancels the login, and `auth_login_end` reports `success: false` with `error: "Login cancelled"`.

A client that never answers loses nothing. The browser/callback completion path still finishes the login, and the pending request is released when the login ends or is cancelled, so an open dialog never blocks completion. Secrets don't cross the wire in either direction: only the prompt message, placeholder, and labels are emitted, and the answer is consumed in-process and never echoed.

Example exchange (Claude subscription through the bundled `claude auth login`, user pastes the code instead of finishing in the browser):

```jsonl
{"id": "login-1", "type": "login_start", "provider": "anthropic-subscription"}
{"id": "login-1", "type": "response", "command": "login_start", "success": true}
{"type": "extension_ui_request", "id": "uuid-6", "method": "select", "title": "Select Anthropic login method:", "options": ["Browser login (default)", "Copy code login (headless)"]}
{"type": "extension_ui_response", "id": "uuid-6", "value": "Browser login (default)"}
{"type": "auth_login_url", "provider": "anthropic-subscription", "url": "https://claude.ai/oauth/authorize?..."}
{"type": "extension_ui_request", "id": "uuid-7", "method": "input", "title": "Paste the code Anthropic shows after you sign in:", "placeholder": "https://claude.ai/oauth/authorize?..."}
{"type": "extension_ui_response", "id": "uuid-7", "value": "<pasted code>"}
{"type": "auth_login_end", "provider": "anthropic-subscription", "success": true}
```

If the user completes the flow in the browser instead, the same `extension_ui_request` is emitted, no response is needed, and `auth_login_end` arrives on its own.

#### verify_api_key

Checks an API key with its provider before a client saves it. The key is used for one authenticated read of the provider's model list and is never stored, logged, or echoed. Hosts that support it advertise `auth_key_verify`.

```json
{"type": "verify_api_key", "provider": "openai", "key": "<key>"}
```

Response `data` is `{ok: true}` or `{ok: false, reason, status?}`:

- `rejected`: the provider answered 401 or 403.
- `unreachable`: no answer, a timeout, or a 5xx.
- `unsupported`: the key cannot be checked this way. Either the provider's API has no probe, the list is not where it was expected (another 4xx or 3xx), or the list answers any key (OpenRouter, keyless local servers). In that last case a 200 proves nothing, so the host also asks with a made-up key and reports `ok` only when that one is refused.
- `unknown-provider`: no model is configured for the provider.

#### login_api_key

Stores an API key for a provider. The response comes after the model registry has seen the key, so a client that re-reads `get_auth_providers` on it gets the new state.

```json
{"type": "login_api_key", "provider": "openrouter", "key": "<key>"}
```

A provider whose API-key login asks a region (Kimi Code: `"mainland-cn"` or `"global"`) takes it as `region`, and the key is stored with that region exactly as the CLI's `/login` stores it. A region the provider does not offer, a region other than the one the host's environment sets (`KIMI_CODE_REGION` / `KIMI_CODE_OAUTH_HOST`), a provider whose login asks a second select, or a `region` for a provider whose key has none fails the command and stores nothing:

```json
{"type": "login_api_key", "provider": "kimi-coding", "key": "<key>", "region": "global"}
```

A provider holds logins of one kind. If it had an OAuth login, the key replaces it: `auth.json` is backed up first, and the response `data` is `{replaced: "oauth", backupPath?}`, where `backupPath` is absent when the credential store is not a file (a failed backup fails the login instead). A key added over another key has no `data`.

When `auth.json` exists but cannot be loaded, `get_auth_providers` `data` also carries `storeError` `{kind, reason}`. `kind` is `malformed_json` (not valid JSON), `invalid_format` (the document is not a JSON object), `unreadable` (the file cannot be read, for example a permission error) or `write_back_failed` (the file was read, but saving its repaired or migrated copy failed; the sign-ins it read stay configured and writes are not refused for this kind). `reason` is a short message that never includes the file's path or contents. While `storeError` has any other kind, a stored sign-in reads as unconfigured because it could not be read, not because it is missing (a store that loaded earlier in the process keeps its last loaded sign-ins). Every write, such as `login_api_key`, a login, or `logout`, fails and leaves the file unchanged. A client should say the sign-in store could not be read and ask the user to repair or move `auth.json`. The next `get_auth_providers` after the file becomes readable no longer has `storeError`. A store that is only locked by another writer is not a `storeError`.

While another process holds `auth.json`'s lock, `get_auth_providers` `data` also carries `storeBusy: true`. The request still answers within about a second: the rows come from `auth.json` read without its lock, so a stored sign-in stays configured instead of reading as missing. A client can say the sign-in store is busy and read again; `storeBusy` is absent once the store has been read under its lock.

`get_auth_providers` API-key rows carry `keyHint`, the last four characters of a literal key the app stored when it is at least 12 characters long. OAuth rows, `!command` and `$ENV` references, and short keys have none.

Every `get_auth_providers` row whose provider is defined carries `origin`, which says where the definition lives so a client can name what to edit when the app cannot remove the entry itself:

| `origin.kind` | Meaning |
| --- | --- |
| `builtin` | Shipped with senpi, including providers registered by builtin extensions. |
| `models_json` | Defined only in models.json. |
| `extension` | Registered by an extension (a native provider, a provider config with no builtin underneath, or virtual models). |

`modelsJsonPath` is the models.json that defines or overrides the provider, and `extensionPath` is the filesystem path of the extension that registered or overrides it, when known. Synthetic builtin identifiers and inline or unknown extension placeholders are omitted. Both paths are optional, on any kind:

```json
{"id": "proxy-box", "name": "proxy-box", "authType": "api_key", "status": {"configured": false}, "origin": {"kind": "extension", "extensionPath": "/home/user/.senpi/agent/extensions/proxy.ts"}}
```

## Extension UI Protocol

Without presenter enforcement, MCP 2026-07-28 multi-round-trip form answering is terminal-only in v1.
RPC-originated modern requests advertise no elicitation and terminate locally
if input is required; they never fabricate a decline or retry incomplete input.
Client roles and capability declarations do not enable this form channel.
Existing legacy MCP dialogs and their RPC request/response shapes remain unchanged.

### session_recovered

Emitted when an interrupted write (usually a full disk) left the session file's last record incomplete. The incomplete
bytes were copied to `backupPath` (`<session file>.torn-<time>-<id>`, never deleted) and cut, and every complete record is
kept. `cause` is `disk_full` when this process saw the write fail with `ENOSPC`/`EDQUOT`, `write_failed` for another
failed write, and `unknown` when the damage was found while opening the session without a known failed write.
`notice` is the text to show the person: paths under the home directory use `~/...`; backups outside it use a neutral
label instead of an absolute path. The machine-readable `backupPath` remains absolute.
A repair found while opening is replayed to each client that attaches before the next prompt; one made during a run is
emitted live. It is sent once per repair.

```json
{
  "type": "session_recovered",
  "cause": "unknown",
  "backupPath": "/home/example/.senpi/sessions/session.jsonl.torn-1761436800000-1a2b3c4d",
  "droppedBytes": 74,
  "notice": "The last message of this session wasn't saved completely (an earlier save was interrupted, for example by a full disk). Everything before it was loaded; the incomplete record was kept in ~/.senpi/sessions/session.jsonl.torn-1761436800000-1a2b3c4d."
}
```

### Opt-in private MCP forms

A multi-session RPC host or interactive terminal can opt in with `--mcp-presenter-enforcement`. This is a
deployment option, not a project setting. It defaults to off; existing desktop and
gateway clients keep their current behavior until they implement the private
presenter protocol. Without this option, terminal forms retain their existing queue,
legacy origin rules, and legacy stderr diagnostics. Enforced terminal forms also
queue, and a collector failure ends only its own form, not the terminal's grant.
All UI contexts in one terminal session binding share its presenter authority.
Without enforcement, each real select/input answer retains its existing human
admission timing; the form collector does not add a second final admission.
Ephemeral selects also keep the scheduled `requestRender()` path without enforcement.
With enforcement, only the authority's winning whole-form action admits once.
The host advertises `mcp_form_presenter_v1` only when enforcement is enabled;
the capability reports protocol support, not authority to present or answer a form.

The public `host ensure` and `host handoff` commands accept the same deployment option,
separately from `--launch-spec`. Add `--mcp-presenter-fd 4` with a live inherited duplex
channel to enroll the launch owner of a new host. The runtime-selecting CLI re-exec,
supervisor and host child preserve that channel. The option alone enables enforcement,
not a presenter; fd 4 alone does not enable enforcement.

An enforcing predecessor keeps enforcement in its successor, including when an older
handoff caller omits the option. Conditional `handoff --when idle` carries the non-secret
`mcp_presenter_enforcement` boolean in `begin_handover`, independently of the launch
specification and environment. It uses only the existing authenticated owner's channel
for fresh successor enrollment; the CLI cannot enroll itself into the predecessor.
Reuse and already-current handover answers report the serving host's actual capabilities.
Neither a successful CLI exit nor an equal `runtimeBuildId` proves enforcement or
enrollment. A deployment requesting enforcement against an unenforced existing host must
coordinate a replacement, not force-restart another owner's busy host.

The native launch owner enrolls an Ed25519 public key through an inherited private
bootstrap channel. Descriptor 4 is reserved for this channel; descriptor 3 remains
the separate owner-lifetime channel. Enrollment and management proofs sign the
host's exact returned transcript. No secret is passed in an argument, environment
variable, launch specification, or session state. Reusing a host does not enroll the
caller, and a successor requires fresh enrollment and fresh grants.
An invalid or lost bootstrap channel leaves the host without a presenter; it does
not terminate the shared daemon or its lifetime channel. The helper remains lazy
to preserve the supervisor's startup import budget, with import and relay failures
contained at that boundary. Conditional idle handover
is owned by the running host after the CLI returns: that host relays the successor's
fresh challenge over the existing authenticated launch-owner channel. The CLI's
bootstrap stream is never serialized into `begin_handover`.

`mcp_presenter_context` returns the caller's current connection nonce and attachment
context. These identifiers confer no authority.

An embedding distribution may inject a `PresenterAccountAuthority` at host start
(`presenterAccountAuthority` in the host options); no RPC command, argument,
environment variable, settings file, or session state can supply one. The CLI's
only way in is code the distribution runs before the CLI loads: it calls
`registerPresenterAccountAuthority(authority)` from the side-effect-free
`@code-yeongyu/senpi/presenter-authority` entry, then imports the CLI. `main()`
takes the registration as its first statement and seals it, so a second
registration throws `presenter_authority_already_registered` and any later one
(an extension, a session, a later import) throws `presenter_authority_sealed`. A
process the CLI or a host supervisor starts on senpi's own entry has no
registration and behaves as a host without an authority. An enforced host
with such an authority has the management endpoint even without the descriptor-4
bootstrap. A caller discovers it only by asking explicitly:
`{"type":"mcp_presenter_context","sessionId":"...","discover":true}`. The reply's
`context` then also carries `controlEndpoint`, the endpoint's socket or pipe path. The
key is added only when `discover` is the boolean `true` and the host has an account
authority; every other request, and every host without an authority, gets the five
context fields exactly as before, so strict decoders that reject unknown keys keep
working. The endpoint path confers no authority; only the exchange below does.

An engine that predates `discover` ignores the key and answers with the five context
fields. A client must treat a missing `controlEndpoint` as "account enrollment
unavailable on this host": not an error, and not a reason to retry the request.

An enforced interactive terminal serves the same private surface on its control endpoint. A control
connection that declared `interactive_user` and `mcp_form_presenter_v1` with `set_client_info` and holds a
live attachment (`attach_session` or `open_session`) answers `mcp_presenter_context`, and sends
`mcp_form_presented`, `mcp_form_response` and `mcp_form_sync` like an RPC connection. Each is answered on
that connection only, as `mcp_form_reply`. Private frames never reach the terminal's `subscribe` feed, a
`subscribe_sessions` observer, another control connection, or a session entry. Releasing the attachment,
closing the connection, or declaring without a role revokes what it holds. When the distribution injects a
`PresenterAccountAuthority` into the terminal (`presenterAccountAuthority` in the interactive options), the
terminal also has the management endpoint and answers `discover`. A terminal has no descriptor-4 bootstrap,
so every other presenter on it is a same-account principal. The terminal itself stays one `local_tui`
holder: a form reaches the terminal and every enrolled holder, and the first human answer wins.

A host-side forwarder that is not attached to any session (a relay host) asks with
`mcp_presenter_control_info` instead, on its own connection:

```json
{ "id": "i1", "type": "mcp_presenter_control_info" }
{ "id": "i1", "type": "response", "command": "mcp_presenter_control_info", "success": true, "data": { "controlEndpoint": "/tmp/senpi-presenter-AbC123/control.sock" } }
```

- It is answered only on a connection that proved the endpoint's launch key (see
  "Authentication"; on Windows, the socket secret) and has not declared a delegation.
  Any other connection gets `presenter_not_authorized`: an ordinary error response
  (`errorCode: "presenter_not_authorized"`), or on a delegated connection the private
  reply `{ "type": "mcp_form_reply", "id": "i1", "error": "presenter_not_authorized" }`.
- `data.controlEndpoint` is present only while an account-enrolling control endpoint
  is listening; otherwise `data` is `{}`. Like `discover`, the path confers no
  authority.
- An engine that predates this record answers it with an error. Read that as "no
  control endpoint", not as a reason to retry.

A same-account presenter enrolls on a fresh connection to that endpoint, with no owner
prompt, in one attempt within the connection's 30 s window:

1. `{"type":"account_enroll","version":1,"purpose":"mcp_form","publicKey":"<SPKI PEM>","installationKeyId":"<sha256 hex of the SPKI DER>","attestation":"<token>"}`.
   The key set is exact and the key must be Ed25519. The attestation is an issuer token
   with `aud: "omo-mcp-presenter"` and `typ: "mcp_presenter"`, whose `cnf.jkt` is the
   RFC 7638 OKP thumbprint of this key (the 32 raw bytes after the fixed 12-byte Ed25519
   SPKI prefix). The injected authority verifies it; the host then requires `acc` to be
   the host's signed-in account, `dev`, `dname` and `jti` to be 1-256 characters with no
   control characters, and the `jti` to be unused in this host incarnation. A `jti` is
   remembered until `exp` plus 60 s; at 4096 live entries the host refuses with
   `presenter_busy` instead of forgetting one.
2. The host answers `{"type":"challenge","version":1,"transcript","hostInstance"}`, where
   `transcript` is the JSON tuple `["mcp-presenter-account-enroll-v1","mcp_form",
   hostInstance, hostAccount, acc, dev, installationKeyId, jti, nonce, 30000]`.
3. The presenter signs the exact transcript: `{"type":"proof","signature":"<hex>"}`.
4. The host answers `{"type":"account_enrolled","version":1,"principalId","hostInstance",
   "attestedUntil"}` (`attestedUntil` is the attestation's `exp`, in seconds). The same
   connection then carries that principal's signed `challenge`/`proof` commands; no other
   connection can act as an account principal.

An enrollment refusal is `{"type":"account_refused","version":1,"reason"}` followed by the
close of the connection. `reason` is one of `presenter_account_unavailable` (no authority, or the
host is signed out), `presenter_account_mismatch`, `attestation_malformed`,
`attestation_signature`, `attestation_audience`, `attestation_expired`,
`attestation_key_mismatch`, `attestation_replayed`, `presenter_busy`, or
`presenter_proof_invalid`. A malformed `account_enroll` record closes the connection
without a reason. Enrolling the same account, device and key again supersedes the earlier
principal: its connection closes and its grants are revoked.

On its enrollment connection the principal extends `attestedUntil` with
`{"type":"account_reattest","attestation":"<token>"}`; the host answers
`{"type":"account_reattested","version":1,"attestedUntil"}`. The same checks apply. A
token for another key, an account that is no longer the host's, or a signed-out host is
refused with `account_refused`, revokes the principal's grants and closes the connection.
Any other re-attestation refusal (for example a reused `jti` or an expired token) is an
`account_refused` on an open connection, and the principal and its grants stay. An account principal never becomes the launch owner, so it cannot authorize a
successor host's enrollment.

Acquisition and revocation use the
separate authenticated management endpoint, with a fresh challenge for each
`mcp_presenter_assign`, `mcp_presenter_acquire`, or `mcp_presenter_revoke` command.
Enrollment alone assigns no sessions: before acquisition, a principal signs
`mcp_presenter_assign` with `sessionId`, the current `bindingEpoch`, and
`purpose: "mcp_form"`. Who may assign depends on the principal:

- The inherited launch principal, the trusted native supervisor, assigns a session it
  opened, or one the user explicitly adopted through the trusted host-owner UI.
- An account principal assigns itself. A same-account login is the authorization, so
  there is no owner prompt. Its `mcp_presenter_assign` and `mcp_presenter_acquire` are
  accepted only while the host is still signed into the principal's account and the
  time is before its `attestedUntil`, and acquisition needs the acquiring connection's
  live attachment to that session. A command from a principal that fails the account
  or attestation check gets `account_refused` with `presenter_account_mismatch`,
  `presenter_account_unavailable`, or `attestation_expired`, and its connection closes,
  revoking its grants.

Ordinary RPC attachment cannot assign a session.
Assignment belongs only to that enrolled principal and live binding; re-enrollment,
including the same device and key enrolling again, or binding replacement requires a
new assignment. It is not persisted, and a successor host knows no earlier principal.

An account principal is also revoked, with its grants, when the embedding distribution
reports a sign-out or an account switch, and when `attestedUntil` passes without an
`account_reattest`. The connection receives `account_refused` with
`presenter_account_unavailable`, `presenter_account_mismatch`, or `attestation_expired`
and closes. A revoked grant ends its forms under the outcome rules below: a presented
form cancels without human admission, and one not yet presented is a processing
failure. A dialog belongs to the grant it was created for. A later holder, including
another device of the same account, never receives or answers a dialog created for
another holder, even after that holder leaves.

An acquisition also requires the connection's `interactive_user` and
`mcp_form_presenter_v1` capabilities, and binds the
current host, session, binding epoch, connection nonce, attachment ID and epoch, and
`purpose: "mcp_form"`. A session binding can have several holders at once, at most
one per (principal, connection), and each grant is checked on its own. An acquire may
add `features: ["elsewhere_v1"]`. The list is part of the signed command, so the host
records it on the grant. Unknown names are ignored, and a list that is not an array of
at most 16 short strings is refused.
Concurrent forms, including worker-origin forms, wait in one abort-aware FIFO per
binding, whichever holder answers. When a form reaches the head, it is offered to the
holders current at that moment; a holder that acquires later never receives that form,
only the following ones. Waiting consumes the original deadline; timeout, cancellation,
or loss of every holder before display never fabricates a human response.
Enforced legacy connections observe presenter readiness and reconnect when their
negotiated form capability becomes stale, including a grant issued after connect.
Revoking the last ready holder removes the capability on the new connection.
A shared physical connection advertises forms when at least one attached owner is
ready; each request still requires its own origin's grant. An ungranted owner cannot
borrow another owner's presenter. Readiness changes during initialization are
rechecked before the connection is published. Modern MRTR connections do not
reconnect for this purpose because their capability metadata is per request.

Legacy elicitation has no reliable parent tool-call identifier in the received SDK
handler metadata. With multiple `tools/call` operations in flight on one physical
legacy client, enforced elicitation fails closed with the same fixed JSON-RPC
processing error as an unavailable presenter: code `-32603`, message
`Elicitation processing unavailable`, and no `data`.
No form is displayed and no human answer is admitted. Without enforcement, legacy
clients keep the SDK request method, origin handling, and concurrent-call behavior.

Worker binding waits at most five seconds for the host's acknowledgement; expiry
fails with `private_form_unavailable`, removes the pending waiter, and releases any
late host binding. Worker readiness events feed the same legacy renegotiation path.
Under enforcement, server stderr remains available as redacted diagnostic records
with allowlisted system error codes. Arbitrary text is omitted because a server can
echo private messages, schema labels, or answers; ordinary legacy stderr is unchanged.

The granted connection receives `mcp_form_request` privately. Its envelope contains
`sessionId`, `bindingEpoch`, `attachmentEpoch`, `grantId`, `dialogId`, `dialogToken`,
and `formRevision`; the request also carries `server` (`label` and `source`),
`message`, `schema`, and `deadlineAtMs`. The presenter returns that exact envelope
with `mcp_form_presented` only after rendering, then `mcp_form_response` with
`action: "accept" | "decline" | "cancel"` and accepted `content` when applicable.
`mcp_form_sync` uses the current session, binding epoch, attachment epoch, and grant
to recover the holder's still-live form. It is not a public replay API.

Unknown and stolen-dialog submissions from a non-holder both return
`presenter_not_authorized` before private dialog lookup. The host validates a whole
form before admitting a human answer. Each holder gets its own `dialogId`,
`dialogToken` and envelope. One synchronous terminal latch per form accepts only one
outcome: the first valid `mcp_form_response` from any holder wins, and a later response
is `form_stale`. `mcp_form_presented` from any holder marks the form presented.
Losing one holder ends only that holder's dialog. The form ends with presentation loss
only when its last holder is gone. `mcp_form_resolved` carries the session, grant,
dialog, and the winning reason: `answered`, `declined`, `cancelled`,
`processing_failed`, or `operation_aborted`. When another holder's action settled the
form, a grant that negotiated `elsewhere_v1` also gets `elsewhere: true`.
A grant without it sees exactly the earlier bytes.

After the latch, each `elsewhere_v1` holder of the form that is still current gets one
private `mcp_form_settled` record:
`{ type, sessionId, groupId, outcome, answeredBy? }`. `outcome` is the same reason.
`answeredBy` is present only when a holder's action settled the form. It contains
`principalKind` (`inherited` or `account`), `presenterKind`, and, for an account
principal, the attested `dev` and `dname`, never the self-declared `remoteOrigin`.
The record carries no message, schema, content, draft, token, or dialog, grant or
revision id. It is memory-only, and it goes only to those holders on the private lane:
never to a holder without `elsewhere_v1`, a `dialog_observer` subscription, the session
file, snapshots, replay, or logs.

No presenter, or loss before actual presentation, is a processing failure. Only
explicit human refusal produces decline. Dismissal after presentation is cancel;
host timeout or presentation loss after presentation also cancels, without human
admission. Operation abort terminates the operation. Private records, schemas,
tokens, drafts, and answers never enter general extension UI events, session
snapshots, replay, or ordinary output queues. Native desktop registration, WSL
relay, and a gateway form page require separate client implementation.

Extensions can request user interaction via `ctx.ui.select()`, `ctx.ui.confirm()`, etc. In RPC mode, these are translated into a request/response sub-protocol on top of the base command/event flow.

There are two categories of extension UI methods:

- **Dialog methods** (`select`, `confirm`, `input`, `editor`, `question`): emit an `extension_ui_request` on stdout and block until the client sends back an `extension_ui_response` on stdin with the matching `id`.
- **Fire-and-forget methods** (`notify`, `setStatus`, `setWidget`, `setTitle`, `set_editor_text`): emit an `extension_ui_request` on stdout but do not expect a response. The client can display the information or ignore it.

If a dialog method includes a `timeout` field, the agent-side will auto-resolve with a default value when the timeout expires. The host owns the timer and clients mirror the `remainingMs` value from each request or update event.

Some `ExtensionUIContext` methods are not supported or degraded in RPC mode because they require direct TUI access:
- `custom()` returns `undefined`
- `setWorkingMessage()`, `setWorkingIndicator()`, `setEditorComponent()`, `setToolsExpanded()`, `setHeader()`, and `setFooter()` are no-ops
- `setWidget()` forwards string-array widgets only; a component factory emits nothing
- `getEditorText()` returns `""`
- `getToolsExpanded()` returns `false`
- `pasteToEditor()` delegates to `setEditorText()` (no paste/collapse handling)
- `getAllThemes()` returns `[]`
- `getTheme()` returns `undefined`
- `setTheme()` returns `{ success: false, error: "..." }`

Note: `ctx.mode` is `"rpc"` and `ctx.hasUI` is `true` in RPC mode because the dialog and fire-and-forget methods are functional via the extension UI sub-protocol. Use `ctx.mode === "tui"` to guard TUI-specific features like `custom()` that require a real terminal.

### Extension UI Requests (stdout)

All requests have `type: "extension_ui_request"`, a unique `id`, and a `method` field.

#### select

Prompt the user to choose from a list. Dialog methods with a `timeout` field include the timeout in milliseconds; the agent auto-resolves with `undefined` if the client doesn't respond in time.

```json
{
  "type": "extension_ui_request",
  "id": "uuid-1",
  "method": "select",
  "title": "Allow dangerous command?",
  "options": ["Allow", "Block"],
  "timeout": 10000
}
```

Expected response: `extension_ui_response` with `value` (the selected option string) or `cancelled: true`.

A permission prompt (title `Permission required: <permission>`) also carries `toolCallId`, the id of the tool call it approves, and `parentToolCallId` when another tool (for example a codemode script) issued that call. Clients bind the prompt to that call by id: the engine raises the prompts for every call of a message before any of them runs, so the order of `tool_execution_start` events does not say which call a prompt belongs to. The `input` that follows a "Deny with feedback" choice carries the same fields.

```json
{
  "type": "extension_ui_request",
  "id": "uuid-3",
  "method": "select",
  "title": "Permission required: read\n\nPath: /project/a.txt\n\nPatterns:\n  - /project/a.txt",
  "options": ["Allow once", "Allow always", "Deny", "Deny with feedback"],
  "toolCallId": "call-a"
}
```

#### confirm

Prompt the user for yes/no confirmation.

```json
{
  "type": "extension_ui_request",
  "id": "uuid-2",
  "method": "confirm",
  "title": "Clear session?",
  "message": "All messages will be lost.",
  "timeout": 5000
}
```

Expected response: `extension_ui_response` with `confirmed: true/false` or `cancelled: true`.

#### input

Prompt the user for free-form text.

```json
{
  "type": "extension_ui_request",
  "id": "uuid-3",
  "method": "input",
  "title": "Enter a value",
  "placeholder": "type something..."
}
```

Expected response: `extension_ui_response` with `value` (the entered text) or `cancelled: true`.

#### editor

Open a multi-line text editor with optional prefilled content.

```json
{
  "type": "extension_ui_request",
  "id": "uuid-4",
  "method": "editor",
  "title": "Edit some text",
  "prefill": "Line 1\nLine 2\nLine 3"
}
```

Expected response: `extension_ui_response` with `value` (the edited text) or `cancelled: true`.

#### notify

Display a notification. Fire-and-forget, no response expected.

```json
{
  "type": "extension_ui_request",
  "id": "uuid-5",
  "method": "notify",
  "message": "Command blocked by user",
  "notifyType": "warning"
}
```

The `notifyType` field is `"info"`, `"warning"`, or `"error"`. Defaults to `"info"` if omitted.

#### setStatus

Set or clear a status entry in the footer/status bar. Fire-and-forget.

```json
{
  "type": "extension_ui_request",
  "id": "uuid-6",
  "method": "setStatus",
  "statusKey": "my-ext",
  "statusText": "Turn 3 running..."
}
```

Send `statusText: undefined` (or omit it) to clear the status entry for that key.

#### setSubagentCost

Report the USD the subagent tree under this session has spent, which the TUI footer shows after the session's own cost as `$0.380 (+1.270)`. Fire-and-forget.

```json
{
  "type": "extension_ui_request",
  "id": "uuid-7",
  "method": "setSubagentCost",
  "costUsd": 1.27
}
```

`costUsd: undefined` (or omitted) clears it. A negative or non-finite figure is sent as `undefined`.

#### setWidget

Set or clear a widget (block of text lines) displayed above or below the editor. Fire-and-forget.

```json
{
  "type": "extension_ui_request",
  "id": "uuid-7",
  "method": "setWidget",
  "widgetKey": "my-ext",
  "widgetLines": ["--- My Widget ---", "Line 1", "Line 2"],
  "widgetPlacement": "aboveEditor"
}
```

Send `widgetLines: undefined` (or omit it) to clear the widget. The `widgetPlacement` field is `"aboveEditor"` (default) or `"belowEditor"`. Only string-array widgets are sent; a component factory needs a terminal to render into and produces no record.

A widget may carry `widgetActions`, a list of `{ "label", "command" }` choices (for example the handoff hint's `{ "label": "Start fresh with a handoff", "command": "/handoff" }`). A client that renders a choice as a button sends its `command` text as an ordinary `prompt` when the user picks it, so the choice runs the same command handler the terminal user types. The field is omitted when the widget has no choices and on a clear.

#### setTitle

Set the terminal window/tab title. Fire-and-forget.

```json
{
  "type": "extension_ui_request",
  "id": "uuid-8",
  "method": "setTitle",
  "title": "senpi - my project"
}
```

#### set_editor_text

Set the text in the input editor. Fire-and-forget.

```json
{
  "type": "extension_ui_request",
  "id": "uuid-9",
  "method": "set_editor_text",
  "text": "prefilled text for the user"
}
```

#### question

Present one or more questions to the user. Requires the `question` client capability (advertised in `set_client_info`). Questions are broadcast to all attached connections, not just the requester. Pending questions survive the assistant message and are replayed to connections that attach later via `open_session` state.

Every `question` frame carries `raisedBy`: the `connectionId` whose command raised it (the same connection a `select`, `confirm`, `input` or `editor` raised at that point is delivered to; for a model tool call, the connection whose prompt started the turn), or `"agent"` when no connection's command started the work (for example a goal continuation, or a classic stdio session). A client uses it to tell a question it raised from one another connection raised; the frame still reaches every attached connection, and any of them may answer. The field is optional and additive: a client that ignores it is unaffected, and frames from older hosts omit it. The replayed frames in `pendingQuestions` carry the same value.

#### Remote origin

A relay forwarder that drives a session on behalf of another device opens its own connection for that device and declares, in that connection's `set_client_info`, which device it speaks for:

```json
{"type":"set_client_info","width":80,"remoteOrigin":{"deviceId":"device-a","deviceName":"Laptop"}}
```

`deviceId` is required and `deviceName` optional; both are non-empty strings of at most 256 characters, and no other key is accepted (`remote_origin_invalid`). A connection's origin is fixed once declared: repeating the same value is accepted, and a different one is refused `remote_origin_fixed` and leaves the declared origin unchanged. A connection that never declares one is local.

Every `select`, `confirm`, `input`, `editor` and `question` frame raised by that connection's command (for a model tool call, the connection whose prompt started the turn) carries the declared value as `remoteOrigin`, next to `raisedBy`. The mirrored `ui_request_pending` carries it inside `request`, and so do replayed pending dialogs. A dialog raised by a local connection carries no `remoteOrigin`, so absence means local. A client shows the label (for example "Requested from Laptop") so that the person at the host can tell a dialog a remote device's turn raised from their own. `set_client_info` is a connection-local method: a forwarder never forwards a remote device's own `set_client_info`, so a remote device cannot set or change the label. A secret `input` goes only to the connection that raised it and is not labeled.

```json
{
  "type": "extension_ui_request",
  "id": "uuid-q1",
  "method": "question",
  "requestId": "ask-user-1",
  "toolCallId": "call_abc123",
  "waitForAnswer": true,
  "raisedBy": "socket-1",
  "questions": [
    {
      "id": "q1",
      "header": "Database",
      "question": "Which database should I use?",
      "options": [
        { "label": "PostgreSQL", "description": "Relational" },
        { "label": "SQLite", "description": "Embedded" }
      ],
      "multiSelect": false
    }
  ],
  "timeout": 1800000,
  "askedAtMs": 1718000000000,
  "deadlineAtMs": 1718001800000,
  "remainingMs": 1799500
}
```

Expected response: `extension_ui_response` with `answers` (a map of question id to `{ selected: string[], text?: string }`) and an optional `comment`. Partial answers are allowed: the model is told which questions went unanswered, by header. Send `cancelled: true` to dismiss.

A multi-session host and a terminal control endpoint settle a `question` answer by one rule, so the same frame reaches the model as the same message on either surface:

- `cancelled: true` dismisses the question.
- Otherwise `answers` and `comment` are read; a `value` or `confirmed` in the same frame belongs to the other dialog methods and is ignored.
- A non-blank `comment` settles it `comment-submitted`: the model receives `The user responded: (see [The user's comment for question <id>] below)`, then any answered questions and the headers of the unanswered ones (`Unanswered: <header>, ...`), and the comment itself as a text block of its own after that. A frame that carries its text only as `comment` with `answers: {}` is a complete answer.
- The user's own words - the comment and any typed answer that is not one of the offered labels - never reach the model inside the tool result or beside the `[Answer to question <id>]` label: the text refers to each by its label (`(see [The user's comment for question <id>] below)`, `(see [The user's answer to <header> for question <id>] below)`), and each word follows as a text block after a block holding that label - after the batch's tool results for a blocking call (rebuilt from the persisted result's `details.userWords` on every request), or after the frame block of a later answer.
- Without a comment, any entry in `answers` settles it `answered`.
- Neither a non-blank comment nor an answer is refused `question_incomplete`, and the question stays pending.

A terminal refuses a frame whose `answers` is missing or malformed with `invalid_response`.

While the question is open, the client may send `extension_ui_progress` frames with draft `answers` and `comment`. Each progress frame resets the idle timer; the host emits `question_updated` with the refreshed `deadlineAtMs` and `remainingMs`.

Every progress frame then gets exactly one reply, keyed by the frame's `id` (the question's id), after that `question_updated`:

```json
{ "id": "uuid-q1", "type": "response", "command": "extension_ui_progress", "success": true }
```

A frame for a question that already resolved is answered `success: false` with `error: "question_already_resolved"`, and one for an id no open question holds with `error: "unknown_extension_ui_request"`; neither changes any question. A progress frame for a private input keeps its `invalid_secret_response` refusal. The reply lets a client that forwards records for someone else (a relay host, for example) settle every record it passes on from the engine's own reply, without a list of records that have none. `question_updated` is a frame, not the reply: match the reply by `type: "response"` and `id`. The typed `RpcClient` still sends progress without waiting, as it sends `extension_ui_response`, and consumes those replies itself.

When the question resolves (answered, comment-submitted, timed_out, or cancelled), the host broadcasts `question_resolved` to all connections:

```json
{
  "type": "question_resolved",
  "id": "uuid-q1",
  "requestId": "ask-user-1",
  "toolCallId": "call_abc123",
  "outcome": "answered",
  "resolvedBy": "rpc_connection",
  "answers": { "q1": { "selected": ["PostgreSQL"] } },
  "comment": "",
  "unanswered": []
}
```

A late answer after resolution receives a `question_already_resolved` error.

`resolvedBy` identifies the surface that submitted the winning answer: `local_ui` for the terminal
widget or composer, `rpc_connection` for an RPC client (including the sequential dialog fallback),
and `control_endpoint` for an answer received through the session's terminal control endpoint.
It is omitted for `timed_out` and `cancelled`, the frame's outcomes with no answering surface.
Restart orphaning and unavailable UI never reach `question_resolved` with their own status: an
extension that aborts the dialog for either is reported to connections as `cancelled`, and only the
tool result and the `ask-user:closed` extension event carry the true status. Clients do not supply
this field; the answering bridge sets it. Competing or late answers do not change the winner's surface.

The built-in `ask_user_question` and `request_user_input` tools retain the field in blocking
`tool_execution_end` result details and in the `response` of `ask-user:settled`. Extensions can
subscribe to `pi.events.on("ask-user:closed", handler)` for `{ requestId, status, resolvedBy? }`,
emitted once for every terminal outcome, including silent cancellations. `ask-user:settled`
continues to skip cancellation. A reload that preserves a pending question does not close it;
a terminal outcome while detached is published once through the next bound extension runner.

`RpcSessionState.pendingQuestions` (returned by `open_session` and `get_state`) lists any questions still waiting for an answer. Connections that attach after the question was asked receive the pending record immediately.

`RpcSessionState.pendingDialogs` lists the still-open select, confirm, input and editor request frames, including requests that remain live across `new_session`, `switch_session`, `fork`, `clone` and `import_jsonl`. The array is empty once all dialogs are resolved, cancelled or timed out. Clients recovering from a gap can restore these dialogs and remove dialogs absent from this authoritative snapshot.

Clients without the `question` capability get a sequential fallback: one `select` per question (options plus "Other (type an answer)", which asks one `input` for that question's typed answer). No comment prompt follows the last question. The result maps back to the same `QuestionResponse` without a `comment`: `answered` when at least one question was answered (the others listed in `unanswered`), `cancelled` when none was. An abort of the question's signal opens no further dialog and settles `cancelled` (or `timed_out` when the abort reason is `"timed_out"`), never `answered`, keeping the answers given before it.

### Extension UI Responses (stdin)

Responses are sent for dialog methods only (`select`, `confirm`, `input`, `editor`, `question`).

A response carries two ids:

- `uiRequestId` names the `extension_ui_request` being answered (its `id`).
- `id` is the response frame's own correlation id; the reply echoes it.

Without `uiRequestId`, `id` names the request too. That short form is what the examples below use and
what every older client sends; it keeps working unchanged.

Every response a multi-session host or a terminal control endpoint settles gets exactly one reply,
carrying the frame's `id`:

```json
{"id": "answer-1", "type": "response", "command": "extension_ui_response", "success": true}
```

`success: true` means the answer resolved a pending request. A refusal carries the same `id` and an
`error`: on a host `question_incomplete` (a `question` answer with neither answers nor a comment),
`question_already_resolved` (a late answer) or `unknown_extension_ui_request` (no request of that
session has that id); on a terminal `unknown_request`, `question_incomplete` or `invalid_response`. A single-session stdio
connection answers every response it resolves the same way, and ignores one that matches none of its
requests. A client may still fire and forget: the reply is an ordinary `response` record.

```json
{"type": "extension_ui_response", "id": "answer-1", "uiRequestId": "uuid-1", "value": "Allow"}
```

#### Value response (select, input, editor)

```json
{"type": "extension_ui_response", "id": "uuid-1", "value": "Allow"}
```

#### Confirmation response (confirm)

```json
{"type": "extension_ui_response", "id": "uuid-2", "confirmed": true}
```

#### Cancellation response (any dialog)

Dismiss any dialog method. The extension receives `undefined` (for select/input/editor) or `false` (for confirm).

```json
{"type": "extension_ui_response", "id": "uuid-3", "cancelled": true}
```

### UI-answer receipts and dialog observation

With capability `ui_answer_ledger`, `extension_ui_response` accepts an optional `answerId` string of 1-256 characters. The response preserves the frame's correlation `id` and adds `disposition`:

- `applied`: success; the pending request was settled once.
- `replay`: success; this `(uiRequestId, answerId)` pair was already applied, with no repeated delivery.
- `already_answered`: failure; the request was already settled with a different answer id.
- `unknown`: failure; no pending request or receipt exists (`unknown_extension_ui_request`).

A malformed answer (for example `invalid_answer_id` or `question_incomplete`) is refused without a `disposition` and leaves its request pending. A single-session stdio connection still ignores an unnamed response that matches no request; a named response always gets a reply.

`get_state.answeredUiRequests` contains the latest 64 receipts, oldest first, as `{uiRequestId, answerId?}`. Receipts are session-local and memory-only, retained for that session's life in the host generation. The ledger evicts FIFO beyond 1,024 requests; replay does not extend retention. Omitting `answerId` keeps the short-form answer contract but provides no named replay identity. A restart, unloaded session, or evicted receipt is not proof of non-execution.

With capability `dialog_observer`, `subscribe_sessions` accepts `dialogs?: boolean` (default false). A matching `dialogs: true` subscription must also enable `mirror`. It receives these new records on its connection FIFO:

`{type: "ui_request_pending", sessionId, uiRequestId, method, request}` when a dialog or question is registered, with its original request frame; `{type: "ui_request_settled", sessionId, uiRequestId, disposition: "answered" | "cancelled"}` when it settles. Timeout and lifecycle teardown count as cancellation. The feed survives the command connection's departure while the session remains loaded. A dialog already present in the snapshot is not emitted again.

The subscription remains observing: it creates no attachment and carries no correlated `response` records. The original select, confirm, input, and editor `extension_ui_request` records remain targeted, not mirrored. Use a separate attached command connection for answers; dialog observation grants no answering authority.

## Error Handling

Failed commands return a response with `success: false`:

```json
{
  "type": "response",
  "command": "set_model",
  "success": false,
  "error": "Model not found: invalid/model",
  "errorCode": "model_not_found"
}
```

Parse errors:

```json
{
  "type": "response",
  "command": "parse",
  "success": false,
  "error": "Failed to parse command: Unexpected token..."
}
```

## Types

Source files:
- [`packages/ai/src/types.ts`](../../ai/src/types.ts) - `Model`, `UserMessage`, `AssistantMessage`, `ToolResultMessage`
- [`packages/agent/src/types.ts`](../../agent/src/types.ts) - `AgentMessage`, `AgentEvent`
- [`src/core/messages.ts`](../src/core/messages.ts) - `BashExecutionMessage`
- [`src/modes/json-event.ts`](../src/modes/json-event.ts) - `JsonAgentSessionEvent`
- [`src/modes/rpc/rpc-types.ts`](../src/modes/rpc/rpc-types.ts) - RPC command/response types, extension UI request/response types

### Model

```json
{
  "id": "claude-sonnet-4-20250514",
  "name": "Claude Sonnet 4",
  "api": "anthropic-messages",
  "provider": "anthropic",
  "baseUrl": "https://api.anthropic.com",
  "reasoning": true,
	  "supportedThinkingLevels": ["off", "minimal", "low", "medium", "high"],
  "input": ["text", "image"],
  "contextWindow": 200000,
  "maxTokens": 16384,
  "cost": {
    "input": 3.0,
    "output": 15.0,
    "cacheRead": 0.3,
    "cacheWrite": 3.75
  }
}
```

| Field | Description |
| --- | --- |
| `supportedThinkingLevels` | Thinking levels accepted by this model. Non-reasoning models expose only `"off"`. |

### UserMessage

```json
{
  "role": "user",
  "content": "Hello!",
  "timestamp": 1733234567890,
  "attachments": []
}
```

The `content` field can be a string or an array of `TextContent`/`ImageContent` blocks.

### AssistantMessage

```json
{
  "role": "assistant",
  "content": [
    {"type": "text", "text": "Hello! How can I help?"},
    {"type": "thinking", "thinking": "User is greeting me..."},
    {"type": "toolCall", "id": "call_123", "name": "bash", "arguments": {"command": "ls"}}
  ],
  "api": "anthropic-messages",
  "provider": "anthropic",
  "model": "claude-sonnet-4-20250514",
  "usage": {
    "input": 100,
    "output": 50,
    "cacheRead": 0,
    "cacheWrite": 0,
    "cost": {"input": 0.0003, "output": 0.00075, "cacheRead": 0, "cacheWrite": 0, "total": 0.00105}
  },
  "stopReason": "stop",
  "timestamp": 1733234567890
}
```

Stop reasons: `"stop"`, `"length"`, `"toolUse"`, `"error"`, `"aborted"`

### ToolResultMessage

```json
{
  "role": "toolResult",
  "toolCallId": "call_123",
  "toolName": "bash",
  "content": [{"type": "text", "text": "total 48\ndrwxr-xr-x ..."}],
  "usage": {
    "input": 100,
    "output": 50,
    "cacheRead": 0,
    "cacheWrite": 0,
    "totalTokens": 150,
    "cost": {"input": 0.0003, "output": 0.00075, "cacheRead": 0, "cacheWrite": 0, "total": 0.00105}
  },
  "isError": false,
  "timestamp": 1733234567890
}
```

`usage` is optional and reports nested LLM work performed by the tool. When present, it contributes to session token and cost totals.

### BashExecutionMessage

Created by the `bash` RPC command (not by LLM tool calls):

```json
{
  "role": "bashExecution",
  "command": "ls -la",
  "output": "total 48\ndrwxr-xr-x ...",
  "exitCode": 0,
  "cancelled": false,
  "truncated": false,
  "fullOutputPath": null,
  "timestamp": 1733234567890
}
```

### Attachment

```json
{
  "id": "img1",
  "type": "image",
  "fileName": "photo.jpg",
  "mimeType": "image/jpeg",
  "size": 102400,
  "content": "base64-encoded-data...",
  "extractedText": null,
  "preview": null
}
```

## Example: Basic Client (Python)

```python
import subprocess
import json

proc = subprocess.Popen(
    ["senpi", "--mode", "rpc", "--no-session"],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    text=True
)

def send(cmd):
    proc.stdin.write(json.dumps(cmd) + "\n")
    proc.stdin.flush()

def read_events():
    for line in proc.stdout:
        yield json.loads(line)

# Send prompt
send({"type": "prompt", "message": "Hello!"})

# Process events
for event in read_events():
    if event.get("type") == "message_update":
        delta = event.get("assistantMessageEvent", {})
        if delta.get("type") == "text_delta":
            print(delta["delta"], end="", flush=True)
    
    if event.get("type") == "agent_end":
        print()
        break
```

## Example: Interactive Client (Node.js)

See [`test/rpc-example.ts`](../test/rpc-example.ts) for a complete interactive example, or [`src/modes/rpc/rpc-client.ts`](../src/modes/rpc/rpc-client.ts) for a typed client implementation.

For a complete example of handling the extension UI protocol, see [`examples/rpc-extension-ui.ts`](../examples/rpc-extension-ui.ts) which pairs with the [`examples/extensions/rpc-demo.ts`](../examples/extensions/rpc-demo.ts) extension.

```javascript
const { spawn } = require("child_process");
const { StringDecoder } = require("string_decoder");

const agent = spawn("senpi", ["--mode", "rpc", "--no-session"]);

function attachJsonlReader(stream, onLine) {
    const decoder = new StringDecoder("utf8");
    let buffer = "";

    stream.on("data", (chunk) => {
        buffer += typeof chunk === "string" ? chunk : decoder.write(chunk);

        while (true) {
            const newlineIndex = buffer.indexOf("\n");
            if (newlineIndex === -1) break;

            let line = buffer.slice(0, newlineIndex);
            buffer = buffer.slice(newlineIndex + 1);
            if (line.endsWith("\r")) line = line.slice(0, -1);
            onLine(line);
        }
    });

    stream.on("end", () => {
        buffer += decoder.end();
        if (buffer.length > 0) {
            onLine(buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer);
        }
    });
}

attachJsonlReader(agent.stdout, (line) => {
    const event = JSON.parse(line);

    if (event.type === "message_update") {
        const { assistantMessageEvent } = event;
        if (assistantMessageEvent.type === "text_delta") {
            process.stdout.write(assistantMessageEvent.delta);
        }
    }
});

// Send prompt
agent.stdin.write(JSON.stringify({ type: "prompt", message: "Hello" }) + "\n");

// Abort on Ctrl+C
process.on("SIGINT", () => {
    agent.stdin.write(JSON.stringify({ type: "abort" }) + "\n");
});
```
