Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(cli): add selectable tmux and Herdr backends

Hermes Agentd04c6a8bbffd
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index a2d2b968a..2400ff116 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -76,11 +76,13 @@ fail, which is also why forgetting them is easy:
```bash
npm run test:tmux-real # RUN_REAL_TMUX_DISCOVERY=1 — drives a real tmux server
+npm run test:herdr-real # RUN_REAL_HERDR=1 — drives isolated Herdr sessions/workspaces
npm run test:cursor-e2e # RUN_CURSOR_E2E=1 — needs a real cursor-agent CLI
```
-If your change touches how agents are discovered or driven, run `test:tmux-real` and say in the pull
-request that you did. It is the one suite that can tell you whether you broke everybody else's setup.
+If your change touches how agents are discovered or driven, run both real multiplexer suites for the
+software available on your machine and say exactly which versions and engine rows ran. A missing
+binary, credential, or onboarding step is an unavailable row, not a passing one.
### Adding an engine
@@ -92,31 +94,34 @@ into the tool feed — and each one passed its unit tests first.
### Adding a multiplexer
-Harness drives agents inside tmux today. A second multiplexer is welcome, on one condition: it is
-**added alongside tmux, not swapped in for it.** Every user's `registry.json` keys its agents by tmux
-pane id, so replacing the multiplexer orphans every running agent on upgrade. tmux stays the default,
-yours becomes a second implementation behind the same interface, and the one after that becomes a
-third instead of a third rewrite.
+Harness drives agents inside tmux and Herdr 0.8.x protocol 19. Another multiplexer is welcome, on one
+condition: it is **added alongside tmux, not swapped in for it.** Existing registries contain tmux
+pane identity, so replacing the multiplexer orphans running agents on upgrade. tmux stays the default,
+yours becomes another implementation behind the same interface instead of another rewrite.
Three things decide how much work this is, and the first one is not in this repository at all:
-1. **Can a process running inside a pane tell which pane it is in?** tmux exports `$TMUX_PANE`, and
- every engine's discovery hangs off it: the shell hooks in `cli/hook/notify.mjs` and the in-process
- plugins and extensions generated in `cli/src/lib/hooks.ts` all read it, and stay deliberately inert
- without it. If your multiplexer exports no per-pane identifier into the child environment, no
- abstraction on our side can rescue discovery. **Check this before writing anything else.**
-2. **Pane ids are validated.** `PANE_RE` in `cli/src/lib/registry.ts` accepts tmux's `%N` and nothing
- else. It has to widen without letting two multiplexers' ids ever collide.
-3. **The recap workers scrub the pane variable.** `cli/src/lib/oneshot.ts` deletes it before spawning
- an ephemeral summary run, so that run cannot register itself as an agent. Miss the equivalent for
- yours and every recap spawns a phantom agent — silent, and thoroughly unpleasant to trace.
-
-The command surface itself is small: list panes with their pid and working directory, send keys,
-capture the pane, display a message, create and kill sessions. Note that reading the conversation
-does **not** go through the multiplexer — each engine tails its own store on disk — so the scope is
-narrower than it first looks. What decides the difficulty is how well your multiplexer answers "read
-this pane" and "send keys to this pane", because that is what the question dialogs and the model
-pickers are driven with.
+1. **Can a process running inside a pane tell which pane it is in?** tmux exports `$TMUX_PANE`; Herdr
+ exports its pane, session, and socket context. The shell hooks in `cli/hook/notify.mjs` and the
+ in-process plugins and extensions generated in `cli/src/lib/hooks.ts` read typed hints and stay
+ deliberately inert without a verifiable configured runtime. If your multiplexer exports no
+ per-pane identifier into the child environment, no abstraction on our side can rescue discovery.
+ **Check this before writing anything else.**
+2. **Pane ids are validated and namespaced.** Identity must include the backend instance so public
+ pane ids from two multiplexers or configured endpoints cannot collide.
+3. **The recap workers scrub every backend's location variables.** `cli/src/lib/oneshot.ts` removes
+ them before spawning an ephemeral summary run, so that run cannot register itself as an agent.
+ Miss the equivalent for yours and every recap spawns a phantom agent — silent, and thoroughly
+ unpleasant to trace.
+
+The command surface itself is small: list panes with their pid and working directory, send literal
+text and logical keys, capture the pane, display a message, and create and kill sessions/workspaces.
+Lifecycle methods are explicit backend capabilities for callers that request them; normal Harness
+startup does not create user sessions, and deleting an agent does not close its pane. Note that
+reading the conversation does **not** go through the multiplexer — each engine tails its own store on
+disk — so the scope is narrower than it first looks. What decides the difficulty is how well your
+multiplexer answers "read this pane" and "send keys to this pane", because that is what the question
+dialogs and the model pickers are driven with.
## Found a gap in the spec?
diff --git a/README.md b/README.md
index 4b24e59e6..a059b8b9d 100644
--- a/README.md
+++ b/README.md
@@ -137,11 +137,11 @@ cd cli && npm install && npm run typecheck && npm test
### 2. Add a terminal multiplexer
-Harness uses tmux today; another multiplexer such as Herdr must be added alongside it, not replace
-it. Before coding, confirm that a process inside a pane can identify that pane with a stable,
-multiplexer-namespaced id. The integration must support listing panes with their PID and working
-directory, sending literal text and keys, capturing pane output, displaying a message, and creating
-and killing sessions.
+Harness supports additive tmux and Herdr 0.8.x protocol 19 backends, with tmux as the default. Another
+multiplexer must be added alongside them, not replace them. Before coding, confirm that a process
+inside a pane can identify that pane with a stable, multiplexer-namespaced id. The integration must
+support listing panes with their PID and working directory, sending literal text and keys, capturing
+pane output, displaying a message, and creating and killing sessions.
The contribution must also carry the new pane identity through process discovery, registry
persistence and hooks, and scrub it from recap workers so they cannot register as phantom agents.
@@ -151,6 +151,7 @@ then run the normal CLI checks plus the real multiplexer discovery suite:
```bash
cd cli && npm install && npm run typecheck && npm test
npm run test:tmux-real
+npm run test:herdr-real
```
## Security and licence
diff --git a/cli/.env.example b/cli/.env.example
index b2dd3cb98..100798220 100644
--- a/cli/.env.example
+++ b/cli/.env.example
@@ -15,13 +15,19 @@ PORT=18473
# Directory Claude Code writes its per-session JSONL transcripts to.
# CLAUDE_PROJECTS_DIR=/Users/you/.claude/projects
-# Where the tmux-session registry + pair token are persisted.
+# Where the process-agent registry + pair token are persisted.
# ADAPTER_DATA_DIR=~/.harness/cli/data
# Set to 'true' to skip auto-installing the claude hooks on startup.
# DISABLE_HOOK_INSTALL=false
-# How often (ms) the reaper drops sessions whose tmux pane is gone.
+# Terminal backends are additive and ordered. tmux remains the default.
+# TERMINAL_BACKENDS=tmux # tmux | herdr | tmux,herdr
+# HERDR_SESSIONS=default # ordered configured local named sessions
+# HERDR_BIN=herdr # used only for non-sensitive session discovery/diagnostics
+# TERMINAL_RECONCILE_INTERVAL_MS=5000 # minimum 5000; neutral replacement for the legacy name below
+
+# One-release compatibility fallback when TERMINAL_RECONCILE_INTERVAL_MS is unset.
# TMUX_REAP_INTERVAL_MS=5000
# Device turn-recap (commander summary card). Only runs while a device is connected.
@@ -39,3 +45,6 @@ PORT=18473
# ADAPTER_UPDATE_CHECK_MS=60000 # poll interval (ms); a check also runs on start
# ADAPTER_UPDATE_DISABLE=false # set 'true' to turn self-update off
# ADAPTER_CLI_DIR=~/.harness/cli # install dir the updater swaps cli.js/notify.mjs in
+
+# Until a Herdr-capable build is upstream, a custom installed bundle must use a fork-owned signed
+# ADAPTER_UPDATE_URL or set ADAPTER_UPDATE_DISABLE=true so upstream cannot replace it with a tmux-only build.
diff --git a/cli/README.md b/cli/README.md
index 82924fcbf..01b787488 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -2,17 +2,17 @@
**Run the coding-agent CLIs you already use, and drive them from anywhere.**
-`harness` watches the agent sessions you start in **tmux** on your own machine and bridges them to a
+`harness` watches the agent sessions you start in **tmux, Herdr, or both** on your own machine and bridges them to a
web UI and, optionally, to a paired hardware device. The agents keep running as your processes, in
your terminal, with your credentials; this is a bridge, not a wrapper.
It works with the popular coding agents — [`src/engines/`](src/engines/) is the current list, one
folder per agent, and yours can join them.
-- Every agent you open in a tmux pane shows up as an agent you can talk to from the browser.
+- Every supported agent process under a configured terminal backend shows up as one agent you can talk to from the browser.
- Turns, tool calls, todo lists and sub-agents stream out as they happen.
- The browser channel is end-to-end encrypted (see `src/lib/e2ee/`).
-- One self-contained bundle, no native dependencies: Node ≥ 20 and `tmux` are all you need.
+- One self-contained bundle with no Node native dependencies. Node ≥ 20 plus tmux and/or Herdr 0.8.x is required.
## Install & run (`harness`)
@@ -50,6 +50,10 @@ build, downloads + verifies + swaps its own bundle and restarts when idle (with
build). See [`RELEASE.md`](RELEASE.md) for publishing and the update internals. Disable with
`ADAPTER_UPDATE_DISABLE=true`.
+Custom Herdr-capable builds must keep self-update disabled or use a fork-owned signed
+`ADAPTER_UPDATE_URL` until that build is available in the configured upstream manifest. Otherwise the
+updater can legitimately replace the custom bundle with a release that lacks its terminal support.
+
**From source (dev):** `cd this package && npm install && npm run build && node dist/cli.js join <token>`
(or `npm run dev -- join` via tsx — always foreground; self-update is off in dev). `npm run bundle`
produces the single-file release artifact.
@@ -60,39 +64,43 @@ daemon on it, so `harness` on this computer means your code without publishing a
turned **off** in the command shim it writes (otherwise the published release overwrites your build within
the minute). See [`RELEASE.md`](RELEASE.md#local-install-no-upload).
-After joining, start each agent yourself in tmux with its normal vendor command. Harness observes the
+After joining, start each agent yourself in tmux or a configured Herdr session with its normal vendor command. Harness observes the
process; it does not launch the CLI or choose its permission/trust flags:
```bash
tmux new
claude # or: codex, agent, opencode, pi, hermes, cmd, devin, muse, amp, kilo, grok
+
+# Or, after starting a named Herdr session through Herdr itself:
+TERMINAL_BACKENDS=herdr HERDR_SESSIONS=default harness join
```
-Each supported top-level CLI process in a pane appears automatically. Exiting the CLI removes only the
-agent; the tmux pane and its shell remain yours.
+Each supported top-level CLI process appears automatically. Exiting or deleting the agent stops only
+the validated engine process; Harness never closes the user-owned tmux or Herdr pane.
## How it works
```
-claude in tmux pane %3 ──writes──▶ ~/.claude/projects/**.jsonl
+claude under a terminal backend ──writes──▶ ~/.claude/projects/**.jsonl
▲ │ chokidar + byte-offset tail (only new lines)
- │ sendToTmux (tmux send-keys) ▼ normalize → ServerEvents (+ derived turn lifecycle)
+ │ backend input contract ▼ normalize → ServerEvents (+ derived turn lifecycle)
adapter CLI ◀────── down:{agentId} ── backend /api/adapter-ws ── up:{agentId} ──▶ web chat
```
- **The adapter emulates a node** on the backend hub: it answers the hosted runtime RPCs
- (`agents_list` = discovered tmux processes, `sessions_list`, `session_get` = full JSONL
+ (`agents_list` = discovered engine processes, `sessions_list`, `session_get` = full JSONL
replay, `project_files`/`project_read_file` = the session's cwd file tree + file view,
`models_list`, `claude_login_status`) and consumes web chat frames.
- **Files panel** (`project_files`/`project_read_file`): rooted at the tmux session's working dir,
it lists the tree (ignoring `node_modules`/`.git`/`dist`/… like the hosted runtime) and views a file only
if it's **≤ 5 MB and text** (binary → rejected). The same guard was added to the hosted runtime so
both behave identically.
-- **Process discovery is lifetime authority.** On startup and every five seconds the daemon reads all
- tmux panes once and the process table once. A supported top-level engine creates an agent immediately,
+- **Process discovery is lifetime authority.** On startup and every five seconds the daemon reads each
+ configured terminal inventory and one shared process table. A supported top-level engine creates an agent immediately,
before an engine session exists. A changed process in the same pane replaces it immediately; an absent
process is removed after two successful scans. Probe failures do not remove anything.
-- **Hooks bind mutable engine sessions** to the process agent (tmux-only via `$TMUX_PANE`). They do not
+- **Hooks bind mutable engine sessions** to the process agent using authenticated tmux and/or Herdr
+ runtime hints plus verified caller ancestry. Hook socket paths are lookup hints only. They do not
require `MACHINE_ID`. `SessionStart` and catch hooks attach transcript/store metadata; `SessionEnd` only
requests an immediate process reconciliation. `/clear`, `/new`, and resume move or rotate the binding
without changing the live process agent's UUID.
@@ -108,8 +116,40 @@ claude in tmux pane %3 ──writes──▶ ~/.claude/projects/**.jsonl
`isCompactSummary` summary line and any `isMeta` bookkeeping line are **suppressed via those
authoritative flags** (`compactEventFromRaw` in `lib/normalize.ts`) so the summary is never rendered
as a fake user turn — an auto-compact firing mid-turn keeps the open turn open.
-- A web chat message arrives as a `message` frame → injected into the session's pane via
- `tmux send-keys -l <text>` + `Enter`.
+- A web chat message arrives as a `message` frame and is submitted through one validated primary runtime.
+ Herdr prompt bytes use its bounded local socket API and never command-line arguments or environment.
+
+### Terminal backend behavior
+
+- `TERMINAL_BACKENDS` is a strict ordered list: `tmux`, `herdr`, or `tmux,herdr`. The default is `tmux`.
+- `HERDR_SESSIONS` is an ordered list of local named sessions. Harness never auto-starts a session and
+ never connects to a socket supplied only by a hook. Herdr support is pinned to compatible 0.8.x,
+ protocol 19.
+- The shared backend contract can create and close a tmux session or Herdr workspace when explicitly
+ invoked. This is lifecycle capability, not automatic startup behavior; normal discovery observes
+ user-owned sessions, and agent deletion still terminates only the validated engine process.
+- One process visible through nested/coexisting backends remains one Harness agent with multiple runtime
+ locators. A Herdr workspace move preserves its stable terminal identity; an engine process replacement does not.
+- Backend and endpoint failures are independent. A failed probe is `unknown`, not proof of death. An
+ agent with no verified runtime becomes dormant and is republished with the same id after recovery.
+- Existing `tmuxPane` registry rows migrate in place. tmux rows retain their legacy projection during
+ the compatibility window; Herdr-only rows never claim a tmux pane. For code rollback, stop the daemon,
+ archive the mixed registry, and give the old binary a copied tmux-only projection.
+
+For reproducible multiplexer verification, install dependencies and run both opt-in real suites from
+`cli/` under a normal umask:
+
+```bash
+umask 022
+npm ci
+npm run test:tmux-real
+npm run test:herdr-real
+```
+
+The Herdr suite requires Herdr 0.8.x protocol 19. Both suites use isolated, test-owned lifecycle
+fixtures. Their engine matrix explicitly skips commands that are not installed; authentication or
+first-run onboarding that prevents a proprietary CLI from running is unavailable evidence and must be
+reported as such, not described as exercised.
## Config (`.env`, see `.env.example`)
@@ -121,6 +161,10 @@ claude in tmux pane %3 ──writes──▶ ~/.claude/projects/**.jsonl
| `CLAUDE_PROJECTS_DIR` | `~/.claude/projects` | where Claude writes session JSONL |
| `ADAPTER_DATA_DIR` | `~/.harness/cli/data` | registry + token persistence |
| `DISABLE_HOOK_INSTALL` | `false` | skip auto-installing the claude hooks |
+| `TERMINAL_BACKENDS` | `tmux` | strict ordered list: `tmux`, `herdr`, or `tmux,herdr` |
+| `HERDR_SESSIONS` | `default` | ordered configured local named Herdr sessions |
+| `HERDR_BIN` | `herdr` | Herdr executable used only for session discovery/diagnostics |
+| `TERMINAL_RECONCILE_INTERVAL_MS` | `5000` | backend-neutral discovery interval; minimum 5000 ms |
| `TMUX_REAP_INTERVAL_MS` | `5000` | process discovery interval (removal requires two confirmed misses) |
| `ADAPTER_UPDATE_URL` | `…/adapter/metadata.json` | GCS release manifest the daemon polls for a newer build |
| `ADAPTER_UPDATE_KEY` | `cli` | manifest key for this CLI |
diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjs
index 8a8d120df..9ac4b39a8 100644
--- a/cli/hook/notify.mjs
+++ b/cli/hook/notify.mjs
@@ -5,9 +5,9 @@
* Self-contained — node built-ins only, no dependency on the adapter's
* node_modules (it runs inside the user's `claude` process).
*
- * SessionStart: registers { tmuxPane, sessionId, transcriptPath, cwd } with the
- * adapter — but only when running inside tmux ($TMUX_PANE set).
- * SessionEnd: asks the adapter to reconcile the pane; process discovery remains
+ * SessionStart: registers terminal hints plus session metadata with the adapter,
+ * but only from an authenticated tmux or configured Herdr context.
+ * SessionEnd: asks the adapter to reconcile the terminal; process discovery remains
* the authority for whether the agent exists.
*
* Always exits 0 quickly and swallows every error, so it can never block or
@@ -15,13 +15,18 @@
*/
import http from 'node:http'
-import { execFile } from 'node:child_process'
+import { execFile, execFileSync } from 'node:child_process'
import { randomUUID } from 'node:crypto'
+import { createConnection } from 'node:net'
import {
accessSync,
closeSync,
constants,
+ fchmodSync,
+ fstatSync,
+ fsyncSync,
mkdirSync,
+ lstatSync,
openSync,
readFileSync,
readdirSync,
@@ -32,18 +37,24 @@ import {
statSync,
writeFileSync,
} from 'node:fs'
-import { basename, delimiter, dirname, isAbsolute, join, relative, sep } from 'node:path'
+import { basename, delimiter, dirname, isAbsolute, join, parse, relative, resolve, sep } from 'node:path'
import { homedir, uptime } from 'node:os'
const BOOT_TOLERANCE_SEC = 120
-const LOCK_STALE_MS = 5000
-const LOCK_RETRIES = 20
+const HOOK_STARTED_AT = performance.now()
+const HOOK_DEADLINE_MS = 4500
+const EXIT_RESERVE_MS = 500
+const LOCK_RETRIES = 60
const LOCK_RETRY_MS = 25
const CURSOR_TASK_MAX_AGE_MS = 10 * 60_000
const CURSOR_TASK_MAX_ENTRIES = 64
const CURSOR_TASK_MAX_INPUT_BYTES = 128 * 1024
const CODEX_META_MAX_BYTES = 128 * 1024
+function remainingBudget(reserve = EXIT_RESERVE_MS) {
+ return Math.max(0, HOOK_DEADLINE_MS - (performance.now() - HOOK_STARTED_AT) - reserve)
+}
+
// Claude Code reports the model as {id, display_name}; Codex/Cursor as a plain string. The registry stores
// a string, so pick the id rather than shipping the object.
function modelName(value) {
@@ -162,14 +173,20 @@ function readStdin() {
function post(port, path, body) {
return new Promise((resolve) => {
const payload = JSON.stringify(body)
+ const credential = readHookCredential()
+ if (!credential) { resolve(false); return }
const req = http.request(
{
host: '127.0.0.1',
port,
path,
method: 'POST',
- headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) },
- timeout: 1500,
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Content-Length': Buffer.byteLength(payload),
+ 'X-Harness-Hook-Token': credential,
+ },
+ timeout: Math.max(1, Math.min(500, remainingBudget())),
},
(res) => {
res.resume()
@@ -186,13 +203,102 @@ function post(port, path, body) {
})
}
+function secureStateDirectory(directory, create = true) {
+ if (create) mkdirSync(directory, { recursive: true, mode: 0o700 })
+ const fd = openSync(directory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW)
+ try {
+ const stat = fstatSync(fd)
+ const uid = typeof process.getuid === 'function' ? process.getuid() : null
+ if (!stat.isDirectory() || (uid !== null && stat.uid !== uid)) {
+ throw new Error('state directory has unsafe owner or type')
+ }
+ const mode = stat.mode & 0o777
+ if (mode & 0o022) throw new Error('state directory is group/world writable')
+ if (mode !== 0o700) {
+ fchmodSync(fd, 0o700)
+ if ((fstatSync(fd).mode & 0o777) !== 0o700) {
+ throw new Error('state directory permissions could not be tightened')
+ }
+ }
+ } finally { closeSync(fd) }
+}
+
+function inspectPrivateStateFile(fd, maxBytes = Number.MAX_SAFE_INTEGER) {
+ const stat = fstatSync(fd)
+ const uid = typeof process.getuid === 'function' ? process.getuid() : null
+ if (!stat.isFile() || (uid !== null && stat.uid !== uid)) throw new Error('state file has unsafe owner or type')
+ if (stat.size > maxBytes) throw new Error('state file exceeds its size limit')
+ const mode = stat.mode & 0o777
+ if (mode & 0o022) throw new Error('state file is group/world writable')
+ if (mode !== 0o600) {
+ fchmodSync(fd, 0o600)
+ if ((fstatSync(fd).mode & 0o777) !== 0o600) {
+ throw new Error('state file permissions could not be tightened')
+ }
+ }
+}
+
+function readPrivateStateFile(file, maxBytes = Number.MAX_SAFE_INTEGER) {
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
+ try {
+ inspectPrivateStateFile(fd, maxBytes)
+ return readFileSync(fd, 'utf8')
+ } finally { closeSync(fd) }
+}
+
+function hardenPrivateStateFileIfPresent(file, maxBytes = Number.MAX_SAFE_INTEGER) {
+ let fd
+ try {
+ fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
+ } catch (error) {
+ if (error?.code === 'ENOENT') return false
+ throw error
+ }
+ try {
+ inspectPrivateStateFile(fd, maxBytes)
+ return true
+ } finally { closeSync(fd) }
+}
+
+function readHookCredential() {
+ let fd = null
+ try {
+ const dataDir = paths().dataDir
+ secureStateDirectory(dataDir, false)
+ const uid = typeof process.getuid === 'function' ? process.getuid() : null
+ const file = join(dataDir, 'hook-credential')
+ fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
+ const stat = fstatSync(fd)
+ if (!stat.isFile() || stat.size > 128 || (stat.mode & 0o777) !== 0o600) return ''
+ if (uid !== null && stat.uid !== uid) return ''
+ const value = readFileSync(fd, 'utf8').trim()
+ return /^[A-Za-z0-9_-]{43}$/.test(value) ? value : ''
+ } catch { return '' } finally {
+ if (fd !== null) closeSync(fd)
+ }
+}
+
+function terminalHookFields(tmuxPane) {
+ const runtimeHints = []
+ if (tmuxPane) runtimeHints.push({ backend: 'tmux', paneId: tmuxPane })
+ if (process.env.HERDR_PANE_ID) runtimeHints.push({
+ backend: 'herdr',
+ paneId: process.env.HERDR_PANE_ID,
+ sessionName: process.env.HERDR_SESSION,
+ socketPath: process.env.HERDR_SOCKET_PATH,
+ })
+ return { tmuxPane, runtimeHints, callerPid: process.ppid }
+}
+
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
function execFileText(cmd, args, timeout) {
return new Promise((resolve) => {
- execFile(cmd, args, { timeout }, (err, stdout) => {
+ const budget = Math.min(timeout, remainingBudget())
+ if (budget < 50) { resolve(null); return }
+ execFile(cmd, args, { timeout: budget }, (err, stdout) => {
resolve(err ? null : stdout)
})
})
@@ -398,6 +504,10 @@ async function paneEngineProcess(pane, engine) {
const rootPid = await panePid(pane)
if (rootPid === undefined) return { state: 'unknown' }
if (!rootPid) return { state: 'gone' }
+ return rootEngineProcess(rootPid, engine)
+}
+
+async function rootEngineProcess(rootPid, engine) {
const rawRows = await processRows()
if (!rawRows) return { state: 'unknown' }
const rows = await enrichProcessImages(rawRows)
@@ -426,6 +536,119 @@ async function paneEngineProcess(pane, engine) {
} : { state: 'gone' }
}
+function safePathComponents(path) {
+ const root = parse(path).root
+ const result = [root]
+ for (const component of path.slice(root.length).split(sep).filter(Boolean)) {
+ result.push(resolve(result[result.length - 1], component))
+ }
+ return result
+}
+
+function readTerminalSnapshot(p) {
+ try {
+ const file = join(p.dataDir, 'terminal-config.json')
+ secureStateDirectory(p.dataDir, false)
+ const snapshot = JSON.parse(readPrivateStateFile(file, 64 * 1024))
+ if (snapshot?.version !== 1 || !Array.isArray(snapshot.backends) || !Array.isArray(snapshot.herdrEndpoints)) return null
+ return snapshot
+ } catch { return null }
+}
+
+function checkedHerdrEndpoint(endpoint) {
+ try {
+ if (!endpoint || typeof endpoint.socketPath !== 'string' || !isAbsolute(endpoint.socketPath)) return false
+ const uid = typeof process.getuid === 'function' ? process.getuid() : null
+ if (uid === null) return false
+ for (const component of safePathComponents(dirname(endpoint.socketPath))) {
+ const stat = lstatSync(component)
+ if (!stat.isDirectory() || stat.isSymbolicLink() || (stat.uid !== uid && stat.uid !== 0)) return false
+ if ((stat.mode & 0o002) || (stat.uid === 0 && (stat.mode & 0o020))) return false
+ }
+ const parent = lstatSync(dirname(endpoint.socketPath))
+ const socket = lstatSync(endpoint.socketPath)
+ if (parent.uid !== uid || !socket.isSocket() || socket.isSymbolicLink() || socket.uid !== uid || (socket.mode & 0o777) !== 0o600) return false
+ if (realpathSync(endpoint.socketPath) !== resolve(endpoint.socketPath)) return false
+ return socket.dev === endpoint.generation?.device && socket.ino === endpoint.generation?.inode
+ } catch { return false }
+}
+
+function herdrRequest(endpoint, method, params) {
+ return new Promise((resolveRequest) => {
+ const budget = Math.min(1500, remainingBudget())
+ if (budget < 50 || !checkedHerdrEndpoint(endpoint)) { resolveRequest(null); return }
+ const id = randomUUID()
+ const frame = Buffer.from(`${JSON.stringify({ id, method, params })}\n`)
+ if (frame.byteLength > 1024 * 1024) { resolveRequest(null); return }
+ let response = Buffer.alloc(0)
+ let settled = false
+ let socket
+ const finish = (value) => {
+ if (settled) return
+ settled = true
+ clearTimeout(timer)
+ socket?.destroy()
+ resolveRequest(value)
+ }
+ const timer = setTimeout(() => finish(null), budget)
+ try { socket = createConnection({ path: endpoint.socketPath }) } catch { finish(null); return }
+ socket.once('connect', () => {
+ if (!checkedHerdrEndpoint(endpoint)) { finish(null); return }
+ try { socket.end(frame) } catch { finish(null) }
+ })
+ socket.on('data', (chunk) => {
+ response = Buffer.concat([response, chunk])
+ if (response.byteLength > 1024 * 1024) { finish(null); return }
+ const newline = response.indexOf(0x0a)
+ if (newline < 0) return
+ if (response.subarray(newline + 1).toString('utf8').trim()) { finish(null); return }
+ try {
+ const parsed = JSON.parse(response.subarray(0, newline).toString('utf8'))
+ finish(parsed?.id === id && parsed.result && !parsed.error ? parsed.result : null)
+ } catch { finish(null) }
+ })
+ socket.once('end', () => finish(null))
+ socket.once('error', () => finish(null))
+ })
+}
+
+async function herdrFallbackRuntime(engine) {
+ const hint = terminalHookFields(process.env.TMUX_PANE).runtimeHints.find((runtime) => runtime.backend === 'herdr')
+ if (!hint?.sessionName || !hint.socketPath || !hint.paneId) return null
+ const snapshot = readTerminalSnapshot(paths())
+ if (!snapshot?.backends.includes('herdr')) return null
+ const endpoint = snapshot.herdrEndpoints.find((candidate) =>
+ candidate?.sessionName === hint.sessionName && candidate?.socketPath === hint.socketPath)
+ if (!endpoint || !checkedHerdrEndpoint(endpoint)) return null
+ const pong = await herdrRequest(endpoint, 'ping', {})
+ if (pong?.type !== 'pong' || pong.protocol !== 19 || !/^0\.8\./.test(String(pong.version || ''))) return null
+ const [pane, info] = await Promise.all([
+ herdrRequest(endpoint, 'pane.get', { pane_id: hint.paneId }),
+ herdrRequest(endpoint, 'pane.process_info', { pane_id: hint.paneId }),
+ ])
+ if (pane?.type !== 'pane_info' || typeof pane.pane?.terminal_id !== 'string'
+ || info?.type !== 'pane_process_info' || !Number.isSafeInteger(info.process_info?.shell_pid)) return null
+ const owner = await rootEngineProcess(info.process_info.shell_pid, engine)
+ if (owner.state !== 'alive' || !owner.identity) return null
+ const rows = await processRows()
+ if (!rows) return null
+ const parents = new Map(rows.map((row) => [row.pid, row.parentPid]))
+ let caller = process.ppid
+ const visited = new Set()
+ while (caller > 0 && !visited.has(caller) && caller !== owner.identity.pid) {
+ visited.add(caller)
+ caller = parents.get(caller) || 0
+ }
+ if (caller !== owner.identity.pid) return null
+ return {
+ identity: owner.identity,
+ runtime: {
+ backend: 'herdr', endpointId: endpoint.endpointId, sessionName: endpoint.sessionName,
+ terminalId: pane.pane.terminal_id, paneId: pane.pane.pane_id,
+ },
+ }
+}
+
/**
* Hermes delegation children execute the same pane-scoped hook as the visible CLI session. During
* daemon downtime the regular hook server cannot apply its source guard, so consult Hermes' own store
@@ -458,27 +681,58 @@ function bootTimeSec() {
return Math.round(Date.now() / 1000 - uptime())
}
+function currentBootId() {
+ try {
+ const value = readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim()
+ if (/^[0-9a-f-]{36}$/i.test(value)) return `linux:${value}`
+ } catch { /* non-Linux fallback below */ }
+ return `time:${bootTimeSec()}`
+}
+
function readSavedBoot(bootFile) {
try {
- const n = Number(readFileSync(bootFile, 'utf-8').trim())
- return Number.isFinite(n) ? n : null
+ secureStateDirectory(dirname(bootFile), false)
+ const raw = readPrivateStateFile(bootFile, 256).trim()
+ if (!raw) return null
+ try {
+ const parsed = JSON.parse(raw)
+ return typeof parsed === 'string' ? parsed : raw
+ } catch { return raw }
} catch {
return null
}
}
function writeBoot(bootFile) {
+ let tmp = ''
+ let renamed = false
try {
- mkdirSync(dirname(bootFile), { recursive: true })
- writeFileSync(bootFile, String(bootTimeSec()))
+ secureStateDirectory(dirname(bootFile))
+ hardenPrivateStateFileIfPresent(bootFile, 256)
+ tmp = `${bootFile}.${process.pid}.${randomUUID()}.tmp`
+ const fd = openSync(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)
+ try { writeFileSync(fd, currentBootId()); fsyncSync(fd) } finally { closeSync(fd) }
+ renameSync(tmp, bootFile)
+ renamed = true
+ const directoryFd = openSync(dirname(bootFile), 'r')
+ try { fsyncSync(directoryFd) } finally { closeSync(directoryFd) }
} catch {
// best effort
+ } finally {
+ if (tmp && !renamed) {
+ try { rmSync(tmp, { force: true }) } catch { /* best effort */ }
+ }
}
}
function rebootedSinceSnapshot(bootFile) {
const saved = readSavedBoot(bootFile)
- return saved !== null && Math.abs(bootTimeSec() - saved) > BOOT_TOLERANCE_SEC
+ if (saved === null) return false
+ const current = currentBootId()
+ if (saved.startsWith('linux:')) return saved !== current
+ const savedNumber = Number(saved.replace(/^time:/, ''))
+ const currentNumber = current.startsWith('time:') ? Number(current.slice(5)) : bootTimeSec()
+ return !Number.isFinite(savedNumber) || Math.abs(currentNumber - savedNumber) > BOOT_TOLERANCE_SEC
}
function isWithin(root, file) {
@@ -534,43 +788,141 @@ function isCodexSubagent(input, p) {
}
}
+function removeLockOwnedBy(lockDir, token) {
+ try {
+ const owner = JSON.parse(readFileSync(join(lockDir, 'owner.json'), 'utf8'))
+ if (owner?.token === token) rmSync(lockDir, { recursive: true, force: true })
+ } catch { /* another owner or unsafe artifact must not be removed */ }
+}
+
+function processStartMarker(pid) {
+ if (!Number.isSafeInteger(pid) || pid <= 0) return null
+ try {
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8')
+ const fields = stat.slice(stat.lastIndexOf(')') + 2).trim().split(/\s+/)
+ if (fields[19]) return `linux:${fields[19]}`
+ } catch { /* non-Linux or exited process; use ps below */ }
+ try {
+ const started = execFileSync('ps', ['-p', String(pid), '-o', 'lstart='], {
+ encoding: 'utf8', timeout: 1000,
+ }).trim()
+ return started ? `ps:${started}` : null
+ } catch { return null }
+}
+
+function processAlive(pid, startMarker = '') {
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false
+ try { process.kill(pid, 0) } catch (error) { if (error?.code !== 'EPERM') return false }
+ if (!startMarker) return true
+ const current = processStartMarker(pid)
+ return current === null || current === startMarker
+}
+
async function withRegistryLock(registryFile, fn) {
const lockDir = `${registryFile}.lock`
- try { mkdirSync(dirname(registryFile), { recursive: true }) } catch { return }
+ const dataDir = dirname(registryFile)
+ try {
+ secureStateDirectory(dataDir)
+ } catch { return }
+ const processMarker = processStartMarker(process.pid) || ''
for (let i = 0; i < LOCK_RETRIES; i++) {
+ if (remainingBudget(750) < 50) return
+ const token = randomUUID()
+ let created = false
try {
- mkdirSync(lockDir)
+ mkdirSync(lockDir, { mode: 0o700 })
+ created = true
+ const ownerFile = join(lockDir, 'owner.json')
+ const ownerFd = openSync(ownerFile, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)
+ try {
+ writeFileSync(ownerFd, JSON.stringify({ pid: process.pid, startMarker: processMarker, token }))
+ fsyncSync(ownerFd)
+ } finally { closeSync(ownerFd) }
try {
return fn()
} finally {
- try { rmSync(lockDir, { recursive: true, force: true }) } catch { /* ignore */ }
+ removeLockOwnedBy(lockDir, token)
}
- } catch {
+ } catch (error) {
+ if (created) removeLockOwnedBy(lockDir, token)
+ if (error?.code !== 'EEXIST') return
try {
- const st = statSync(lockDir)
- if (Date.now() - st.mtimeMs > LOCK_STALE_MS) rmSync(lockDir, { recursive: true, force: true })
+ const uid = typeof process.getuid === 'function' ? process.getuid() : null
+ const st = lstatSync(lockDir)
+ const ownerStat = lstatSync(join(lockDir, 'owner.json'))
+ if (!st.isDirectory() || st.isSymbolicLink() || (uid !== null && st.uid !== uid) || (st.mode & 0o777) !== 0o700
+ || !ownerStat.isFile() || ownerStat.isSymbolicLink() || (uid !== null && ownerStat.uid !== uid)
+ || (ownerStat.mode & 0o777) !== 0o600) return
+ const owner = JSON.parse(readFileSync(join(lockDir, 'owner.json'), 'utf8'))
+ const ownerPid = Number(owner?.pid)
+ const ownerStartMarker = typeof owner?.startMarker === 'string' ? owner.startMarker : ''
+ const ownerToken = typeof owner?.token === 'string' ? owner.token : ''
+ if (!processAlive(ownerPid, ownerStartMarker) && ownerPid > 0 && ownerToken) {
+ const current = JSON.parse(readFileSync(join(lockDir, 'owner.json'), 'utf8'))
+ if (Number(current?.pid) === ownerPid
+ && current?.startMarker === ownerStartMarker
+ && current?.token === ownerToken
+ && !processAlive(ownerPid, ownerStartMarker)) {
+ rmSync(lockDir, { recursive: true, force: true })
+ continue
+ }
+ }
} catch {
- // lock disappeared between mkdir attempts
+ // Lock disappeared or is still being initialized; wait without stealing it.
}
await sleep(LOCK_RETRY_MS)
}
}
}
-function readRegistry(file) {
+function readJsonArray(file) {
try {
- const arr = JSON.parse(readFileSync(file, 'utf-8'))
+ secureStateDirectory(dirname(file), false)
+ const arr = JSON.parse(readPrivateStateFile(file))
return Array.isArray(arr) ? arr : []
- } catch {
- return []
+ } catch (error) {
+ return error?.code === 'ENOENT' ? [] : null
+ }
+}
+
+function readRegistryState(file) {
+ try {
+ secureStateDirectory(dirname(file), false)
+ const rows = JSON.parse(readPrivateStateFile(file))
+ if (!Array.isArray(rows)) return null
+ if (rows.some((row) => row && typeof row === 'object'
+ && Object.hasOwn(row, 'schemaVersion') && row.schemaVersion !== 2)) return null
+ const legacyRows = rows.filter((row) => !row || typeof row !== 'object' || !Object.hasOwn(row, 'schemaVersion'))
+ if (legacyRows.some((row) => !validLegacyRegistryRow(row))) return null
+ const v2Rows = rows.filter((row) => row && typeof row === 'object' && row.schemaVersion === 2)
+ if (v2Rows.length && !validV2Registry(v2Rows)) return null
+ return rows
+ } catch (error) {
+ return error?.code === 'ENOENT' ? [] : null
}
}
function writeRegistry(file, sessions) {
- mkdirSync(dirname(file), { recursive: true })
- const tmp = `${file}.${process.pid}.tmp`
- writeFileSync(tmp, JSON.stringify(sessions, null, 2))
- renameSync(tmp, file)
+ secureStateDirectory(dirname(file))
+ hardenPrivateStateFileIfPresent(file)
+ const tmp = `${file}.${process.pid}.${randomUUID()}.tmp`
+ let renamed = false
+ try {
+ const fd = openSync(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)
+ try {
+ writeFileSync(fd, JSON.stringify(sessions, null, 2))
+ fchmodSync(fd, 0o600)
+ fsyncSync(fd)
+ } finally { closeSync(fd) }
+ renameSync(tmp, file)
+ renamed = true
+ const directoryFd = openSync(dirname(file), 'r')
+ try { fsyncSync(directoryFd) } finally { closeSync(directoryFd) }
+ } finally {
+ if (!renamed) {
+ try { rmSync(tmp, { force: true }) } catch { /* ignore */ }
+ }
+ }
}
function cursorPendingFile() {
@@ -599,7 +951,9 @@ async function persistCursorTask(input) {
const file = cursorPendingFile()
await withRegistryLock(file, () => {
const now = Date.now()
- const existing = readRegistry(file).filter((item) =>
+ const current = readJsonArray(file)
+ if (current === null) return
+ const existing = current.filter((item) =>
item
&& typeof item.sessionId === 'string'
&& typeof item.toolUseId === 'string'
@@ -615,7 +969,8 @@ async function clearCursorTasks(sessionId) {
if (typeof sessionId !== 'string' || !sessionId) return
const file = cursorPendingFile()
await withRegistryLock(file, () => {
- const current = readRegistry(file)
+ const current = readJsonArray(file)
+ if (current === null) return
const next = current.filter((item) => !item || item.sessionId !== sessionId)
if (next.length) writeRegistry(file, next)
else {
@@ -624,6 +979,115 @@ async function clearCursorTasks(sessionId) {
})
}
+function runtimeRouteKey(runtime) {
+ return runtime.backend === 'tmux'
+ ? `tmux\u0000${runtime.paneId}`
+ : `herdr\u0000${runtime.endpointId}\u0000${runtime.paneId}`
+}
+
+function runtimePlacementKey(runtime) {
+ return runtime.backend === 'tmux'
+ ? runtimeRouteKey(runtime)
+ : `herdr\u0000${runtime.endpointId}\u0000${runtime.terminalId}`
+}
+
+function mergeRuntimes(current, observed) {
+ const merged = new Map()
+ for (const runtime of [...(Array.isArray(current) ? current : []), ...observed]) {
+ if (runtime?.backend === 'tmux' || runtime?.backend === 'herdr') merged.set(runtimePlacementKey(runtime), runtime)
+ }
+ return [...merged.values()].sort((a, b) => runtimePlacementKey(a).localeCompare(runtimePlacementKey(b)))
+}
+
+const REGISTRY_ENGINES = new Set([
+ 'claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin', 'muse', 'amp', 'kilo', 'grok',
+])
+
+function validRegistryString(value, max = 4096) {
+ return typeof value === 'string' && value.length <= max && !/[\u0000-\u001f\u007f]/.test(value)
+}
+
+function validRegistryRuntime(runtime) {
+ if (!runtime || typeof runtime !== 'object') return false
+ if (runtime.backend === 'tmux') return typeof runtime.paneId === 'string' && /^%\d+$/.test(runtime.paneId)
+ return runtime.backend === 'herdr'
+ && validRegistryString(runtime.endpointId, 200) && runtime.endpointId.length > 0
+ && validRegistryString(runtime.sessionName, 64) && runtime.sessionName.length > 0
+ && validRegistryString(runtime.terminalId, 200) && runtime.terminalId.length > 0
+ && validRegistryString(runtime.paneId, 200) && runtime.paneId.length > 0
+}
+
+function validRegistryProcess(identity) {
+ return identity === null || (!!identity && typeof identity === 'object'
+ && Number.isSafeInteger(identity.pid) && identity.pid > 0
+ && validRegistryString(identity.executable, 1000)
+ && validRegistryString(identity.startMarker, 200) && identity.startMarker.length > 0)
+}
+
+function validV2Registry(rows) {
+ const agents = new Set()
+ const sessions = new Set()
+ const processes = new Set()
+ const routes = new Set()
+ for (const row of rows) {
+ if (row.schemaVersion !== 2 || row.active !== true && row.active !== false
+ || !validRegistryString(row.agentId, 200) || !row.agentId
+ || !validRegistryString(row.sessionId, 200)
+ || !REGISTRY_ENGINES.has(row.engine)
+ || !validRegistryString(row.projectDir)
+ || !Array.isArray(row.runtimes) || !row.runtimes.length || !row.runtimes.every(validRegistryRuntime)
+ || typeof row.primaryRuntimeKey !== 'string'
+ || !validRegistryProcess(row.processIdentity)) return false
+ const placementKeys = row.runtimes.map(runtimePlacementKey)
+ if (new Set(placementKeys).size !== placementKeys.length) return false
+ const routeKeys = row.runtimes.map(runtimeRouteKey)
+ if (row.active ? !routeKeys.includes(row.primaryRuntimeKey) : row.primaryRuntimeKey !== '') return false
+ const tmuxProjection = row.runtimes.find((runtime) => runtime.backend === 'tmux')?.paneId
+ if (tmuxProjection ? row.tmuxPane !== tmuxProjection : Object.hasOwn(row, 'tmuxPane')) return false
+ if (agents.has(row.agentId)) return false
+ agents.add(row.agentId)
+ if (row.sessionId) {
+ if (sessions.has(row.sessionId)) return false
+ sessions.add(row.sessionId)
+ }
+ if (row.processIdentity) {
+ const processKey = `${row.engine}\u0000${row.processIdentity.pid}\u0000${row.processIdentity.startMarker}`
+ if (processes.has(processKey)) return false
+ processes.add(processKey)
+ }
+ for (const route of routeKeys) {
+ if (routes.has(route)) return false
+ routes.add(route)
+ }
+ }
+ return true
+}
+
+function validLegacyRegistryRow(row) {
+ if (!row || typeof row !== 'object' || Array.isArray(row) || Object.hasOwn(row, 'schemaVersion')) return false
+ const id = typeof row.agentId === 'string' && row.agentId ? row.agentId : row.launcherId
+ if (!validRegistryString(id, 200) || !id) return false
+ if (row.engine !== undefined && !REGISTRY_ENGINES.has(row.engine)) return false
+ if (row.tmuxPane !== undefined && (typeof row.tmuxPane !== 'string' || !/^%\d+$/.test(row.tmuxPane))) return false
+ if (row.runtimes !== undefined
+ && (!Array.isArray(row.runtimes) || !row.runtimes.length || !row.runtimes.every(validRegistryRuntime))) return false
+ return /^%\d+$/.test(row.tmuxPane || '') || (Array.isArray(row.runtimes) && row.runtimes.length > 0)
+}
+
+async function callerOwns(identity) {
+ const rows = await processRows()
+ if (!rows) return false
+ const parents = new Map(rows.map((row) => [row.pid, row.parentPid]))
+ let pid = process.ppid
+ const visited = new Set()
+ while (pid > 0 && !visited.has(pid)) {
+ if (pid === identity.pid) return true
+ visited.add(pid)
+ pid = parents.get(pid) || 0
+ }
+ return false
+}
+
async function fallbackRegister(input, engine, tmuxPane) {
const p = paths()
const transcriptPath = typeof input.transcript_path === 'string' ? input.transcript_path : ''
@@ -631,29 +1095,53 @@ async function fallbackRegister(input, engine, tmuxPane) {
const sessionId = typeof rawSessionId === 'string' && rawSessionId
? rawSessionId
: (transcriptPath ? basename(transcriptPath).replace(/\.jsonl$/, '') : '')
- if (!sessionId || !/^%\d+$/.test(tmuxPane)) return
+ if (!sessionId) return
const transcriptOptional = ['cursor', 'opencode', 'kilo', 'pi', 'hermes', 'commandcode', 'devin', 'grok'].includes(engine)
if (!transcriptOptional && !transcriptPath) return
if (transcriptPath && !validTranscriptPath(engine, transcriptPath, p)) return
- const process = await paneEngineProcess(tmuxPane, engine)
- if (process.state !== 'alive' || !process.identity) return
+ const observations = []
+ if (/^%\d+$/.test(tmuxPane || '')) {
+ const tmux = await paneEngineProcess(tmuxPane, engine)
+ if (tmux.state === 'alive' && tmux.identity && await callerOwns(tmux.identity)) {
+ observations.push({ identity: tmux.identity, runtime: { backend: 'tmux', paneId: tmuxPane } })
+ }
+ }
+ const herdr = await herdrFallbackRuntime(engine)
+ if (herdr) observations.push(herdr)
+ if (!observations.length) return
+ const process = observations[0]
+ if (observations.some((observation) => observation.identity.pid !== process.identity.pid
+ || observation.identity.startMarker !== process.identity.startMarker)) return
+ const observedRuntimes = observations.map((observation) => observation.runtime)
if (engine === 'hermes' && !await hermesTopLevelSession(p.hermesDb, sessionId)) return
await withRegistryLock(p.registryFile, () => {
- let sessions = rebootedSinceSnapshot(p.bootFile) ? [] : readRegistry(p.registryFile)
+ if (remainingBudget(600) < 50) return
+ const loaded = rebootedSinceSnapshot(p.bootFile) ? [] : readRegistryState(p.registryFile)
+ // Corrupt/non-array/unknown-schema/unsafe bytes are operator-owned recovery data. Never turn them
+ // into an empty registry merely because the daemon is down.
+ if (loaded === null) return
+ let sessions = loaded
writeBoot(p.bootFile)
const now = Date.now()
- const sameRuntime = (s) => s && s.tmuxPane === tmuxPane && s.engine === engine
- && (!s.processIdentity || (s.processIdentity.pid === process.identity.pid && s.processIdentity.startMarker === process.identity.startMarker))
+ const sameRuntime = (s) => s && s.engine === engine
+ && s.processIdentity?.pid === process.identity.pid && s.processIdentity?.startMarker === process.identity.startMarker
const existingIndex = sessions.findIndex(sameRuntime)
const existing = existingIndex >= 0 ? sessions[existingIndex] : null
// A resumed session moves to this process agent; the previous process remains visible but unbound.
sessions = sessions.map((s) => s && s.sessionId === sessionId && !sameRuntime(s)
? { ...s, sessionId: '', boundAt: null, transcriptPath: null, source: null, updatedAt: now }
: s)
- if (existingIndex < 0) sessions = sessions.filter((s) => !s || s.tmuxPane !== tmuxPane)
+ const routeKeys = new Set(observedRuntimes.map(runtimeRouteKey))
+ if (existingIndex < 0) sessions = sessions.filter((s) => !s || !(Array.isArray(s.runtimes)
+ ? s.runtimes.some((runtime) => routeKeys.has(runtimeRouteKey(runtime)))
+ : s.tmuxPane && routeKeys.has(runtimeRouteKey({ backend: 'tmux', paneId: s.tmuxPane }))))
const agentId = typeof existing?.agentId === 'string' && existing.agentId ? existing.agentId : randomUUID()
+ const runtimes = mergeRuntimes(existing?.runtimes, observedRuntimes)
+ const tmuxProjection = runtimes.find((runtime) => runtime.backend === 'tmux')?.paneId || ''
const entry = {
+ schemaVersion: 2,
+ active: true,
agentId,
sessionId,
engine,
@@ -665,7 +1153,11 @@ async function fallbackRegister(input, engine, tmuxPane) {
? basename(dirname(transcriptPath))
: basename(typeof input.cwd === 'string' ? input.cwd : '') || sessionId,
cwd: typeof input.cwd === 'string' ? input.cwd : (existing?.cwd ?? null),
- tmuxPane,
+ runtimes,
+ primaryRuntimeKey: existing?.primaryRuntimeKey && runtimes.some((runtime) => runtimeRouteKey(runtime) === existing.primaryRuntimeKey)
+ ? existing.primaryRuntimeKey
+ : runtimeRouteKey(observedRuntimes[0]),
+ tmuxPane: tmuxProjection,
source: typeof input.source === 'string' ? input.source : (existing?.source ?? null),
title: typeof input.session_title === 'string' ? input.session_title : (existing?.title ?? null),
model: typeof input.model === 'string' ? input.model : (existing?.model ?? null),
@@ -676,6 +1168,7 @@ async function fallbackRegister(input, engine, tmuxPane) {
lastHookAt: now,
lastTranscriptAt: typeof existing?.lastTranscriptAt === 'number' ? existing.lastTranscriptAt : now,
}
+ if (!tmuxProjection) delete entry.tmuxPane
if (existingIndex >= 0) sessions[existingIndex] = entry
else sessions.push(entry)
writeRegistry(p.registryFile, sessions)
@@ -701,7 +1194,8 @@ async function main() {
const event = input.hook_event_name || input.hookEventName
const tmuxPane = process.env.TMUX_PANE
- if (!tmuxPane) return // tmux-only: ignore every lifecycle event from standalone CLI sessions
+ if (!tmuxPane && !process.env.HERDR_PANE_ID) return
+ const mutationFields = { engine, ...terminalHookFields(tmuxPane) }
if (engine === 'cursor' && input.is_background_agent === true) return
if (engine === 'codex' && isCodexSubagent(input, paths())) return
// Devin's documented user-level hook locations include ~/.claude.json and ~/.claude/settings.json, so a
@@ -722,12 +1216,12 @@ async function main() {
const cwd = input.cwd || input.workspaceRoot
const transcriptPath = grokTranscriptPath(paths(), cwd, sessionId)
if (grokEventName === 'SessionEnd') {
- const ok = await post(port, '/api/hook/session-end', { sessionId, reason: input.reason })
+ const ok = await post(port, '/api/hook/session-end', { sessionId, reason: input.reason, ...mutationFields })
if (!ok) await fallbackSessionEnd(sessionId, input.reason, engine, tmuxPane)
return
}
if (grokEventName === 'StopFailure') {
- await post(port, '/api/hook/turn-stop', { sessionId, transcriptPath, status: 'error' })
+ await post(port, '/api/hook/turn-stop', { sessionId, transcriptPath, status: 'error', ...mutationFields })
return
}
if (grokEventName !== 'SessionStart' && grokEventName !== 'UserPromptSubmit') return
@@ -737,7 +1231,7 @@ async function main() {
sessionId,
transcriptPath,
cwd,
- tmuxPane,
+ ...terminalHookFields(tmuxPane),
model: modelName(input.model),
cliVersion: input.cliVersion || input.version,
}
@@ -759,6 +1253,7 @@ async function main() {
const ok = await post(port, '/api/hook/session-end', {
sessionId: input.session_id || input.conversation_id,
reason: input.reason,
+ ...mutationFields,
})
if (!ok) await fallbackSessionEnd(input.session_id || input.conversation_id, input.reason, engine, tmuxPane)
if (engine === 'cursor' && ok) await clearCursorTasks(input.session_id || input.conversation_id)
@@ -770,6 +1265,7 @@ async function main() {
if (engine === 'commandcode' && (event === 'PreToolUse' || event === 'preToolUse')) {
await post(port, '/api/hook/turn-start', {
sessionId: input.session_id || input.conversation_id,
+ ...mutationFields,
})
return
}
@@ -782,6 +1278,7 @@ async function main() {
toolUseId: input.tool_use_id,
toolName: input.tool_name,
input: input.tool_input,
+ ...mutationFields,
})
}
return
@@ -795,7 +1292,7 @@ async function main() {
sessionId,
transcriptPath: input.transcript_path,
cwd: Array.isArray(input.workspace_roots) ? input.workspace_roots[0] : input.cwd,
- tmuxPane,
+ ...terminalHookFields(tmuxPane),
model: modelName(input.model),
cliVersion: input.cursor_version || input.version,
}
@@ -805,6 +1302,7 @@ async function main() {
sessionId,
status: input.status,
transcriptPath: input.transcript_path,
+ ...mutationFields,
})
if (stopped) await clearCursorTasks(sessionId)
return
@@ -829,7 +1327,7 @@ async function main() {
sessionId: input.session_id,
transcriptPath: existsPath(input.transcript_path) ? input.transcript_path : undefined,
cwd: input.cwd,
- tmuxPane,
+ ...terminalHookFields(tmuxPane),
title: input.session_title,
model: modelName(input.model),
cliVersion: input.cli_version || input.version,
@@ -840,6 +1338,7 @@ async function main() {
sessionId: input.session_id,
transcriptPath: input.transcript_path,
status: event === 'StopFailure' ? 'error' : undefined,
+ ...mutationFields,
})
return
}
@@ -866,7 +1365,7 @@ async function main() {
// Devin's payload carries no cwd; the hook process inherits the session's working directory.
cwd: Array.isArray(input.workspace_roots) ? input.workspace_roots[0] : (input.cwd || (engine === 'devin' ? process.cwd() : undefined)),
source: input.source,
- tmuxPane,
+ ...terminalHookFields(tmuxPane),
title: input.session_title,
model: modelName(input.model),
cliVersion: input.cli_version || input.cursor_version || input.version,
diff --git a/cli/package.json b/cli/package.json
index 95c07d544..0e17bc201 100644
--- a/cli/package.json
+++ b/cli/package.json
@@ -14,6 +14,7 @@
"test": "vitest run",
"test:cursor-e2e": "RUN_CURSOR_E2E=1 vitest run src/engines/cursor/localE2e.spec.ts",
"test:tmux-real": "RUN_REAL_TMUX_DISCOVERY=1 vitest run src/lib/tmuxAgentDiscovery.real.spec.ts --reporter=verbose",
+ "test:herdr-real": "RUN_REAL_HERDR=1 vitest run src/lib/herdrBackend.real.spec.ts --reporter=verbose",
"release": "bash scripts/upload-cli.sh"
},
"dependencies": {
@@ -33,7 +34,7 @@
"typescript": "^5.5.3",
"vitest": "^4.1.10"
},
- "description": "Run your own coding-agent CLIs (Claude Code, Codex, Cursor, OpenCode, Pi, Hermes, Command Code, Devin, Muse, Amp, Kilo, and Grok) in tmux and drive them from the web or a paired device.",
+ "description": "Run your own coding-agent CLIs in tmux, Herdr, or both and drive them from the web or a paired device.",
"license": "Apache-2.0",
"repository": {
"type": "git",
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 9bfcf712d..f374f7024 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -23,7 +23,6 @@ import { routeVoiceTask } from './lib/voiceRouter.js'
import { tailFile } from './lib/sessions.js'
import { messagesToEvents, windowRawLines, subagentStatsFromRawLines, type SessionEvent } from './lib/normalize.js'
import { listFileTree, readProjectFile } from './lib/files.js'
-import { sendToTmux } from './lib/tmux.js'
import { codexMessagesToEvents, windowCodexLines } from './engines/codex/normalizer.js'
import { cursorMessagesToEvents, windowCursorLines } from './engines/cursor/normalizer.js'
import { loadCursorReplayTaskLinks } from './engines/cursor/subagent.js'
@@ -246,14 +245,15 @@ export class BackendSocket {
onCommanderPresenceChanged: ((connected: boolean) => void) | null = null
/** Called when the web cancels a turn (C-c) — cli.ts stops that session's turn heartbeat. */
onCancel: ((sessionId: string) => void) | null = null
- /** Called when the web deletes an agent (`agent_delete`) — cli.ts kills the tmux pane (if any) and
- * forgets the session (removes it from the list + emits `agent_deleted`). Keeps recap + agent name. */
+ /** Called when the web deletes an agent (`agent_delete`) — cli.ts signals only the validated engine
+ * process and forgets the session. Keeps recap + agent name. */
onDeleteAgent: ((sessionId: string) => void) | null = null
- /** Called when the web/device sends a chat `message` to inject into a session's tmux pane — cli.ts does
- * the bracketed-paste inject + a watcher-confirmed Enter retry so long/multi-line text always submits. */
+ /** Called when the web/device sends chat input to an agent terminal. */
onMessage: ((sessionId: string, content: string) => void) | null = null
+ /** Best-effort terminal-native title sync after a user renames an agent. */
+ onAgentRename: ((session: RegisteredSession, name: string) => void) | null = null
/** Called when a device answers an AskUserQuestion (`question_response`) — cli.ts drives the CLI's own
- * question dialog in that session's tmux pane (option digit / free text), since a remote machine has no
+ * terminal dialog (option digit / free text), since a remote machine has no
* programmatic answer channel the way the hosted runtime’s brain does. */
onQuestionAnswer: ((payload: { requestId?: string; sessionId?: string; agentId?: string; answers?: Record<string, string> }) => void) | null = null
/** Called when this machine was deleted/revoked (a `machine_revoked` down-frame, or a 401/403 on the
@@ -652,7 +652,7 @@ export class BackendSocket {
}
case 'agents_list': {
- const projects = await Promise.all(registry.list().map((s) => this.toProject(s)))
+ const projects = await Promise.all(registry.active().map((s) => this.toProject(s)))
// Ordered by creation time, oldest → newest — a stable tab order that doesn't reshuffle as
// sessions become active (createdAt = the session's registeredAt).
projects.sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt))
@@ -938,7 +938,7 @@ export class BackendSocket {
reply(type, requestId, { error: 'MISSING_TRANSCRIPT' })
return
}
- const projects = (await Promise.all(registry.list().map((s) => this.toProject(s)))).slice(0, 24) // cap the router prompt (mirror the hosted runtime path)
+ const projects = (await Promise.all(registry.active().map((s) => this.toProject(s)))).slice(0, 24) // cap the router prompt (mirror the hosted runtime path)
const agents = projects.map((p) => {
// Use the last 3 turns' recaps (not just 1) — a single turn can misrepresent what the agent is
// actually working on; 3 gives the router a more stable picture.
@@ -977,7 +977,10 @@ export class BackendSocket {
return
}
}
- if (hasName) s = registry.rename(projectId, name) ?? s
+ if (hasName) {
+ s = registry.rename(projectId, name) ?? s
+ this.onAgentRename?.(s, name)
+ }
const agent = await this.toProject(s)
reply(type, requestId, { agent })
if (hasName) {
@@ -993,12 +996,12 @@ export class BackendSocket {
return
}
- // A project IS a tmux session; the web/device can't CREATE one remotely.
+ // A project is backed by an existing local terminal agent; the web/device cannot create one remotely.
case 'agent_create':
reply(type, requestId, { error: 'UNSUPPORTED_ON_REMOTE' })
return
- // Delete an agent: kill its tmux pane (if any) + drop it from the list. Idempotent — an already
+ // Delete an agent: signal its validated engine process and drop it from the list. Idempotent — an already
// gone target still acks + re-emits agent_deleted so the web/device converge. E2EE-gated (the
// frame arrived decrypted). Keeps the persisted recap + agent name for a later resume.
case 'agent_delete': {
@@ -1048,7 +1051,7 @@ export class BackendSocket {
// to the web (mirror-all) — no synthetic events here. Prefer cli.ts's handler (inject + Enter
// retry); fall back to a direct inject when unwired (isolation/tests).
if (this.onMessage) this.onMessage(target, content)
- else { const s = registry.resolve(target); if (s?.tmuxPane) void sendToTmux(s.tmuxPane, content) }
+ else console.warn('[backend] message handler is not wired; terminal input was not dispatched')
return
}
@@ -1102,17 +1105,18 @@ export class BackendSocket {
/** Map a registered tmux session onto the web's Project shape (tabs in ProjectTabs). */
private async toProject(s: RegisteredSession): Promise<{
id: string; userId: string; name: string; status: string
- createdAt: string; updatedAt: string; tmuxPane: string | null; engine: RegisteredSession['engine']; selectedModel: string | null
+ createdAt: string; updatedAt: string; tmuxPane: string | null; terminal: { primary: string; runtimes: RegisteredSession['runtimes'] }; engine: RegisteredSession['engine']; selectedModel: string | null
}> {
const st = s.transcriptPath ? await stat(s.transcriptPath).catch(() => null) : null
return {
id: s.agentId,
userId: '',
name: projectDisplayName(s),
- status: 'active',
+ status: s.active ? 'active' : 'offline',
createdAt: new Date(s.registeredAt).toISOString(),
updatedAt: new Date(st?.mtimeMs ?? s.updatedAt).toISOString(),
- tmuxPane: s.tmuxPane,
+ tmuxPane: s.tmuxPane || null,
+ terminal: { primary: s.primaryRuntimeKey, runtimes: s.runtimes },
engine: s.engine,
selectedModel: this.runtimeProfileProvider?.(s) ?? null,
}
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index d4b3b56b3..97e90acf2 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -31,16 +31,15 @@ import { ENGINE_CLI_COMMANDS, ENGINES } from './lib/engineBin.js'
import { clearDeleted, isRecentlyDeleted, markDeleted } from './lib/deletedSessions.js'
import { terminateDeletedAgent } from './lib/deleteAgentFallback.js'
import { findLiveSession } from './lib/sessionRepair.js'
-import {
- sendToTmux,
- sendKeyToTmux,
- sendLiteralToTmux,
- validateSessionRuntime,
- checkSessionRuntime,
- captureTmuxPane,
- listPaneTitles,
-} from './lib/tmux.js'
-import { TmuxAgentReconciler, type DiscoveredTmuxAgent } from './lib/tmuxAgentDiscovery.js'
+import { TmuxBackend } from './lib/tmuxBackend.js'
+import { HerdrBackend } from './lib/herdrBackend.js'
+import { listInstalledHerdrSessions, resolveConfiguredHerdrSessions } from './lib/herdrSessions.js'
+import { TerminalBackendCoordinator } from './lib/terminalBackendCoordinator.js'
+import { terminalRouteKey, terminalRuntimeLabel } from './lib/terminalRuntime.js'
+import { TerminalAgentReconciler } from './lib/terminalAgentReconciler.js'
+import { processRows, type DiscoveredTerminalAgent } from './lib/terminalAgentDiscovery.js'
+import { terminalActionNotStarted, type HookTerminalHint, type TerminalActionResult, type TerminalRuntimeRef } from './lib/terminalTypes.js'
+import { readTerminalConfigSnapshot, writeTerminalConfigSnapshot } from './lib/terminalConfigSnapshot.js'
import { Watcher, type LineEvent } from './watcher/watcher.js'
import { startHookServer } from './hookServer.js'
import { BackendSocket } from './backendSocket.js'
@@ -397,15 +396,21 @@ async function projectFrame(s: RegisteredSession, selectedModel: string | null):
id: s.agentId,
userId: '',
name: projectDisplayName(s),
- status: 'active',
+ status: s.active ? 'active' : 'offline',
createdAt: new Date(s.registeredAt).toISOString(),
updatedAt: new Date(st?.mtimeMs ?? s.updatedAt).toISOString(),
- tmuxPane: s.tmuxPane,
+ tmuxPane: s.tmuxPane || null,
+ terminal: { primary: s.primaryRuntimeKey, runtimes: s.runtimes },
engine: s.engine,
selectedModel,
}
}
+function primaryTerminalLabel(session: RegisteredSession): string {
+ const runtime = session.runtimes.find((candidate) => terminalRouteKey(candidate) === session.primaryRuntimeKey)
+ return runtime ? terminalRuntimeLabel(runtime) : 'dormant'
+}
+
/** Birth time of a transcript in ms, or 0 when it cannot be read (treated as "not newer than the agent"). */
async function statBirthMs(path: string): Promise<number> {
const st = await stat(path).catch(() => null)
@@ -437,13 +442,232 @@ async function runForeground(token: string): Promise<void> {
})
registry.load()
+ // Persisted locators are hints until this process has observed their terminal root and PID/start marker.
+ // Mark them dormant before the backend socket can publish anything; the first authoritative reconcile
+ // reactivates matching process agents without changing their public identity or session binding.
+ await registry.transaction(() => {
+ for (const session of registry.list()) registry.setActive(session.agentId, false)
+ })
+ const terminalConfig = { backends: env.TERMINAL_BACKENDS, herdrSessions: env.HERDR_SESSIONS }
+ const tmuxBackend = terminalConfig.backends.includes('tmux') ? new TmuxBackend() : null
+ const herdrTargets = terminalConfig.backends.includes('herdr')
+ ? await resolveConfiguredHerdrSessions(terminalConfig.herdrSessions, () => listInstalledHerdrSessions(env.HERDR_BIN))
+ : []
+ const resolvedHerdrPaths = herdrTargets.flatMap((target) => target.state === 'available' ? [target.endpoint.socketPath] : [])
+ if (new Set(resolvedHerdrPaths).size !== resolvedHerdrPaths.length) {
+ throw new Error('two configured Herdr session names resolve to the same canonical endpoint')
+ }
+ const herdrStartup = await Promise.all(herdrTargets.map(async (target) => {
+ if (target.state === 'unavailable') return { sessionName: target.sessionName, state: 'unavailable' as const, reason: target.reason }
+ const backend = new HerdrBackend(target.endpoint)
+ const ping = await backend.client.ping()
+ if (ping.ok) return { sessionName: target.sessionName, state: 'available' as const, backend }
+ return {
+ sessionName: target.sessionName,
+ state: ping.code === 'protocol_mismatch' ? 'incompatible' as const : 'unavailable' as const,
+ reason: ping.reason,
+ }
+ }))
+ const herdrBackends = herdrStartup.flatMap((target) => target.state === 'available' ? [target.backend] : [])
+ const herdrTargetStates = new Map(herdrStartup.map((target) => [target.sessionName, {
+ state: target.state,
+ ...(target.state === 'available' ? {} : { reason: target.reason }),
+ }]))
+ if (!tmuxBackend && herdrStartup.length > 0 && herdrStartup.every((target) => target.state === 'incompatible')) {
+ throw new Error('every enabled terminal backend is protocol-incompatible')
+ }
+ const terminalBackends = [...(tmuxBackend ? [tmuxBackend] : []), ...herdrBackends]
+ const terminals = new TerminalBackendCoordinator(
+ terminalBackends,
+ terminalConfig.backends,
+ terminalConfig.herdrSessions,
+ )
+ const refreshHerdrTargets = async (): Promise<void> => {
+ if (!terminalConfig.backends.includes('herdr')) return
+ const resolved = await resolveConfiguredHerdrSessions(
+ terminalConfig.herdrSessions,
+ () => listInstalledHerdrSessions(env.HERDR_BIN),
+ )
+ const available = resolved.filter((target): target is Extract<typeof target, { state: 'available' }> => target.state === 'available')
+ const aliased = new Set<string>()
+ const byPath = new Map<string, string>()
+ for (const target of available) {
+ const owner = byPath.get(target.endpoint.socketPath)
+ if (owner) { aliased.add(owner); aliased.add(target.sessionName) }
+ else byPath.set(target.endpoint.socketPath, target.sessionName)
+ }
+
+ const recovered = new Map(herdrBackends.map((backend) => [backend.endpoint.sessionName, backend]))
+ for (const target of resolved) {
+ if (target.state === 'unavailable') {
+ herdrTargetStates.set(target.sessionName, { state: 'unavailable', reason: target.reason })
+ continue
+ }
+ if (aliased.has(target.sessionName)) {
+ recovered.delete(target.sessionName)
+ herdrTargetStates.set(target.sessionName, { state: 'incompatible', reason: 'configured Herdr sessions alias one endpoint' })
+ continue
+ }
+ const backend = new HerdrBackend(target.endpoint)
+ const ping = await backend.client.ping()
+ if (!ping.ok) {
+ if (ping.code === 'protocol_mismatch') recovered.delete(target.sessionName)
+ herdrTargetStates.set(target.sessionName, {
+ state: ping.code === 'protocol_mismatch' ? 'incompatible' : 'unavailable',
+ reason: ping.reason,
+ })
+ continue
+ }
+ recovered.set(target.sessionName, backend)
+ herdrTargetStates.set(target.sessionName, { state: 'available' })
+ }
+ herdrBackends.splice(0, herdrBackends.length, ...terminalConfig.herdrSessions.flatMap((name) => {
+ const backend = recovered.get(name)
+ return backend ? [backend] : []
+ }))
+ terminalBackends.splice(0, terminalBackends.length, ...(tmuxBackend ? [tmuxBackend] : []), ...herdrBackends)
+ terminals.replaceBackends(terminalBackends)
+ if (herdrBackends.length === terminalConfig.herdrSessions.length) {
+ writeTerminalConfigSnapshot(env.ADAPTER_DATA_DIR, terminalConfig, herdrBackends.map((backend) => backend.endpoint))
+ }
+ }
+ const completeHerdrSnapshot = !terminalConfig.backends.includes('herdr')
+ || herdrBackends.length === terminalConfig.herdrSessions.length
+ if (completeHerdrSnapshot) {
+ writeTerminalConfigSnapshot(
+ env.ADAPTER_DATA_DIR,
+ terminalConfig,
+ herdrBackends.map((backend) => backend.endpoint),
+ )
+ } else {
+ const previous = readTerminalConfigSnapshot(env.ADAPTER_DATA_DIR)
+ const previousNames = previous?.herdrEndpoints.map((endpoint) => endpoint.sessionName) ?? []
+ if (JSON.stringify(previousNames) !== JSON.stringify(terminalConfig.herdrSessions)
+ || !previous?.backends.includes('herdr')) {
+ // The configured allowlist changed but cannot be resolved completely. Publish a fail-closed
+ // snapshot rather than leaving an old endpoint authorized for daemon-down hooks.
+ writeTerminalConfigSnapshot(env.ADAPTER_DATA_DIR, {
+ backends: terminalConfig.backends.filter((backend) => backend !== 'herdr'),
+ herdrSessions: [],
+ }, [])
+ }
+ }
+ console.log(`[terminal] enabled backends: ${terminalConfig.backends.join(', ')}`)
+ if (tmuxBackend) {
+ const tmuxStartup = await tmuxBackend.inventory()
+ console.log(tmuxStartup.state === 'available'
+ ? '[terminal] tmux: available'
+ : `[terminal] tmux: ${tmuxStartup.state} (${tmuxStartup.reason})`)
+ }
+ for (const target of herdrStartup) {
+ console.log(target.state === 'available'
+ ? `[terminal] Herdr session ${target.sessionName}: available`
+ : `[terminal] Herdr session ${target.sessionName}: ${target.state} (${target.reason})`)
+ }
+
+ const terminalSession = (target: string): RegisteredSession | undefined => registry.resolve(target)
+ const controlLeases = new Map<string, { lease: Awaited<ReturnType<typeof terminals.acquireLease>> & { state: 'succeeded' }; expiresAt: number }>()
+ const pinnedControls = new Set<string>()
+ const invalidControls = new Set<string>()
+ const CONTROL_LEASE_IDLE_MS = 15_000
+ const leasedTerminal = async (session: RegisteredSession): Promise<Extract<Awaited<ReturnType<typeof terminals.acquireLease>>, { state: 'succeeded' }> | null> => {
+ const pinned = pinnedControls.has(session.agentId)
+ if (pinned && invalidControls.has(session.agentId)) return null
+ const current = controlLeases.get(session.agentId)
+ if (current && (pinned || current.expiresAt > Date.now())) {
+ if (!await terminals.validateLease(current.lease.value, session)) {
+ controlLeases.delete(session.agentId)
+ if (pinned) invalidControls.add(session.agentId)
+ return null
+ }
+ current.expiresAt = Date.now() + CONTROL_LEASE_IDLE_MS
+ return current.lease
+ }
+ controlLeases.delete(session.agentId)
+ const acquired = await terminals.acquireLease(session)
+ if (acquired.state !== 'succeeded') return null
+ const value = { lease: acquired, expiresAt: Date.now() + CONTROL_LEASE_IDLE_MS }
+ controlLeases.set(session.agentId, value)
+ return acquired
+ }
+ const pinTerminalControl = (target: string): (() => void) | null => {
+ const session = terminalSession(target)
+ if (!session || pinnedControls.has(session.agentId)) return null
+ pinnedControls.add(session.agentId)
+ invalidControls.delete(session.agentId)
+ return () => {
+ pinnedControls.delete(session.agentId)
+ invalidControls.delete(session.agentId)
+ controlLeases.delete(session.agentId)
+ }
+ }
+ const invalidateTerminalControl = (agentId: string): void => {
+ controlLeases.delete(agentId)
+ if (pinnedControls.has(agentId)) invalidControls.add(agentId)
+ }
+ const captureTerminal = async (target: string, historyLines?: number): Promise<string | null> => {
+ const session = terminalSession(target)
+ if (!session) return null
+ const pinned = pinnedControls.has(session.agentId)
+ if (pinned && invalidControls.has(session.agentId)) return null
+ let activeLease = controlLeases.get(session.agentId)
+ if (activeLease && !pinned && activeLease.expiresAt <= Date.now()) {
+ controlLeases.delete(session.agentId)
+ activeLease = undefined
+ }
+ const leased = activeLease || pinned ? await leasedTerminal(session) : null
+ if ((activeLease || pinned) && !leased) return null
+ const result = leased
+ ? await terminals.captureLease(leased.value, { historyLines })
+ : await terminals.capture(session, { historyLines })
+ return result.state === 'succeeded' ? result.value : null
+ }
+ const terminalActionSucceeded = (result: Awaited<ReturnType<typeof terminals.submitText>>): boolean =>
+ result.state === 'succeeded'
+ const submitTerminalAction = async (target: string, text: string): Promise<TerminalActionResult> => {
+ const session = terminalSession(target)
+ if (!session) return terminalActionNotStarted('terminal agent is unavailable')
+ const lease = await leasedTerminal(session)
+ if (!lease) return terminalActionNotStarted('terminal control lease is unavailable or changed')
+ const result = pinnedControls.has(session.agentId)
+ ? await terminals.submitTextLease(lease.value, text)
+ : await terminals.submitTextForLease(session, lease.value, text)
+ if (result.state !== 'succeeded' && pinnedControls.has(session.agentId)) invalidateTerminalControl(session.agentId)
+ return result
+ }
+ const submitTerminal = async (target: string, text: string): Promise<boolean> => {
+ return terminalActionSucceeded(await submitTerminalAction(target, text))
+ }
+ const typeTerminal = async (target: string, text: string): Promise<boolean> => {
+ const session = terminalSession(target)
+ if (!session) return false
+ const lease = await leasedTerminal(session)
+ if (!lease) return false
+ const succeeded = terminalActionSucceeded(await terminals.typeLiteralLease(lease.value, text))
+ if (!succeeded && pinnedControls.has(session.agentId)) invalidateTerminalControl(session.agentId)
+ return succeeded
+ }
+ const keyTerminalAction = async (target: string, key: string): Promise<TerminalActionResult> => {
+ const session = terminalSession(target)
+ if (!session) return terminalActionNotStarted('terminal session is unavailable')
+ const lease = await leasedTerminal(session)
+ if (!lease) return terminalActionNotStarted('terminal control lease is unavailable or changed')
+ const result = await terminals.sendLegacyKeyLease(lease.value, key)
+ if (result.state !== 'succeeded' && pinnedControls.has(session.agentId)) invalidateTerminalControl(session.agentId)
+ return result
+ }
+ const keyTerminal = async (target: string, key: string): Promise<boolean> => {
+ return terminalActionSucceeded(await keyTerminalAction(target, key))
+ }
+ const validateTerminal = async (session: RegisteredSession): Promise<boolean> =>
+ (await terminals.validate(session)).state === 'alive'
// Persisted records are not trusted blindly. The process reconciler below adopts a matching live
// runtime, replaces it immediately when PID/start-marker changed, and requires two successful misses
// before removing it. Probe errors leave the registry untouched.
// Recap pool AND voice router share one sync: both need to know which engines the machine actually
// runs, and a router warmed for an engine no agent uses is exactly the bug this rides along to fix.
const syncRecapPool = (): void => {
- const sessions = registry.list()
+ const sessions = registry.active()
syncSummaryPoolSessions(sessions)
setVoiceRouterSessions(sessions)
}
@@ -474,11 +698,11 @@ async function runForeground(token: string): Promise<void> {
announceRename(s, opts)
}
- const syncPaneTitles = async (): Promise<void> => {
- const titles = await listPaneTitles()
+ const syncTerminalTitles = async (): Promise<void> => {
+ const titles = await terminals.titles()
if (titles.size === 0) return
for (const session of registry.list()) {
- const title = titles.get(session.tmuxPane)
+ const title = terminals.titleFor(session, titles)
if (!title) continue
const before = projectDisplayName(session)
const updated = registry.updateTitle(session.sessionId, title)
@@ -495,7 +719,7 @@ async function runForeground(token: string): Promise<void> {
const backend = new BackendSocket(token, (connected) => {
if (!connected) return
- const sessions = registry.list()
+ const sessions = registry.active()
console.log(`[cli] connected · ${sessions.length} agent(s) registered`)
void fullReconcile(true).catch((err) => {
console.error('[runtime-profile] connect reconcile failed:', err instanceof Error ? err.message : err)
@@ -595,7 +819,8 @@ async function runForeground(token: string): Promise<void> {
transcriptPath,
cwd: existing.cwd ?? undefined,
source: existing.source ?? undefined,
- tmuxPane: existing.tmuxPane,
+ runtimes: existing.runtimes,
+ primaryRuntimeKey: existing.primaryRuntimeKey,
title: existing.title ?? undefined,
model: existing.model ?? undefined,
cliVersion: existing.cliVersion ?? undefined,
@@ -629,7 +854,7 @@ async function runForeground(token: string): Promise<void> {
*/
replayFromStart = false,
): Promise<boolean> => {
- if (!await validateSessionRuntime(session)) return false
+ if (!await validateTerminal(session)) return false
if (!reset && (
turnStates.has(session.sessionId)
|| codexNormalizers.has(session.sessionId)
@@ -652,7 +877,7 @@ async function runForeground(token: string): Promise<void> {
)
}
else if (session.engine === 'cursor') await cursorDiscovery.add(session.sessionId)
- console.log(`[agent] ${sid(session.agentId)} re-attached · engine=${session.engine} · pane=${session.tmuxPane} · session=${sid(session.sessionId)}`)
+ console.log(`[agent] ${sid(session.agentId)} re-attached · engine=${session.engine} · terminal=${primaryTerminalLabel(session)} · session=${sid(session.sessionId)}`)
return true
}
const lines = session.transcriptPath ? await tailFile(session.transcriptPath, Infinity) : []
@@ -693,7 +918,7 @@ async function runForeground(token: string): Promise<void> {
const normalizer = new CursorNormalizer('live', session.sessionId)
historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)
cursorNormalizers.set(session.sessionId, normalizer)
- const capture = await captureTmuxPane(session.tmuxPane, 100)
+ const capture = await captureTerminal(session.agentId, 100)
if (capture) runtimeProfiles.ingestPane(session, capture, true)
} else if (session.engine === 'opencode') {
// OpenCode has no transcript file — poll its SQLite DB. The reader hydrates silently, then
@@ -732,7 +957,7 @@ async function runForeground(token: string): Promise<void> {
const normalizer = new GrokNormalizer()
historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)
grokNormalizers.set(session.sessionId, normalizer)
- const capture = await captureTmuxPane(session.tmuxPane, 60)
+ const capture = await captureTerminal(session.agentId, 60)
if (capture) runtimeProfiles.ingestPane(session, capture, true)
} else if (session.engine === 'pi') {
const normalizer = new PiNormalizer('live')
@@ -769,7 +994,7 @@ async function runForeground(token: string): Promise<void> {
await reader.start()
// Devin's model/effort exist ONLY in its pane footer, so read it now. Without this the chip stayed
// on Auto until the 5-minute reconcile happened to run — the attach itself said nothing about it.
- const devinPane = await captureTmuxPane(session.tmuxPane, 60)
+ const devinPane = await captureTerminal(session.agentId, 60)
if (devinPane) runtimeProfiles.ingestPane(session, devinPane, true)
} else if (session.engine === 'commandcode') {
const normalizer = new CommandCodeNormalizer('live')
@@ -806,7 +1031,7 @@ async function runForeground(token: string): Promise<void> {
emitSessionEvents(session.sessionId, initialEvents)
console.log(`[agent] ${sid(session.agentId)} replayed the first turn its transcript already held · ${initialEvents.length} events`)
}
- console.log(`[agent] ${sid(session.agentId)} attached · engine=${session.engine} · pane=${session.tmuxPane} · session=${sid(session.sessionId)} · lines=${lines.length}`)
+ console.log(`[agent] ${sid(session.agentId)} attached · engine=${session.engine} · terminal=${primaryTerminalLabel(session)} · session=${sid(session.sessionId)} · lines=${lines.length}`)
// A first prompt that lands while this attach is running is already in the transcript we just
// folded, so its turn_started was consumed as history and the live turn would end up untracked.
// Replay that one event, after the attach log, so the recovery is visible in order.
@@ -828,13 +1053,40 @@ async function runForeground(token: string): Promise<void> {
if (pollsQuestions(session.engine)) questionWatcher.start(session.sessionId)
return true
}
+ const input = new SessionInputController({
+ getSession: (id) => registry.resolve(id),
+ validateRuntime: validateTerminal,
+ inject: submitTerminalAction,
+ sendKey: keyTerminalAction,
+ capture: captureTerminal,
+ onError: (sessionId, message) => {
+ backend.send({ type: 'error', agentId: agentIdFor(sessionId), dbSessionId: sessionId, payload: { message } })
+ const engine = registry.resolve(sessionId)?.engine
+ backend.sendCommander({ type: 'commander_event', agentId: agentIdFor(sessionId), dbSessionId: sessionId, payload: { kind: 'error', text: deviceErrorText(message, engine) } })
+ },
+ })
+ const acquireTerminalControl = (id: string): (() => void) | null => {
+ const agentId = registry.resolve(id)?.agentId ?? id
+ const releaseInput = input.acquireControl(agentId)
+ if (!releaseInput) return null
+ const releaseTerminal = pinTerminalControl(agentId)
+ if (!releaseTerminal) {
+ releaseInput()
+ return null
+ }
+ return () => {
+ releaseTerminal()
+ releaseInput()
+ }
+ }
// AskUserQuestion bridge: mirrors the question to the device's question screen, and keys the device's
- // answer back into the CLI's own dialog in the tmux pane.
+ // answer back into the CLI's own terminal dialog.
const questions = new AskQuestionController({
getSession: (id) => registry.resolve(id),
- capture: captureTmuxPane,
- sendText: sendToTmux,
- sendKey: sendKeyToTmux,
+ capture: captureTerminal,
+ sendText: submitTerminal,
+ sendKey: keyTerminal,
+ acquireControl: acquireTerminalControl,
})
// Command Code ENDS its turn in order to ask (its Stop hook fires, the dialog goes up, and the answer
// opens a NEW turn). With the turn closed the device tile falls back to the PREVIOUS task's recap — so
@@ -858,7 +1110,7 @@ async function runForeground(token: string): Promise<void> {
}
const questionWatcher = new QuestionWatcher({
getSession: (id) => registry.resolve(id),
- capture: captureTmuxPane,
+ capture: captureTerminal,
hasDevice: () => backend.hasCommander(),
isDriving: (sessionId) => questions.isDriving(sessionId),
onQuestion: (sessionId, requestId, shaped) => {
@@ -909,27 +1161,15 @@ async function runForeground(token: string): Promise<void> {
// and the voice router know. Resolve across the two, or every tile restores empty.
backend.recentProvider = (id, n) => mirror.recent(registry.resolve(id)?.sessionId || id, n)
- const input = new SessionInputController({
- getSession: (id) => registry.resolve(id),
- validateRuntime: validateSessionRuntime,
- inject: sendToTmux,
- sendKey: sendKeyToTmux,
- capture: captureTmuxPane,
- onError: (sessionId, message) => {
- backend.send({ type: 'error', agentId: agentIdFor(sessionId), dbSessionId: sessionId, payload: { message } })
- const engine = registry.resolve(sessionId)?.engine
- backend.sendCommander({ type: 'commander_event', agentId: agentIdFor(sessionId), dbSessionId: sessionId, payload: { kind: 'error', text: deviceErrorText(message, engine) } })
- },
- })
const runtimeController = new RuntimeProfileController({
manager: runtimeProfiles,
getSession: (id) => registry.resolve(id),
- validateRuntime: validateSessionRuntime,
- capture: captureTmuxPane,
- sendText: sendToTmux,
- sendLiteral: sendLiteralToTmux,
- sendKey: sendKeyToTmux,
- acquireInput: (id) => input.acquireControl(registry.resolve(id)?.agentId ?? id),
+ validateRuntime: validateTerminal,
+ capture: captureTerminal,
+ sendText: submitTerminal,
+ sendLiteral: typeTerminal,
+ sendKey: keyTerminal,
+ acquireInput: acquireTerminalControl,
})
/**
* Engine session id → the agent that owns it. The event stream speaks in ENGINE session ids while
@@ -945,6 +1185,7 @@ async function runForeground(token: string): Promise<void> {
return session ? runtimeProfiles.modelsForSession(session) : Promise.resolve([])
}
backend.runtimeProfileProvider = (session) => runtimeProfiles.selectedModel(session)
+ backend.onAgentRename = (session, name) => { void terminals.setTitle(session, name) }
backend.onRuntimeProfileUpdate = (sessionId, selectedModel) => runtimeController.setProfile(sessionId, selectedModel)
runtimeProfiles.onChanged = (sessionId) => {
const session = registry.resolve(sessionId)
@@ -994,7 +1235,7 @@ async function runForeground(token: string): Promise<void> {
}
emitSessionEvents = (sessionId: string, events: ReturnType<CursorNormalizer['ingest']>): void => {
- if (!events.length || !registry.has(sessionId)) return
+ if (!events.length || !registry.bySession(sessionId)?.active) return
for (const event of events) {
backend.send({ ...event, dbSessionId: sessionId })
if (event.type === 'turn_started') {
@@ -1007,7 +1248,7 @@ async function runForeground(token: string): Promise<void> {
registry.bySession(sessionId)?.engine ?? 'claude',
agentIdFor(sessionId),
)
- console.log(`[turn] ${sid(sessionId)} started · engine=${registry.bySession(sessionId)?.engine ?? 'claude'} · "${preview(event.payload.userMessage)}"`)
+ console.log(`[turn] ${sid(sessionId)} started · engine=${registry.bySession(sessionId)?.engine ?? 'claude'} · bytes=${Buffer.byteLength(event.payload.userMessage, 'utf8')}`)
input.onTurnStarted(agentIdFor(sessionId), event.payload.userMessage)
startHeartbeat(sessionId)
questionWatcher.start(sessionId) // Claude opens its dialog INSIDE a turn
@@ -1164,13 +1405,13 @@ async function runForeground(token: string): Promise<void> {
const lastRepairAttempt = new Map<string, number>()
const repairAttempts = new Map<string, number>()
- const bindObservedAgent = async (observed: DiscoveredTmuxAgent): Promise<void> => {
- const agent = registry.byPaneEngine(observed.tmuxPane, observed.engine)
+ const bindObservedAgent = async (observed: DiscoveredTerminalAgent): Promise<void> => {
+ const agent = registry.byProcess(observed.engine, observed.processIdentity)
if (!agent || agent.sessionId) return
let sessionId = observed.resumeSessionId
let transcriptPath: string | undefined
- let source = 'tmux-resume'
+ let source = 'terminal-resume'
if (sessionId) {
if (isRecentlyDeleted(sessionId)) return
const owner = registry.bySession(sessionId)
@@ -1207,9 +1448,10 @@ async function runForeground(token: string): Promise<void> {
transcriptPath,
cwd: observed.cwd,
source,
- tmuxPane: observed.tmuxPane,
+ runtimes: observed.runtimes,
+ primaryRuntimeKey: observed.primaryRuntimeKey,
processIdentity: observed.processIdentity,
- hookEvent: source === 'tmux-resume' ? 'TmuxResumeDiscovery' : 'ProcessRepair',
+ hookEvent: source === 'terminal-resume' ? 'TerminalResumeDiscovery' : 'ProcessRepair',
})
if (!result || !result.isNew) return
if (previousOwner && previousOwner.agentId !== result.entry.agentId) {
@@ -1219,29 +1461,60 @@ async function runForeground(token: string): Promise<void> {
lastRepairAttempt.delete(agent.agentId)
repairAttempts.delete(agent.agentId)
await handleRegistered(result.entry, result)
- console.log(`[discovery] bound ${observed.engine} session ${sid(result.entry.sessionId)} on ${observed.tmuxPane}`)
+ console.log(`[discovery] bound ${observed.engine} session ${sid(result.entry.sessionId)} via ${observed.primaryRuntimeKey}`)
}
- const agentReconciler = new TmuxAgentReconciler({
+ const agentReconciler = new TerminalAgentReconciler({
current: () => registry.list(),
+ backends: terminalBackends,
+ backendOrder: terminalConfig.backends,
+ herdrSessionOrder: terminalConfig.herdrSessions,
+ beforeProbe: refreshHerdrTargets,
+ transaction: (apply) => registry.transaction(apply),
onDiscovered: async (observed) => {
const opened = registry.openProcessAgent({
engine: observed.engine,
- tmuxPane: observed.tmuxPane,
+ runtimes: observed.runtimes,
+ primaryRuntimeKey: observed.primaryRuntimeKey,
cwd: observed.cwd,
processIdentity: observed.processIdentity,
})
if (!opened) return
- if (opened.evicted) console.log(`[discovery] ${observed.tmuxPane} replaced ${sid(opened.evicted)}`)
+ if (opened.evicted) console.log(`[discovery] ${observed.primaryRuntimeKey} replaced ${sid(opened.evicted)}`)
if (opened.isNew) {
- console.log(`[discovery] ${sid(opened.entry.agentId)} opened · engine=${observed.engine} · pane=${observed.tmuxPane}`)
+ console.log(`[discovery] ${sid(opened.entry.agentId)} opened · engine=${observed.engine} · terminal=${observed.primaryRuntimeKey}`)
announceSession(opened.entry)
}
await bindObservedAgent(observed)
},
onObserved: async (observed, current) => {
+ const wasDormant = !current.active
+ registry.updateRuntimes(current.agentId, observed.runtimes, observed.primaryRuntimeKey)
registry.updateProcessIdentity(current.agentId, observed.processIdentity)
await bindObservedAgent(observed)
+ if (wasDormant) {
+ const active = registry.byAgent(current.agentId)
+ if (!active) return
+ if (active.sessionId && !await attachSession(active)) {
+ registry.setActive(active.agentId, false)
+ return
+ }
+ syncRecapPool()
+ announceSession(active)
+ }
+ },
+ onDormant: (agent, reason) => {
+ if (!agent.active) return
+ registry.setActive(agent.agentId, false)
+ invalidateTerminalControl(agent.agentId)
+ input.forget(agent.agentId)
+ if (agent.sessionId) {
+ questionWatcher.stop(agent.sessionId)
+ stopHeartbeat(agent.sessionId)
+ }
+ console.log(`[discovery] ${sid(agent.agentId)} dormant · ${reason}`)
+ backend.send({ type: 'agent_deleted', payload: { agentId: agent.agentId } })
+ backend.sendCommander({ type: 'agent_deleted', payload: { agentId: agent.agentId } })
},
onRemoved: (agent, reason) => {
console.log(`[discovery] ${sid(agent.agentId)} removed · ${reason}`)
@@ -1250,15 +1523,65 @@ async function runForeground(token: string): Promise<void> {
})
// SessionEnd describes the mutable engine session, never process lifetime. Reconcile now; discovery
- // decides whether the agent still exists from tmux + ps.
+ // decides whether the agent still exists from terminal inventory + ps.
const onSessionEnd = (_sessionId: string, _reason: string | undefined): void => {
void agentReconciler.trigger()
}
const { server: hookServer, port: hookPort } = await startHookServer(env.PORT, {
- resolveHookAgent: async ({ engine, tmuxPane }) => {
- await agentReconciler.triggerHint(tmuxPane, engine)
- return registry.byPaneEngine(tmuxPane, engine) ?? null
+ resolveHookAgent: async ({ engine, runtimeHints, callerPid }) => {
+ if (!callerPid) return null
+ const resolved: TerminalRuntimeRef[] = []
+ for (const hint of runtimeHints ?? []) {
+ if (hint.backend === 'tmux') {
+ if (tmuxBackend) resolved.push({ backend: 'tmux', paneId: hint.paneId })
+ continue
+ }
+ const backend = herdrBackends.find((candidate) =>
+ candidate.endpoint.sessionName === hint.sessionName
+ && (!hint.socketPath || candidate.endpoint.socketPath === hint.socketPath))
+ if (!backend) continue
+ const runtime = await backend.resolveRuntimeHint(hint.paneId)
+ if (runtime.state === 'succeeded') resolved.push(runtime.value)
+ }
+ for (const runtime of resolved) await agentReconciler.triggerHint(runtime, engine)
+
+ const rows = await processRows()
+ if (!rows) return null
+ const callerBelongsTo = (session: RegisteredSession): boolean => {
+ const expectedPid = session.processIdentity?.pid
+ if (!expectedPid) return false
+ const byPid = new Map(rows.map((row) => [row.pid, row.parentPid]))
+ let pid = callerPid
+ const visited = new Set<number>()
+ while (pid > 0 && !visited.has(pid)) {
+ if (pid === expectedPid) return true
+ visited.add(pid)
+ pid = byPid.get(pid) ?? 0
+ }
+ return false
+ }
+ const candidates = new Map<string, RegisteredSession>()
+ for (const runtime of resolved) {
+ const candidate = registry.byRuntimeEngine(runtime, engine)
+ if (candidate && callerBelongsTo(candidate)) candidates.set(candidate.agentId, candidate)
+ }
+ // A moved Herdr pane may leave an inherited stale route. Caller/process correlation is the
+ // deterministic fallback, but only within a configured Herdr session named by the hook.
+ if (!candidates.size && runtimeHints?.some((hint) => hint.backend === 'herdr')) {
+ const configuredSessions = new Set(runtimeHints
+ .filter((hint): hint is Extract<HookTerminalHint, { backend: 'herdr' }> => hint.backend === 'herdr')
+ .filter((hint) => herdrBackends.some((backend) => backend.endpoint.sessionName === hint.sessionName
+ && (!hint.socketPath || backend.endpoint.socketPath === hint.socketPath)))
+ .map((hint) => hint.sessionName))
+ for (const candidate of registry.list()) {
+ if (candidate.engine !== engine || !callerBelongsTo(candidate)) continue
+ if (candidate.runtimes.some((runtime) => runtime.backend === 'herdr' && configuredSessions.has(runtime.sessionName))) {
+ candidates.set(candidate.agentId, candidate)
+ }
+ }
+ }
+ return candidates.size === 1 ? [...candidates.values()][0] : null
},
onRegistered: handleRegistered,
onSessionEnd,
@@ -1412,8 +1735,32 @@ async function runForeground(token: string): Promise<void> {
deviceE2eeConnected: backend.deviceE2eeConnected(),
uptimeSec: Math.round((Date.now() - startedAt) / 1000),
fingerprint: backend.e2eeFingerprint(),
- config: { watching: 'tmux sessions across all supported engines (including Grok)', dataDir: tildify(env.ADAPTER_DATA_DIR), port: daemonPort() },
- sessions: registry.list().map((s) => ({ id: s.agentId, sessionId: s.sessionId, name: projectDisplayName(s), engine: s.engine, cwd: tildify(s.cwd ?? ''), tmuxPane: s.tmuxPane, updatedAt: s.updatedAt })),
+ config: {
+ watching: `${terminalConfig.backends.join(' + ')} terminals across all supported engines`,
+ terminalBackends: terminalConfig.backends,
+ herdrSessions: terminalConfig.herdrSessions,
+ terminalTargets: [
+ ...(tmuxBackend ? [{ backend: 'tmux', instance: 'default', state: 'configured' }] : []),
+ ...terminalConfig.herdrSessions.map((sessionName) => ({
+ backend: 'herdr',
+ sessionName,
+ ...(herdrTargetStates.get(sessionName) ?? { state: 'unavailable', reason: 'not yet resolved' }),
+ })),
+ ],
+ dormantAgents: registry.list().filter((session) => !session.active).length,
+ dataDir: tildify(env.ADAPTER_DATA_DIR),
+ port: daemonPort(),
+ },
+ sessions: registry.active().map((s) => ({
+ id: s.agentId,
+ sessionId: s.sessionId,
+ name: projectDisplayName(s),
+ engine: s.engine,
+ cwd: tildify(s.cwd ?? ''),
+ tmuxPane: s.tmuxPane || null,
+ terminal: { primary: s.primaryRuntimeKey, runtimes: s.runtimes },
+ updatedAt: s.updatedAt,
+ })),
pairs: backend.listPairs(),
pending: backend.pendingPair(),
}),
@@ -1447,7 +1794,7 @@ async function runForeground(token: string): Promise<void> {
// This runs from a void-discarded async read, so a throw here would be an unhandledRejection. A
// single malformed line must never take the daemon down — contain it per line and move on.
try {
- if (!registry.has(evt.sessionId)) return // scope to tmux-registered sessions
+ if (!registry.has(evt.sessionId)) return // scope to terminal-registered sessions
const session = registry.bySession(evt.sessionId)
if (!session || session.engine !== evt.engine) return
runtimeProfiles.ingest(session, evt.text)
@@ -1510,8 +1857,8 @@ async function runForeground(token: string): Promise<void> {
// hook/store repair path binds it as soon as the engine reports a session. Attaching an
// empty session id here would tear down an agent the user can see running in their pane, which is
// exactly what a self-update restart must never do.
- if (!session.sessionId) continue
- if (!await attachSession(session)) forgetSession(session.sessionId)
+ if (!session.active || !session.sessionId) continue
+ if (!await attachSession(session)) registry.setActive(session.agentId, false)
else {
input.setTurnOpen(
session.agentId,
@@ -1533,7 +1880,7 @@ async function runForeground(token: string): Promise<void> {
}
watcher.start()
await cursorDiscovery.start()
- agentReconciler.start(env.TMUX_REAP_INTERVAL_MS)
+ agentReconciler.start(env.TERMINAL_RECONCILE_INTERVAL_MS ?? env.TMUX_REAP_INTERVAL_MS)
for (const task of await loadCursorPendingTasks(env.ADAPTER_DATA_DIR)) {
onCursorTaskStart(task.sessionId, task.toolUseId, task.input)
}
@@ -1551,11 +1898,11 @@ async function runForeground(token: string): Promise<void> {
await Promise.all(registry.list().map((session) => runtimeProfiles.ingestConfig(session, true)))
await watcher.pollAll()
await Promise.all(registry.list().map(async (session) => {
- const capture = await captureTmuxPane(session.tmuxPane, 120)
+ const capture = await captureTerminal(session.agentId, 120)
if (capture) runtimeProfiles.ingestPane(session, capture, true)
}))
})
- await syncPaneTitles()
+ await syncTerminalTitles()
const includeDevice = reconcileNeedsDeviceAnnouncement
reconcileNeedsDeviceAnnouncement = false
for (const session of registry.list()) {
@@ -1593,7 +1940,7 @@ async function runForeground(token: string): Promise<void> {
setInterval(() => {
for (const session of registry.list()) {
if (!PANE_POLLED_ENGINES.has(session.engine)) continue
- void captureTmuxPane(session.tmuxPane, 60)
+ void captureTerminal(session.agentId, 60)
.then((capture) => { if (capture) runtimeProfiles.ingestPane(session, capture) })
.catch(() => undefined)
}
@@ -1607,8 +1954,8 @@ async function runForeground(token: string): Promise<void> {
}, RUNTIME_RECONCILE_MS)
const PANE_TITLE_SYNC_MS = 5_000
const paneTitleSyncTimer = setInterval(() => {
- void syncPaneTitles().catch((err) => {
- console.error('[tmux-title] sync failed:', err instanceof Error ? err.message : err)
+ void syncTerminalTitles().catch((err) => {
+ console.error('[terminal-title] sync failed:', err instanceof Error ? err.message : err)
})
}, PANE_TITLE_SYNC_MS)
@@ -1660,12 +2007,21 @@ async function runForeground(token: string): Promise<void> {
// boundary. Without the tombstone that hook re-registers the session and the tile comes straight back.
markDeleted(sessionId)
if (s?.processIdentity) {
- agentReconciler.suppress({ engine: s.engine, tmuxPane: s.tmuxPane, processIdentity: s.processIdentity })
+ agentReconciler.suppress(s)
}
forgetSession(sessionId, { force: true })
if (!s) return
void terminateDeletedAgent(s, {
- checkRuntime: checkSessionRuntime,
+ checkRuntime: async (session) => {
+ const expected = session.processIdentity
+ if (!expected) return { state: 'gone', reason: 'agent has no saved process identity' }
+ const rows = await processRows()
+ if (!rows) return { state: 'unknown', reason: 'process table is unavailable' }
+ const live = rows.find((row) => row.pid === expected.pid)
+ return live && live.startMarker === expected.startMarker && live.executable === expected.executable
+ ? { state: 'alive' }
+ : { state: 'gone', reason: 'saved process identity is no longer running' }
+ },
kill: (pid, signal) => process.kill(pid, signal),
sleep: (ms) => new Promise((resolve) => { const t = setTimeout(resolve, ms); t.unref?.() }),
log: (message) => console.log(message),
@@ -1689,9 +2045,9 @@ async function runForeground(token: string): Promise<void> {
// error in the user's terminal instead of running their turn.
const adapted = adaptSlashCommand(content, engine)
if (adapted !== content) {
- console.log(`[msg] ${sid(sessionId)} slash-command adapted for engine=${engine} · "${preview(content, 40)}" → "${preview(adapted, 40)}"`)
+ console.log(`[msg] ${sid(sessionId)} slash-command adapted for engine=${engine}`)
}
- console.log(`[msg] ${sid(sessionId)} recv · engine=${engine} · len=${adapted.length} · "${preview(adapted)}"`)
+ console.log(`[msg] ${sid(sessionId)} recv · engine=${engine} · bytes=${Buffer.byteLength(adapted, 'utf8')}`)
input.submit(record?.agentId ?? sessionId, adapted)
}
diff --git a/cli/src/config/env.ts b/cli/src/config/env.ts
index 1a126cb59..fd9af980a 100644
--- a/cli/src/config/env.ts
+++ b/cli/src/config/env.ts
@@ -3,6 +3,7 @@ import { existsSync, mkdirSync, readdirSync, renameSync, rmSync } from 'fs'
import { homedir } from 'os'
import { join } from 'path'
import { z } from 'zod'
+import { parseHerdrSessions, parseTerminalBackends } from './terminalConfig.js'
// Packaged files (cli.js/notify.mjs) live in ~/.harness/cli; mutable state in ~/.harness/cli/data.
// `~/.harness` is the PRODUCT data root and does not move — see the naming discipline in CLAUDE.md.
@@ -179,6 +180,23 @@ const envSchema = z.object({
ANALYTICS_FLUSH_INTERVAL_MS: z.string().default('60000').transform(Number),
// Set to 'true' to skip auto-installing lifecycle hooks for every supported engine.
DISABLE_HOOK_INSTALL: z.string().default('false').transform((v) => v === 'true'),
+ // Additive terminal capability. Order controls deterministic primary-route tie breaking.
+ TERMINAL_BACKENDS: z.string().default('tmux').transform((value, context) => {
+ try { return parseTerminalBackends(value) } catch (error) {
+ context.addIssue({ code: 'custom', message: error instanceof Error ? error.message : 'invalid terminal backends' })
+ return z.NEVER
+ }
+ }),
+ // Configured Herdr named sessions only. Hook-supplied socket paths never expand this allowlist.
+ HERDR_SESSIONS: z.string().default('default').transform((value, context) => {
+ try { return parseHerdrSessions(value) } catch (error) {
+ context.addIssue({ code: 'custom', message: error instanceof Error ? error.message : 'invalid Herdr sessions' })
+ return z.NEVER
+ }
+ }),
+ HERDR_BIN: z.string().default('herdr'),
+ // Neutral discovery interval. The legacy tmux name remains a one-release fallback.
+ TERMINAL_RECONCILE_INTERVAL_MS: z.string().optional().transform((value) => value === undefined ? undefined : Number(value)),
// How often (ms) the reaper checks tmux panes and drops dead sessions.
TMUX_REAP_INTERVAL_MS: z.string().default('5000').transform(Number),
// Path to the `claude` CLI for the device turn-recap one-shot (else resolved from PATH).
@@ -269,6 +287,11 @@ function validateEnv(): Env {
if (!process.env.WEB_URL && /^wss?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/.test(data.BACKEND_WS_URL)) {
data.WEB_URL = 'http://localhost:3000'
}
+ const reconcileMs = data.TERMINAL_RECONCILE_INTERVAL_MS ?? data.TMUX_REAP_INTERVAL_MS
+ if (!Number.isFinite(reconcileMs) || reconcileMs < 5_000) {
+ console.error('Invalid environment variables: TERMINAL_RECONCILE_INTERVAL_MS must be at least 5000')
+ process.exit(1)
+ }
return data
}
diff --git a/cli/src/config/terminalConfig.spec.ts b/cli/src/config/terminalConfig.spec.ts
new file mode 100644
index 000000000..1b63cabcc
--- /dev/null
+++ b/cli/src/config/terminalConfig.spec.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest'
+import { parseHerdrSessions, parseTerminalBackends, parseTerminalConfig } from './terminalConfig.js'
+
+describe('terminal backend configuration', () => {
+ it('defaults to tmux without requiring Herdr', () => {
+ expect(parseTerminalConfig({})).toEqual({ backends: ['tmux'], herdrSessions: [] })
+ })
+
+ it('preserves backend and named-session order for deterministic ranking', () => {
+ expect(parseTerminalConfig({
+ TERMINAL_BACKENDS: 'herdr,tmux',
+ HERDR_SESSIONS: 'work,default',
+ })).toEqual({ backends: ['herdr', 'tmux'], herdrSessions: ['work', 'default'] })
+ })
+
+ it.each(['', ' ', 'tmux,', 'tmux,,herdr', 'tmux,tmux', 'screen'])('rejects invalid TERMINAL_BACKENDS=%j', (value) => {
+ expect(() => parseTerminalBackends(value)).toThrow(/TERMINAL_BACKENDS/)
+ })
+
+ it.each(['', 'default,', 'default,default', '../socket', '/tmp/socket', 'work space'])('rejects invalid HERDR_SESSIONS=%j', (value) => {
+ expect(() => parseHerdrSessions(value)).toThrow(/HERDR_SESSIONS/)
+ })
+})
diff --git a/cli/src/config/terminalConfig.ts b/cli/src/config/terminalConfig.ts
new file mode 100644
index 000000000..da83bc067
--- /dev/null
+++ b/cli/src/config/terminalConfig.ts
@@ -0,0 +1,48 @@
+import type { TerminalBackendName } from '../lib/terminalTypes.js'
+
+const HERDR_SESSION_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/
+
+export interface TerminalConfig {
+ backends: readonly TerminalBackendName[]
+ herdrSessions: readonly string[]
+}
+
+function strictList(value: string, field: string): string[] {
+ const parts = value.split(',').map((part) => part.trim())
+ if (!parts.length || parts.some((part) => !part)) {
+ throw new Error(`${field} must be a non-empty comma-separated list`)
+ }
+ if (new Set(parts).size !== parts.length) throw new Error(`${field} must not contain duplicates`)
+ return parts
+}
+
+export function parseTerminalBackends(value = 'tmux'): TerminalBackendName[] {
+ const values = strictList(value, 'TERMINAL_BACKENDS')
+ for (const backend of values) {
+ if (backend !== 'tmux' && backend !== 'herdr') {
+ throw new Error(`TERMINAL_BACKENDS contains unsupported backend "${backend}"; expected tmux, herdr, or tmux,herdr`)
+ }
+ }
+ return values as TerminalBackendName[]
+}
+
+export function parseHerdrSessions(value = 'default'): string[] {
+ const values = strictList(value, 'HERDR_SESSIONS')
+ for (const session of values) {
+ if (!HERDR_SESSION_RE.test(session)) {
+ throw new Error(`HERDR_SESSIONS contains invalid session name "${session}"`)
+ }
+ }
+ return values
+}
+
+export function parseTerminalConfig(input: {
+ TERMINAL_BACKENDS?: string
+ HERDR_SESSIONS?: string
+}): TerminalConfig {
+ const backends = parseTerminalBackends(input.TERMINAL_BACKENDS)
+ return {
+ backends,
+ herdrSessions: backends.includes('herdr') ? parseHerdrSessions(input.HERDR_SESSIONS) : [],
+ }
+}
diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.ts
index 679d36633..723114034 100644
--- a/cli/src/hookNotify.spec.ts
+++ b/cli/src/hookNotify.spec.ts
@@ -1,17 +1,25 @@
-import { spawn } from 'child_process'
+import { execFileSync, spawn, spawnSync } from 'child_process'
import { createServer } from 'http'
-import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'fs'
-import { tmpdir } from 'os'
+import { createServer as createNetServer } from 'net'
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'fs'
+import { homedir, tmpdir } from 'os'
import { join } from 'path'
import { fileURLToPath } from 'url'
import { afterEach, describe, expect, it } from 'vitest'
const HOOK = fileURLToPath(new URL('../hook/notify.mjs', import.meta.url))
const servers: ReturnType<typeof createServer>[] = []
+const netServers: ReturnType<typeof createNetServer>[] = []
const tmpDirs: string[] = []
+function writeLegacyStateFile(path: string, value: string): void {
+ writeFileSync(path, value, { mode: 0o644 })
+ chmodSync(path, 0o644)
+}
+
afterEach(async () => {
await Promise.all(servers.splice(0).map((server) => new Promise<void>((resolve) => server.close(() => resolve()))))
+ await Promise.all(netServers.splice(0).map((server) => new Promise<void>((resolve) => server.close(() => resolve()))))
for (const dir of tmpDirs.splice(0)) rmSync(dir, { recursive: true, force: true })
})
@@ -53,7 +61,7 @@ function runHook(opts: RunHookOpts): Promise<string> {
const executable = opts.processExecutable ?? (opts.processEngine === 'cursor' ? 'agent' : opts.processEngine)
const processArgs = opts.processArgs ?? executable
writeFileSync(join(binDir, 'tmux'), '#!/bin/sh\necho 7000\n', { mode: 0o755 })
- writeFileSync(join(binDir, 'ps'), `#!/bin/sh\nprintf '%s\\n' '7000 1 zsh Mon Aug 10 10:00:00 2026 -zsh' '7001 7000 ${executable} Mon Aug 10 10:00:01 2026 ${processArgs}'\n`, { mode: 0o755 })
+ writeFileSync(join(binDir, 'ps'), `#!/bin/sh\nprintf '%s\\n' '7000 1 zsh Mon Aug 10 10:00:00 2026 -zsh' '7001 7000 ${executable} Mon Aug 10 10:00:01 2026 ${processArgs}' '${process.pid} 7001 node Mon Aug 10 10:00:02 2026 hook-parent'\n`, { mode: 0o755 })
if (opts.processEngine === 'cursor') {
const target = join(binDir, 'cursor-agent-target')
writeFileSync(target, '#!/bin/sh\n', { mode: 0o755 })
@@ -80,6 +88,11 @@ function runHook(opts: RunHookOpts): Promise<string> {
if (opts.hermesHome) args.push('--hermes-home', opts.hermesHome)
if (opts.grokHome) args.push('--grok-home', opts.grokHome)
if (opts.devinHome) args.push('--devin-home', opts.devinHome)
+ const hookDataDir = opts.dataDir || process.env.ADAPTER_DATA_DIR
+ if (hookDataDir) {
+ mkdirSync(hookDataDir, { recursive: true, mode: 0o700 })
+ try { writeFileSync(join(hookDataDir, 'hook-credential'), `${'a'.repeat(43)}\n`, { mode: 0o600, flag: 'wx' }) } catch { /* already exists */ }
+ }
const child = spawn(process.execPath, args, {
env,
stdio: ['pipe', 'pipe', 'inherit'],
@@ -115,7 +128,42 @@ async function collect(): Promise<{ port: number; requests: Array<{ url: string;
return { port: address.port, requests }
}
-describe('hook notify tmux scope', () => {
+describe('hook notify terminal scope', () => {
+ it('refuses a symlinked hook credential instead of authenticating with its target', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-credential-link-'))
+ tmpDirs.push(dir)
+ const dataDir = join(dir, 'data')
+ const target = join(dir, 'credential-target')
+ mkdirSync(dataDir, { recursive: true })
+ writeFileSync(target, `${'a'.repeat(43)}\n`, { mode: 0o600 })
+ symlinkSync(target, join(dataDir, 'hook-credential'))
+ const { port, requests } = await collect()
+
+ await runHook({ port, tmuxPane: '%42', dataDir })
+
+ expect(requests).toEqual([])
+ })
+
+ it('rejects a hook credential FIFO without blocking', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-credential-fifo-'))
+ tmpDirs.push(dir)
+ const dataDir = join(dir, 'data')
+ mkdirSync(dataDir, { mode: 0o700 })
+ const credential = join(dataDir, 'hook-credential')
+ execFileSync('mkfifo', [credential])
+
+ const result = spawnSync(process.execPath, [HOOK, '--port', '9', '--data-dir', dataDir], {
+ encoding: 'utf8',
+ env: { ...process.env, TMUX_PANE: '%42' },
+ input: JSON.stringify({ hook_event_name: 'SessionEnd', session_id: 'fifo', reason: 'logout' }),
+ timeout: 1_500,
+ })
+
+ expect(result.error).toBeUndefined()
+ expect(result.status).toBe(0)
+ expect(statSync(credential).isFIFO()).toBe(true)
+ })
+
it('forwards Cursor Task/stop hooks, journals the launcher, and always prints JSON', async () => {
const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-cursor-'))
tmpDirs.push(dir)
@@ -158,6 +206,10 @@ describe('hook notify tmux scope', () => {
toolUseId: 'call-1',
toolName: 'Task',
input: { description: 'Inspect', prompt: 'Read code', model: 'inherit' },
+ engine: 'cursor',
+ tmuxPane: '%21',
+ runtimeHints: [{ backend: 'tmux', paneId: '%21' }],
+ callerPid: expect.any(Number),
},
}])
expect(JSON.parse(readFileSync(join(dataDir, 'cursor-pending-tasks.json'), 'utf8'))).toMatchObject([{
@@ -295,7 +347,14 @@ describe('hook notify tmux scope', () => {
await runHook({ port: address.port, tmuxPane: '%42' })
expect(requests).toEqual([{
url: '/api/hook/session-end',
- body: { sessionId: 'session-test', reason: 'logout' },
+ body: {
+ sessionId: 'session-test',
+ reason: 'logout',
+ engine: 'claude',
+ tmuxPane: '%42',
+ runtimeHints: [{ backend: 'tmux', paneId: '%42' }],
+ callerPid: expect.any(Number),
+ },
}])
})
@@ -306,6 +365,9 @@ describe('hook notify tmux scope', () => {
const dataDir = join(dir, 'data')
const transcriptPath = join(claudeProjectsDir, 'demo', 'session-1.jsonl')
mkdirSync(join(claudeProjectsDir, 'demo'), { recursive: true })
+ mkdirSync(dataDir, { recursive: true })
+ chmodSync(dataDir, 0o755)
+ writeLegacyStateFile(join(dataDir, 'registry.json'), '[]')
writeFileSync(transcriptPath, '{}\n')
await runHook({
@@ -337,6 +399,75 @@ describe('hook notify tmux scope', () => {
model: 'sonnet',
cliVersion: '1.0.0',
}])
+ expect(statSync(dataDir).mode & 0o777).toBe(0o700)
+ expect(statSync(join(dataDir, 'registry.json')).mode & 0o777).toBe(0o600)
+ expect(statSync(join(dataDir, 'registry-boot')).mode & 0o777).toBe(0o600)
+ })
+
+ it('leaves a corrupt offline registry byte-identical instead of replacing it', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-offline-corrupt-'))
+ tmpDirs.push(dir)
+ const claudeProjectsDir = join(dir, 'claude-projects')
+ const dataDir = join(dir, 'data')
+ const transcriptPath = join(claudeProjectsDir, 'demo', 'session-corrupt.jsonl')
+ const registryFile = join(dataDir, 'registry.json')
+ const corrupt = '[{"schemaVersion":2'
+ mkdirSync(join(claudeProjectsDir, 'demo'), { recursive: true })
+ mkdirSync(dataDir, { recursive: true })
+ writeFileSync(transcriptPath, '{}\n')
+ writeFileSync(registryFile, corrupt, { mode: 0o600 })
+
+ await runHook({
+ port: 9,
+ tmuxPane: '%70',
+ processEngine: 'claude',
+ dataDir,
+ claudeProjectsDir,
+ input: {
+ hook_event_name: 'SessionStart',
+ session_id: 'session-corrupt',
+ transcript_path: transcriptPath,
+ cwd: '/tmp/demo',
+ },
+ })
+
+ expect(readFileSync(registryFile, 'utf8')).toBe(corrupt)
+ })
+
+ it('leaves malformed current, future, and legacy rows byte-identical while offline', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-offline-invalid-v2-'))
+ tmpDirs.push(dir)
+ const claudeProjectsDir = join(dir, 'claude-projects')
+ const dataDir = join(dir, 'data')
+ const transcriptPath = join(claudeProjectsDir, 'demo', 'session-invalid-v2.jsonl')
+ const registryFile = join(dataDir, 'registry.json')
+ mkdirSync(join(claudeProjectsDir, 'demo'), { recursive: true })
+ mkdirSync(dataDir, { recursive: true })
+ writeFileSync(transcriptPath, '{}\n')
+
+ for (const bytes of [
+ JSON.stringify([{ schemaVersion: 2, agentId: 'damaged' }]),
+ JSON.stringify([{ schemaVersion: '3', agentId: 'future' }]),
+ JSON.stringify([{}]),
+ JSON.stringify([7]),
+ JSON.stringify([{ agentId: 'legacy-agent' }]),
+ ]) {
+ writeFileSync(registryFile, bytes, { mode: 0o600 })
+ await runHook({
+ port: 9,
+ tmuxPane: '%71',
+ processEngine: 'claude',
+ dataDir,
+ claudeProjectsDir,
+ input: {
+ hook_event_name: 'SessionStart',
+ session_id: 'session-invalid-v2',
+ transcript_path: transcriptPath,
+ cwd: '/tmp/demo',
+ },
+ })
+ expect(readFileSync(registryFile, 'utf8')).toBe(bytes)
+ }
})
it('falls back with Codex engine under CODEX_HOME/sessions', async () => {
@@ -369,6 +500,141 @@ describe('hook notify tmux scope', () => {
expect(registry).toMatchObject([{ sessionId: 'codex-session', engine: 'codex', tmuxPane: '%8' }])
})
+ it('uses only a configured, validated Herdr endpoint for daemon-down registration', async () => {
+ const dir = mkdtempSync(join(homedir(), '.adapter-hook-herdr-'))
+ tmpDirs.push(dir)
+ chmodSync(dir, 0o775)
+ const dataDir = join(dir, 'data')
+ const claudeProjectsDir = join(dir, 'claude-projects')
+ const transcriptPath = join(claudeProjectsDir, 'demo', 'herdr-session.jsonl')
+ const socketPath = join(dir, 'herdr.sock')
+ mkdirSync(join(claudeProjectsDir, 'demo'), { recursive: true })
+ mkdirSync(dataDir, { recursive: true })
+ chmodSync(dataDir, 0o755)
+ writeFileSync(transcriptPath, '{}\n')
+ const server = createNetServer((socket) => {
+ let raw = ''
+ socket.on('data', (chunk) => { raw += chunk.toString('utf8') })
+ socket.on('end', () => {
+ const request = JSON.parse(raw.trim()) as { id: string; method: string }
+ const result = request.method === 'ping'
+ ? { type: 'pong', version: '0.8.0', protocol: 19 }
+ : request.method === 'pane.get'
+ ? { type: 'pane_info', pane: { pane_id: 'w1:p1', terminal_id: 'terminal-1' } }
+ : { type: 'pane_process_info', process_info: { pane_id: 'w1:p1', shell_pid: 7000 } }
+ socket.end(`${JSON.stringify({ id: request.id, result })}\n`)
+ })
+ })
+ netServers.push(server)
+ await new Promise<void>((resolve) => server.listen(socketPath, resolve))
+ chmodSync(socketPath, 0o600)
+ const socket = statSync(socketPath)
+ writeFileSync(join(dataDir, 'terminal-config.json'), `${JSON.stringify({
+ version: 1,
+ updatedAt: Date.now(),
+ backends: ['herdr'],
+ herdrEndpoints: [{
+ sessionName: 'test', endpointId: 'endpoint-test', socketPath,
+ generation: { device: socket.dev, inode: socket.ino },
+ }],
+ })}\n`, { mode: 0o600 })
+ chmodSync(join(dataDir, 'terminal-config.json'), 0o644)
+
+ await runHook({
+ port: 9,
+ processEngine: 'claude',
+ dataDir,
+ claudeProjectsDir,
+ env: { HERDR_PANE_ID: 'w1:p1', HERDR_SESSION: 'test', HERDR_SOCKET_PATH: socketPath },
+ input: {
+ hook_event_name: 'SessionStart', session_id: 'herdr-session', transcript_path: transcriptPath, cwd: '/tmp/demo',
+ },
+ })
+
+ expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))).toMatchObject([{
+ schemaVersion: 2,
+ active: true,
+ sessionId: 'herdr-session',
+ primaryRuntimeKey: 'herdr\u0000endpoint-test\u0000w1:p1',
+ runtimes: [{
+ backend: 'herdr', endpointId: 'endpoint-test', sessionName: 'test', terminalId: 'terminal-1', paneId: 'w1:p1',
+ }],
+ }])
+ expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))[0]).not.toHaveProperty('tmuxPane')
+ expect(statSync(join(dataDir, 'terminal-config.json')).mode & 0o777).toBe(0o600)
+ })
+
+ it('rejects a world-writable Herdr endpoint parent during daemon-down registration', async () => {
+ const dir = mkdtempSync(join(homedir(), '.adapter-hook-herdr-world-writable-'))
+ tmpDirs.push(dir)
+ const dataDir = join(dir, 'data')
+ const claudeProjectsDir = join(dir, 'claude-projects')
+ const transcriptPath = join(claudeProjectsDir, 'demo', 'herdr-session.jsonl')
+ const socketPath = join(dir, 'herdr.sock')
+ mkdirSync(join(claudeProjectsDir, 'demo'), { recursive: true })
+ mkdirSync(dataDir, { mode: 0o700 })
+ writeFileSync(transcriptPath, '{}\n')
+ let requestCount = 0
+ const server = createNetServer((socket) => {
+ requestCount++
+ socket.end()
+ })
+ netServers.push(server)
+ await new Promise<void>((resolve) => server.listen(socketPath, resolve))
+ chmodSync(socketPath, 0o600)
+ const socket = statSync(socketPath)
+ writeFileSync(join(dataDir, 'terminal-config.json'), `${JSON.stringify({
+ version: 1,
+ updatedAt: Date.now(),
+ backends: ['herdr'],
+ herdrEndpoints: [{
+ sessionName: 'test', endpointId: 'endpoint-test', socketPath,
+ generation: { device: socket.dev, inode: socket.ino },
+ }],
+ })}\n`, { mode: 0o600 })
+ chmodSync(dir, 0o777)
+
+ await runHook({
+ port: 9,
+ processEngine: 'claude',
+ dataDir,
+ claudeProjectsDir,
+ env: { HERDR_PANE_ID: 'w1:p1', HERDR_SESSION: 'test', HERDR_SOCKET_PATH: socketPath },
+ input: {
+ hook_event_name: 'SessionStart', session_id: 'herdr-session', transcript_path: transcriptPath, cwd: '/tmp/demo',
+ },
+ })
+
+ expect(requestCount).toBe(0)
+ expect(() => readFileSync(join(dataDir, 'registry.json'), 'utf8')).toThrow()
+ })
+
+ it('rejects a group-writable Herdr config without changing or trusting it', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-herdr-unsafe-config-'))
+ tmpDirs.push(dir)
+ const dataDir = join(dir, 'data')
+ const config = join(dataDir, 'terminal-config.json')
+ mkdirSync(dataDir, { mode: 0o700 })
+ writeFileSync(config, `${JSON.stringify({
+ version: 1,
+ updatedAt: Date.now(),
+ backends: ['herdr'],
+ herdrEndpoints: [],
+ })}\n`, { mode: 0o600 })
+ chmodSync(config, 0o660)
+
+ await runHook({
+ port: 9,
+ processEngine: 'claude',
+ dataDir,
+ env: { HERDR_PANE_ID: 'w1:p1', HERDR_SESSION: 'test', HERDR_SOCKET_PATH: join(dir, 'herdr.sock') },
+ input: { hook_event_name: 'SessionStart', session_id: 'unsafe-config' },
+ })
+
+ expect(statSync(config).mode & 0o777).toBe(0o660)
+ expect(() => readFileSync(join(dataDir, 'registry.json'), 'utf8')).toThrow()
+ })
+
it('does not treat engine names in unrelated process arguments as an offline agent', async () => {
const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-process-false-positive-'))
tmpDirs.push(dir)
@@ -550,9 +816,10 @@ describe('hook notify tmux scope', () => {
const transcriptPath = join(claudeProjectsDir, 'demo', 'fresh.jsonl')
mkdirSync(join(claudeProjectsDir, 'demo'), { recursive: true })
mkdirSync(dataDir, { recursive: true })
+ chmodSync(dataDir, 0o755)
writeFileSync(transcriptPath, '{}\n')
- writeFileSync(join(dataDir, 'registry-boot'), '1')
- writeFileSync(join(dataDir, 'registry.json'), JSON.stringify([{ sessionId: 'stale', tmuxPane: '%1' }]))
+ writeLegacyStateFile(join(dataDir, 'registry-boot'), '1')
+ writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([{ sessionId: 'stale', tmuxPane: '%1' }]))
await runHook({
port: 9,
@@ -603,7 +870,15 @@ describe('hook notify Grok lifecycle', () => {
await runHook({ port, tmuxPane: '%44', engine: 'grok', grokHome, input: { hookEventName: 'stop_failure', sessionId, cwd } })
expect(requests).toEqual([{
url: '/api/hook/turn-stop',
- body: { sessionId, transcriptPath: transcript, status: 'error' },
+ body: {
+ sessionId,
+ transcriptPath: transcript,
+ status: 'error',
+ engine: 'grok',
+ tmuxPane: '%44',
+ runtimeHints: [{ backend: 'tmux', paneId: '%44' }],
+ callerPid: expect.any(Number),
+ },
}])
})
diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.ts
index 0768de3d7..5fe7bdbb9 100644
--- a/cli/src/hookServer.spec.ts
+++ b/cli/src/hookServer.spec.ts
@@ -1,6 +1,8 @@
import type { Server } from 'node:http'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { startHookServer, type HookServerHandlers } from './hookServer.js'
+import { env } from './config/env.js'
+import { readHookCredential } from './lib/hookAuth.js'
let server: Server | null = null
@@ -18,16 +20,22 @@ async function start(overrides: Partial<HookServerHandlers> = {}) {
}
const started = await startHookServer(0, handlers)
server = started.server
- return { handlers, base: `http://127.0.0.1:${started.port}` }
+ const credential = readHookCredential(env.ADAPTER_DATA_DIR)
+ if (!credential) throw new Error('hook credential was not created')
+ return {
+ handlers,
+ base: `http://127.0.0.1:${started.port}`,
+ headers: { 'content-type': 'application/json', 'x-harness-hook-token': credential },
+ }
}
describe('process-owned hook server', () => {
it('runs targeted resolution and rejects a hook without a matching pane engine process', async () => {
const resolveHookAgent = vi.fn(async () => null)
- const { handlers, base } = await start({ resolveHookAgent })
+ const { handlers, base, headers } = await start({ resolveHookAgent })
const response = await fetch(`${base}/api/hook/session-start`, {
method: 'POST',
- headers: { 'content-type': 'application/json' },
+ headers,
body: JSON.stringify({
engine: 'codex',
tmuxPane: '%41',
@@ -37,31 +45,38 @@ describe('process-owned hook server', () => {
})
expect(await response.json()).toEqual({ ignored: true, reason: 'no_matching_engine_process' })
- expect(resolveHookAgent).toHaveBeenCalledWith({ engine: 'codex', tmuxPane: '%41' })
+ expect(resolveHookAgent).toHaveBeenCalledWith({
+ engine: 'codex', tmuxPane: '%41', runtimeHints: [{ backend: 'tmux', paneId: '%41' }], callerPid: undefined,
+ })
expect(handlers.onRegistered).not.toHaveBeenCalled()
})
- it('rejects hooks outside tmux before attempting process resolution', async () => {
+ it('rejects hooks outside configured terminal contexts before attempting process resolution', async () => {
const resolveHookAgent = vi.fn(async () => null)
- const { handlers, base } = await start({ resolveHookAgent })
+ const { handlers, base, headers } = await start({ resolveHookAgent })
const response = await fetch(`${base}/api/hook/session-start`, {
method: 'POST',
- headers: { 'content-type': 'application/json' },
+ headers,
body: JSON.stringify({ engine: 'claude', sessionId: 'session-1', cwd: '/work/demo' }),
})
- expect(await response.json()).toEqual({ ignored: true, reason: 'not_in_tmux' })
+ expect(await response.json()).toEqual({ ignored: true, reason: 'not_in_terminal' })
expect(resolveHookAgent).not.toHaveBeenCalled()
expect(handlers.onRegistered).not.toHaveBeenCalled()
})
it('treats SessionEnd as a reconciliation hint and exposes no launcher websocket endpoint', async () => {
const onSessionEnd = vi.fn()
- const { base } = await start({ onSessionEnd })
+ const resolveHookAgent = vi.fn(async () => ({
+ engine: 'claude', sessionId: 'session-1', agentId: 'agent-1',
+ } as never))
+ const { base, headers } = await start({ onSessionEnd, resolveHookAgent })
const ended = await fetch(`${base}/api/hook/session-end`, {
method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ sessionId: 'session-1', reason: 'clear' }),
+ headers,
+ body: JSON.stringify({
+ engine: 'claude', sessionId: 'session-1', reason: 'clear', tmuxPane: '%1', callerPid: 123,
+ }),
})
expect(await ended.json()).toEqual({ ok: true })
expect(onSessionEnd).toHaveBeenCalledWith('session-1', 'clear')
@@ -69,4 +84,57 @@ describe('process-owned hook server', () => {
const legacy = await fetch(`${base}/api/machine-ws`)
expect(legacy.status).toBe(404)
})
+
+ it('rejects every unauthenticated mutating hook request', async () => {
+ const { base, handlers } = await start()
+ const response = await fetch(`${base}/api/hook/session-end`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ sessionId: 'session-1' }),
+ })
+ expect(response.status).toBe(401)
+ expect(await response.json()).toEqual({ error: 'UNAUTHORIZED' })
+ expect(handlers.onSessionEnd).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ [{ engine: 'claude', sessionId: 'session-1', tmuxPane: '%1', unknown: true }],
+ [{ engine: 'claude', sessionId: 'session-1', runtimeHints: [{ backend: 'tmux', paneId: '%1', extra: true }] }],
+ [{ engine: 'claude', sessionId: 'session-1', tmuxPane: '%1', source: { forged: true } }],
+ [{ engine: 'claude', sessionId: 'session-1', tmuxPane: '%1', input: 'x'.repeat(128 * 1024 + 1) }],
+ [null],
+ ])('rejects malformed or unknown hook fields before process resolution', async (body) => {
+ const resolveHookAgent = vi.fn(async () => null)
+ const { base, headers } = await start({ resolveHookAgent })
+ const response = await fetch(`${base}/api/hook/session-start`, {
+ method: 'POST', headers, body: JSON.stringify(body),
+ })
+ expect(response.status).toBe(400)
+ expect(await response.json()).toEqual({ error: 'invalid hook body' })
+ expect(resolveHookAgent).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ['/api/hook/session-end', { reason: 'clear' }, 'onSessionEnd'],
+ ['/api/hook/turn-start', {}, 'onTurnStart'],
+ ['/api/hook/tool-start', { toolUseId: 'tool-1', toolName: 'Task' }, 'onToolStart'],
+ ['/api/hook/turn-stop', { status: 'error' }, 'onTurnStop'],
+ ] as const)('rejects a forged bound-session mutation on %s', async (path, extra, handlerName) => {
+ const handler = vi.fn()
+ const resolveHookAgent = vi.fn(async () => ({
+ engine: 'claude', sessionId: 'real-session', agentId: 'agent-1',
+ } as never))
+ const { base, headers } = await start({ [handlerName]: handler, resolveHookAgent })
+ const response = await fetch(`${base}${path}`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({
+ engine: 'claude', sessionId: 'forged-session', tmuxPane: '%1', callerPid: 123, ...extra,
+ }),
+ })
+
+ expect(response.status).toBe(403)
+ expect(await response.json()).toEqual({ error: 'UNBOUND_HOOK' })
+ expect(handler).not.toHaveBeenCalled()
+ })
})
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index c5f411d14..1c09ffefd 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -16,6 +16,9 @@ import { LOCAL_WEB_HTML } from './webui.js'
import { sid } from './lib/log.js'
import { VERSION } from './version.js'
import { env } from './config/env.js'
+import { hookCredentialMatches, loadOrCreateHookCredential } from './lib/hookAuth.js'
+import type { HookTerminalHint } from './lib/terminalTypes.js'
+import { ENGINES, type AgentEngine } from './engines/types.js'
export interface PairOutcome {
status: number
@@ -29,7 +32,9 @@ export interface HookServerHandlers {
/** Ensure a matching process-owned agent exists before a hook binds its mutable engine session. */
resolveHookAgent?: (session: {
engine: RegisteredSession['engine']
- tmuxPane: string
+ tmuxPane?: string
+ runtimeHints: HookTerminalHint[]
+ callerPid?: number
}) => Promise<RegisteredSession | null>
/** A turn is now running (Command Code's PreToolUse — its only live turn-open signal). Idempotent:
* it fires once per tool call, and every call after the first in a turn must be a no-op. */
@@ -63,16 +68,134 @@ export interface HookServerHandlers {
onStop?: () => void
}
+const MAX_HOOK_BODY_BYTES = 256 * 1024
+const HOOK_BODY_FIELDS = new Set([
+ 'engine', 'launcherId', 'sessionId', 'transcriptPath', 'cwd', 'source', 'tmuxPane', 'title', 'model',
+ 'cliVersion', 'runtimeHints', 'callerPid', 'hookEvent', 'pluginVersion', 'reason', 'status', 'toolUseId',
+ 'toolName', 'input',
+])
+
+function optionalBoundedString(value: unknown, max: number): boolean {
+ return value === undefined || value === null || (typeof value === 'string'
+ && value.length <= max && !/[\u0000-\u001f\u007f]/.test(value))
+}
+
+function optionalBoundedJson(value: unknown, max: number): boolean {
+ if (value === undefined) return true
+ try { return Buffer.byteLength(JSON.stringify(value)) <= max } catch { return false }
+}
+
+function validHookBody(value: unknown): value is BoundHookBody {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false
+ const body = value as Record<string, unknown>
+ if (Object.keys(body).some((field) => !HOOK_BODY_FIELDS.has(field))) return false
+ if (body.engine !== undefined && (typeof body.engine !== 'string' || !ENGINES.includes(body.engine as AgentEngine))) return false
+ if (!optionalBoundedString(body.launcherId, 200)
+ || !optionalBoundedString(body.sessionId, 200)
+ || !optionalBoundedString(body.transcriptPath, 4_096)
+ || !optionalBoundedString(body.cwd, 4_096)
+ || !optionalBoundedString(body.source, 1_000)
+ || !optionalBoundedString(body.tmuxPane, 32)
+ || !optionalBoundedString(body.title, 1_000)
+ || !optionalBoundedString(body.model, 200)
+ || !optionalBoundedString(body.cliVersion, 200)
+ || !optionalBoundedString(body.hookEvent, 100)
+ || !optionalBoundedString(body.pluginVersion, 100)
+ || !optionalBoundedString(body.reason, 500)
+ || !optionalBoundedString(body.status, 100)
+ || !optionalBoundedString(body.toolUseId, 200)
+ || !optionalBoundedString(body.toolName, 200)
+ || !optionalBoundedJson(body.input, 128 * 1024)) return false
+ if (body.callerPid !== undefined
+ && (!Number.isSafeInteger(body.callerPid) || (body.callerPid as number) <= 0)) return false
+ if (body.runtimeHints !== undefined) {
+ if (!Array.isArray(body.runtimeHints) || body.runtimeHints.length > 4) return false
+ for (const value of body.runtimeHints) {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false
+ const hint = value as Record<string, unknown>
+ if (hint.backend === 'tmux') {
+ if (Object.keys(hint).some((field) => field !== 'backend' && field !== 'paneId')
+ || typeof hint.paneId !== 'string' || !/^%\d+$/.test(hint.paneId)) return false
+ } else if (hint.backend === 'herdr') {
+ if (Object.keys(hint).some((field) => !['backend', 'paneId', 'sessionName', 'socketPath'].includes(field))
+ || !optionalBoundedString(hint.paneId, 200) || !hint.paneId
+ || !optionalBoundedString(hint.sessionName, 64)
+ || !optionalBoundedString(hint.socketPath, 4_096)) return false
+ } else return false
+ }
+ }
+ return true
+}
+
function readBody(req: http.IncomingMessage): Promise<string> {
return new Promise((resolve) => {
let data = ''
+ let bytes = 0
+ let oversized = false
req.setEncoding('utf8')
- req.on('data', (c) => (data += c))
- req.on('end', () => resolve(data))
- req.on('error', () => resolve(data))
+ req.on('data', (chunk: string) => {
+ bytes += Buffer.byteLength(chunk)
+ if (bytes > MAX_HOOK_BODY_BYTES) { oversized = true; data = ''; return }
+ data += chunk
+ })
+ req.on('end', () => resolve(oversized ? '' : data))
+ req.on('error', () => resolve(''))
})
}
+function normalizedRuntimeHints(body: RegisterInput): HookTerminalHint[] {
+ const hints: HookTerminalHint[] = []
+ if (Array.isArray(body.runtimeHints) && body.runtimeHints.length <= 4) {
+ for (const hint of body.runtimeHints) {
+ if (hint?.backend === 'tmux' && /^%\d+$/.test(hint.paneId)) hints.push({ backend: 'tmux', paneId: hint.paneId })
+ if (hint?.backend === 'herdr'
+ && typeof hint.paneId === 'string' && hint.paneId.length <= 200
+ && (hint.sessionName === undefined || (typeof hint.sessionName === 'string' && hint.sessionName.length <= 64))
+ && (hint.socketPath === undefined || (typeof hint.socketPath === 'string' && hint.socketPath.length <= 4_096))) {
+ hints.push({
+ backend: 'herdr', paneId: hint.paneId,
+ ...(hint.sessionName ? { sessionName: hint.sessionName } : {}),
+ ...(hint.socketPath ? { socketPath: hint.socketPath } : {}),
+ })
+ }
+ }
+ }
+ if (body.tmuxPane && /^%\d+$/.test(body.tmuxPane)
+ && !hints.some((hint) => hint.backend === 'tmux' && hint.paneId === body.tmuxPane)) {
+ hints.push({ backend: 'tmux', paneId: body.tmuxPane })
+ }
+ return hints
+}
+
+type BoundHookBody = RegisterInput & {
+ sessionId?: string
+ reason?: string
+ status?: string
+ toolUseId?: string
+ toolName?: string
+ input?: unknown
+}
+
+async function verifiedBoundMutation(
+ body: BoundHookBody,
+ handlers: HookServerHandlers,
+): Promise<RegisteredSession | null> {
+ if (!body.sessionId || !body.engine) return null
+ const runtimeHints = normalizedRuntimeHints(body)
+ if (!runtimeHints.length) return null
+ const processAgent = handlers.resolveHookAgent
+ ? await handlers.resolveHookAgent({
+ engine: body.engine,
+ tmuxPane: body.tmuxPane,
+ runtimeHints,
+ callerPid: Number.isSafeInteger(body.callerPid) && body.callerPid! > 0 ? body.callerPid : undefined,
+ })
+ : body.tmuxPane ? registry.byPaneEngine(body.tmuxPane, body.engine) ?? null : null
+ return processAgent?.engine === body.engine && processAgent.sessionId === body.sessionId
+ ? processAgent
+ : null
+}
+
/**
* Bind the localhost hook server on a FIXED `port` (no OS free-port fallback — a random fallback made
* a leftover daemon un-findable by `lsof :<port>`). Rejects with EADDRINUSE if the port is taken (the
@@ -84,6 +207,18 @@ const HERMES_KIND_TRIES = 6
const HERMES_KIND_WAIT_MS = 120
const TRANSCRIPT_WAIT_TRIES = 20
+function registeredHookProcess(body: RegisterInput, engine: AgentEngine): RegisteredSession | undefined {
+ if (body.processIdentity) {
+ const processAgent = registry.byProcess(engine, body.processIdentity)
+ if (processAgent) return processAgent
+ }
+ for (const runtime of body.runtimes ?? []) {
+ const processAgent = registry.byRuntimeEngine(runtime, engine)
+ if (processAgent) return processAgent
+ }
+ return body.tmuxPane ? registry.byPaneEngine(body.tmuxPane, engine) : undefined
+}
+
/**
* Register once the announced transcript exists.
*
@@ -95,7 +230,7 @@ async function awaitTranscript(body: RegisterInput, handlers: HookServerHandlers
for (let i = 0; i < TRANSCRIPT_WAIT_TRIES; i++) {
await new Promise((resolve) => { const t = setTimeout(resolve, TRANSCRIPT_WAIT_MS); t.unref?.() })
const engine = body.engine ?? 'claude'
- if (!body.tmuxPane || !registry.byPaneEngine(body.tmuxPane, engine)) return
+ if (!registeredHookProcess(body, engine)) return
if (isRecentlyDeleted(body.sessionId)) return
if (!body.transcriptPath || !existsSync(body.transcriptPath)) continue
const result = registry.register(body)
@@ -117,7 +252,7 @@ async function awaitHermesKind(body: RegisterInput, handlers: HookServerHandlers
const dbPath = join(env.HERMES_HOME, 'state.db')
for (let i = 0; i < HERMES_KIND_TRIES; i++) {
if (i > 0) await new Promise((resolve) => { const t = setTimeout(resolve, HERMES_KIND_WAIT_MS); t.unref?.() })
- if (!body.tmuxPane || !registry.byPaneEngine(body.tmuxPane, 'hermes')) return
+ if (!registeredHookProcess(body, 'hermes')) return
if (isRecentlyDeleted(body.sessionId)) return
const source = await hermesSessionSource(dbPath, body.sessionId ?? '')
if (source === null) continue
@@ -137,6 +272,7 @@ export function startHookServer(
port: number,
handlers: HookServerHandlers,
): Promise<{ server: http.Server; port: number }> {
+ const hookCredential = loadOrCreateHookCredential(env.ADAPTER_DATA_DIR)
const server = http.createServer((req, res) => {
void (async () => {
const url = (req.url ?? '').split('?')[0]
@@ -149,6 +285,7 @@ export function startHookServer(
// (and the CLI, which sends it too) can trigger actions. A local process could still call it —
// same trust level as the CLI, which is acceptable on loopback.
const localOk = req.headers['x-adapter-local'] === '1'
+ const hookOk = hookCredentialMatches(hookCredential, req.headers['x-harness-hook-token'])
if (req.method === 'GET' && url === '/api/health') {
json(200, { ok: true, version: VERSION }); return
@@ -172,8 +309,13 @@ export function startHookServer(
// SessionStart AND UserPromptSubmit both POST here (the catch hook re-registers so a session
// whose SessionStart the adapter missed still shows up on its first prompt).
if (req.method === 'POST' && url === '/api/hook/session-start') {
+ if (!hookOk) { json(401, { error: 'UNAUTHORIZED' }); return }
let body: RegisterInput
- try { body = JSON.parse(await readBody(req)) as RegisterInput } catch { json(400, { error: 'bad json' }); return }
+ try {
+ const parsed = JSON.parse(await readBody(req)) as unknown
+ if (!validHookBody(parsed)) { json(400, { error: 'invalid hook body' }); return }
+ body = parsed
+ } catch { json(400, { error: 'bad json' }); return }
// Every rejection below says WHY, out loud. They used to be silent, and a hook that arrives and
// is dropped looks exactly like a hook that never fired — which is precisely the confusion behind
// "the agent is running in my terminal but the list does not show it".
@@ -181,7 +323,8 @@ export function startHookServer(
console.log(`[hooks] ${sid(body.sessionId ?? '?')} ${body.hookEvent ?? 'session-start'} ignored · ${reason}`)
json(200, { ignored: true, reason })
}
- if (!body.tmuxPane) { ignore('not_in_tmux'); return }
+ const runtimeHints = normalizedRuntimeHints(body)
+ if (!runtimeHints.length) { ignore('not_in_terminal'); return }
// A plugin/extension is loaded ONCE per engine process, so a pane opened before an update keeps
// running the old copy — silently, and for hours. Measured on amp: a pane started at 11:49 was
// still writing transcripts with no tool calls long after the fix reached disk. The engines that
@@ -195,11 +338,18 @@ export function startHookServer(
}
const engine = body.engine ?? 'claude'
const processAgent = handlers.resolveHookAgent
- ? await handlers.resolveHookAgent({ engine, tmuxPane: body.tmuxPane })
- : registry.byPaneEngine(body.tmuxPane, engine) ?? null
+ ? await handlers.resolveHookAgent({
+ engine,
+ tmuxPane: body.tmuxPane,
+ runtimeHints,
+ callerPid: Number.isSafeInteger(body.callerPid) && body.callerPid! > 0 ? body.callerPid : undefined,
+ })
+ : body.tmuxPane ? registry.byPaneEngine(body.tmuxPane, engine) ?? null : null
if (!processAgent || processAgent.engine !== engine) { ignore('no_matching_engine_process'); return }
// The process scanner is authoritative. Never accept a hook's legacy launcher id or a stale PID.
body.processIdentity = processAgent.processIdentity ?? undefined
+ body.runtimes = processAgent.runtimes
+ body.primaryRuntimeKey = processAgent.primaryRuntimeKey
// Deleting an agent no longer kills its pane, so the engine lives on for a moment and its catch
// hook still fires — and the exact process may remain alive during SIGTERM grace. Without
// this the tile the user just deleted re-registers itself and comes back.
@@ -241,8 +391,14 @@ export function startHookServer(
}
if (req.method === 'POST' && url === '/api/hook/session-end') {
- let body: { sessionId?: string; reason?: string }
- try { body = JSON.parse(await readBody(req)) as { sessionId?: string; reason?: string } } catch { json(400, { error: 'bad json' }); return }
+ if (!hookOk) { json(401, { error: 'UNAUTHORIZED' }); return }
+ let body: BoundHookBody
+ try {
+ const parsed = JSON.parse(await readBody(req)) as unknown
+ if (!validHookBody(parsed)) { json(400, { error: 'invalid hook body' }); return }
+ body = parsed
+ } catch { json(400, { error: 'bad json' }); return }
+ if (!await verifiedBoundMutation(body, handlers)) { json(403, { error: 'UNBOUND_HOOK' }); return }
if (body.sessionId) {
console.log(`[hooks] ${sid(body.sessionId)} session-end${body.reason ? ` · reason=${body.reason}` : ''}`)
handlers.onSessionEnd(body.sessionId, body.reason)
@@ -252,8 +408,14 @@ export function startHookServer(
}
if (req.method === 'POST' && url === '/api/hook/tool-start') {
- let body: { sessionId?: string; toolUseId?: string; toolName?: string; input?: unknown }
- try { body = JSON.parse(await readBody(req)) as typeof body } catch { json(400, { error: 'bad json' }); return }
+ if (!hookOk) { json(401, { error: 'UNAUTHORIZED' }); return }
+ let body: BoundHookBody
+ try {
+ const parsed = JSON.parse(await readBody(req)) as unknown
+ if (!validHookBody(parsed)) { json(400, { error: 'invalid hook body' }); return }
+ body = parsed
+ } catch { json(400, { error: 'bad json' }); return }
+ if (!await verifiedBoundMutation(body, handlers)) { json(403, { error: 'UNBOUND_HOOK' }); return }
if (body.sessionId && body.toolUseId && body.toolName) {
console.log(`[hooks] ${sid(body.sessionId)} tool-start · tool=${body.toolName}`)
handlers.onToolStart?.({
@@ -268,16 +430,28 @@ export function startHookServer(
}
if (req.method === 'POST' && url === '/api/hook/turn-start') {
- let body: { sessionId?: string }
- try { body = JSON.parse(await readBody(req)) as typeof body } catch { json(400, { error: 'bad json' }); return }
+ if (!hookOk) { json(401, { error: 'UNAUTHORIZED' }); return }
+ let body: BoundHookBody
+ try {
+ const parsed = JSON.parse(await readBody(req)) as unknown
+ if (!validHookBody(parsed)) { json(400, { error: 'invalid hook body' }); return }
+ body = parsed
+ } catch { json(400, { error: 'bad json' }); return }
+ if (!await verifiedBoundMutation(body, handlers)) { json(403, { error: 'UNBOUND_HOOK' }); return }
if (body.sessionId) handlers.onTurnStart?.({ sessionId: body.sessionId })
json(200, { ok: true })
return
}
if (req.method === 'POST' && url === '/api/hook/turn-stop') {
- let body: { sessionId?: string; status?: string; transcriptPath?: string }
- try { body = JSON.parse(await readBody(req)) as typeof body } catch { json(400, { error: 'bad json' }); return }
+ if (!hookOk) { json(401, { error: 'UNAUTHORIZED' }); return }
+ let body: BoundHookBody
+ try {
+ const parsed = JSON.parse(await readBody(req)) as unknown
+ if (!validHookBody(parsed)) { json(400, { error: 'invalid hook body' }); return }
+ body = parsed
+ } catch { json(400, { error: 'bad json' }); return }
+ if (!await verifiedBoundMutation(body, handlers)) { json(403, { error: 'UNBOUND_HOOK' }); return }
if (body.sessionId) {
console.log(`[hooks] ${sid(body.sessionId)} turn-stop${body.status ? ` · status=${body.status}` : ''}`)
handlers.onTurnStop?.({
diff --git a/cli/src/lib/__fixtures__/herdr/pty-capture.mjs b/cli/src/lib/__fixtures__/herdr/pty-capture.mjs
new file mode 100644
index 000000000..6bb308e1b
--- /dev/null
+++ b/cli/src/lib/__fixtures__/herdr/pty-capture.mjs
@@ -0,0 +1,31 @@
+import { writeFileSync, writeSync } from 'node:fs'
+
+const [outputPath, readyPath] = process.argv.slice(2)
+if (!outputPath || !readyPath || !process.stdin.isTTY || typeof process.stdin.setRawMode !== 'function') {
+ process.exit(2)
+}
+
+process.stdin.setRawMode(true)
+process.stdin.resume()
+writeSync(1, '\u001b[?2004h')
+writeFileSync(readyPath, 'ready', { mode: 0o600 })
+
+const chunks = []
+const deadline = setTimeout(() => process.exit(3), 10_000)
+
+process.stdin.on('data', (chunk) => {
+ chunks.push(Buffer.from(chunk))
+ const bytes = Buffer.concat(chunks)
+ const bracketedEnd = bytes.indexOf(Buffer.from('\u001b[201~'))
+ if (bracketedEnd < 0 || bytes.indexOf(0x0d, bracketedEnd + 6) < 0) return
+ clearTimeout(deadline)
+ writeFileSync(outputPath, JSON.stringify({
+ base64: bytes.toString('base64'),
+ byteLength: bytes.byteLength,
+ bracketedStarts: bytes.toString('binary').split('\u001b[200~').length - 1,
+ bracketedEnds: bytes.toString('binary').split('\u001b[201~').length - 1,
+ carriageReturnsAfterPaste: [...bytes.subarray(bracketedEnd + 6)].filter((byte) => byte === 0x0d).length,
+ }), { mode: 0o600 })
+ writeSync(1, '\u001b[?2004l')
+ process.exit(0)
+})
diff --git a/cli/src/lib/askQuestion.ts b/cli/src/lib/askQuestion.ts
index f939654f3..18eb62656 100644
--- a/cli/src/lib/askQuestion.ts
+++ b/cli/src/lib/askQuestion.ts
@@ -1,6 +1,6 @@
/**
* AskUserQuestion on a REMOTE machine — mirror the question to the device, then answer it by driving the
- * interactive CLI's own dialog in the tmux pane.
+ * interactive CLI's own terminal dialog.
*
* A runtime that speaks stream-json gets this for free: a `question_request` event carries
* the questions out and a `question_response` control-frame carries the answer back. A remote machine has no
@@ -536,9 +536,11 @@ export function pickAnswer(answers: Record<string, string>, question: string, us
export interface AskQuestionDeps {
getSession: (sessionId: string) => RegisteredSession | undefined
- capture: (pane: string, historyLines?: number) => Promise<string | null>
- sendText: (pane: string, text: string) => Promise<boolean>
- sendKey: (pane: string, key: string) => Promise<boolean>
+ capture: (terminalTarget: string, historyLines?: number) => Promise<string | null>
+ sendText: (terminalTarget: string, text: string) => Promise<boolean>
+ sendKey: (terminalTarget: string, key: string) => Promise<boolean>
+ /** Pins one backend locator for the whole multi-step dialog drive. */
+ acquireControl?: (sessionId: string) => (() => void) | null
/** Injected for tests. */
wait?: (ms: number) => Promise<void>
}
@@ -552,7 +554,7 @@ export interface QuestionAnswerPayload {
/**
* Owns the OUT side's pending map (requestId → session) and the IN side's pane driving. One answer at a
- * time per pane: a second `question_response` for a dialog already being driven is dropped, not queued.
+ * time per agent: a second `question_response` for a dialog already being driven is dropped, not queued.
*/
export class AskQuestionController {
private pending = new Map<string, string>() // requestId → sessionId
@@ -575,25 +577,29 @@ export class AskQuestionController {
console.warn(`[question] ignoring answer with no session/answers (req=${requestId})`)
return false
}
- const pane = this.deps.getSession(sessionId)?.tmuxPane
- if (!pane) {
- console.warn(`[question] no tmux pane for ${sessionId.slice(0, 8)} — answer dropped`)
+ const session = this.deps.getSession(sessionId)
+ const terminalTarget = session?.agentId || session?.sessionId
+ if (!terminalTarget) {
+ console.warn(`[question] no terminal target for ${sessionId.slice(0, 8)} — answer dropped`)
return false
}
if (this.driving.has(sessionId)) return false
+ const release = this.deps.acquireControl?.(terminalTarget)
+ if (this.deps.acquireControl && !release) return false
this.driving.add(sessionId)
try {
- const ok = await this.drive(pane, answers, this.deps.getSession(sessionId)?.engine ?? 'claude')
+ const ok = await this.drive(terminalTarget, answers, this.deps.getSession(sessionId)?.engine ?? 'claude')
this.pending.delete(requestId)
console.log(`[question] ${sessionId.slice(0, 8)} answered from device · ${ok ? 'submitted' : 'FAILED'}`)
return ok
} finally {
this.driving.delete(sessionId)
+ release?.()
}
}
/** Key the answers into the pane's dialog, question by question, ending on the review screen. */
- private async drive(pane: string, answers: Record<string, string>, engine: AgentEngine): Promise<boolean> {
+ private async drive(terminalTarget: string, answers: Record<string, string>, engine: AgentEngine): Promise<boolean> {
const wait = this.deps.wait ?? sleep
const used = new Set<string>()
let lastQuestion = ''
@@ -601,15 +607,14 @@ export class AskQuestionController {
let answered = 0
for (let step = 0; step < MAX_STEPS; step++) {
- const capture = await this.deps.capture(pane, CAPTURE_LINES)
+ const capture = await this.deps.capture(terminalTarget, CAPTURE_LINES)
const view = parseEngineQuestionPane(engine, capture ?? '')
if (!view) {
// Nothing on screen: either the dialog was never open, or the last keystroke submitted it.
return answered > 0
}
if (view.kind === 'review') {
- await this.deps.sendKey(pane, view.submitRow)
- return true
+ return this.deps.sendKey(terminalTarget, view.submitRow)
}
// The same question still showing after we acted on it: give the TUI one more beat to repaint,
// then treat it as stuck rather than hammering the pane with more keystrokes. Never consume a
@@ -636,12 +641,13 @@ export class AskQuestionController {
for (const label of labels) {
const row = matchRow(view.rows, label)
if (!row || row.checked) continue
- await this.deps.sendKey(pane, row.number)
+ if (!await this.deps.sendKey(terminalTarget, row.number)) return false
await wait(TEXT_MS)
toggled++
}
- if (!toggled && view.typeRow) await this.typeFreeText(pane, view.typeRow, picked.value, wait)
- await this.deps.sendKey(pane, multiSubmitKey(engine)) // advance to the next question / review
+ if (!toggled && view.typeRow
+ && !await this.typeFreeText(terminalTarget, view.typeRow, picked.value, wait)) return false
+ if (!await this.deps.sendKey(terminalTarget, multiSubmitKey(engine))) return false // advance to the next question / review
await wait(STEP_MS)
continue
}
@@ -651,14 +657,14 @@ export class AskQuestionController {
// One digit selects AND submits — except on Amp, whose rows are unnumbered and reached by
// walking the list, so this is a short sequence rather than a single key.
for (const key of rowKeys(engine, row)) {
- await this.deps.sendKey(pane, key)
+ if (!await this.deps.sendKey(terminalTarget, key)) return false
await wait(TEXT_MS)
}
await wait(STEP_MS)
continue
}
if (!view.typeRow) { console.warn(`[question] no option matched "${picked.value.slice(0, 40)}" and no free-text row`); return false }
- await this.typeFreeText(pane, view.typeRow, picked.value, wait)
+ if (!await this.typeFreeText(terminalTarget, view.typeRow, picked.value, wait)) return false
await wait(STEP_MS)
}
return false
@@ -670,20 +676,20 @@ export class AskQuestionController {
}
/** Free-text answer (a voice answer is always free text): open the "Type something." row, type, Enter. */
- private async typeFreeText(pane: string, typeRow: QuestionRow, text: string, wait: (ms: number) => Promise<void>): Promise<void> {
- await this.deps.sendKey(pane, typeRow.number)
+ private async typeFreeText(terminalTarget: string, typeRow: QuestionRow, text: string, wait: (ms: number) => Promise<void>): Promise<boolean> {
+ if (!await this.deps.sendKey(terminalTarget, typeRow.number)) return false
await wait(TEXT_MS)
- await this.deps.sendText(pane, text)
+ if (!await this.deps.sendText(terminalTarget, text)) return false
await wait(TEXT_MS)
- await this.deps.sendKey(pane, 'Enter')
+ return this.deps.sendKey(terminalTarget, 'Enter')
}
}
-// ── watching a pane for an open question ─────────────────────────────────────────────────────────
+// ── watching a terminal for an open question ─────────────────────────────────────────────────────
export interface QuestionWatcherDeps {
getSession: (sessionId: string) => RegisteredSession | undefined
- capture: (pane: string, historyLines?: number) => Promise<string | null>
+ capture: (terminalTarget: string, historyLines?: number) => Promise<string | null>
/** Skip the capture entirely when no device is listening — nothing would consume the question. */
hasDevice: () => boolean
/** A dialog is open on screen. Fires ONCE per distinct question (until it changes or closes). */
@@ -728,7 +734,7 @@ export class QuestionWatcher {
const session = this.deps.getSession(sessionId)
// Only the engines that actually paint a question dialog: Claude and Command Code share one shape,
// devin has its own (parseDevinQuestionPane). Polling any other pane would be pure waste.
- if (!session?.tmuxPane || !QUESTION_ENGINES.has(session.engine)) return
+ if (!session || session.active === false || !(session.agentId || session.sessionId) || !QUESTION_ENGINES.has(session.engine)) return
this.timers.set(sessionId, setInterval(() => { void this.tick(sessionId) }, POLL_MS))
}
@@ -750,8 +756,9 @@ export class QuestionWatcher {
}
private async tick(sessionId: string): Promise<void> {
- const pane = this.deps.getSession(sessionId)?.tmuxPane
- if (!pane) { this.stop(sessionId); return }
+ const session = this.deps.getSession(sessionId)
+ const terminalTarget = session?.agentId || session?.sessionId
+ if (!terminalTarget) { this.stop(sessionId); return }
// Both of these silently do nothing, which is how a live dialog can sit on the terminal with no trace
// in the log. Say it once per transition rather than every 1.5s tick.
const blocked = !this.deps.hasDevice() ? 'no device' : this.deps.isDriving?.(sessionId) ? 'driving an answer' : ''
@@ -761,7 +768,7 @@ export class QuestionWatcher {
}
if (blocked) return
const engine = this.deps.getSession(sessionId)?.engine ?? 'claude'
- const view = parseEngineQuestionPane(engine, await this.deps.capture(pane, CAPTURE_LINES) ?? '')
+ const view = parseEngineQuestionPane(engine, await this.deps.capture(terminalTarget, CAPTURE_LINES) ?? '')
if (!view || view.kind !== 'question' || !view.question || view.rows.length === 0) {
this.last.delete(sessionId) // dialog closed (or moved to review) → the next one announces fresh
return
diff --git a/cli/src/lib/commandcodeModel.spec.ts b/cli/src/lib/commandcodeModel.spec.ts
index e7d450d3d..23c2d0a11 100644
--- a/cli/src/lib/commandcodeModel.spec.ts
+++ b/cli/src/lib/commandcodeModel.spec.ts
@@ -20,6 +20,8 @@ async function loadRuntimeProfile() {
}
const session = (): RegisteredSession => ({
+ schemaVersion: 2,
+ active: true,
sessionId: 'session:1',
engine: 'commandcode',
launcherId: 'h1',
@@ -29,6 +31,8 @@ const session = (): RegisteredSession => ({
projectDir: 'tmp',
cwd: '/tmp',
tmuxPane: '%1',
+ runtimes: [{ backend: 'tmux', paneId: '%1' }],
+ primaryRuntimeKey: 'tmux\u0000%1',
source: null,
title: null,
model: null,
diff --git a/cli/src/lib/deleteAgentFallback.spec.ts b/cli/src/lib/deleteAgentFallback.spec.ts
index 98e565dbc..c398566ff 100644
--- a/cli/src/lib/deleteAgentFallback.spec.ts
+++ b/cli/src/lib/deleteAgentFallback.spec.ts
@@ -113,6 +113,35 @@ describe('delete-agent process termination', () => {
await expect(terminateDeletedAgent(SESSION, d)).resolves.toBe('failed')
expect(d.logs.join('\n')).toContain('could not validate')
})
+
+ it('does not SIGKILL when identity validation becomes unknown after SIGTERM', async () => {
+ let checks = 0
+ const d = deps({
+ checkRuntime: async () => {
+ checks += 1
+ return checks > 13
+ ? { state: 'unknown', reason: 'process table timed out' }
+ : runtime(true)
+ },
+ })
+ await expect(terminateDeletedAgent(SESSION, d)).resolves.toBe('failed')
+ expect(d.kills).toEqual([[4242, 'SIGTERM']])
+ expect(d.logs.join('\n')).toContain('before SIGKILL')
+ })
+
+ it('does not SIGKILL a PID whose process identity changed after SIGTERM', async () => {
+ let checks = 0
+ const d = deps({
+ checkRuntime: async () => {
+ checks += 1
+ return checks > 13
+ ? { state: 'gone', reason: 'saved PID was reused' }
+ : runtime(true)
+ },
+ })
+ await expect(terminateDeletedAgent(SESSION, d)).resolves.toBe('terminated')
+ expect(d.kills).toEqual([[4242, 'SIGTERM']])
+ })
})
describe('delete-agent process termination timing', () => {
diff --git a/cli/src/lib/deleteAgentFallback.ts b/cli/src/lib/deleteAgentFallback.ts
index 1bef4c460..0b3936c94 100644
--- a/cli/src/lib/deleteAgentFallback.ts
+++ b/cli/src/lib/deleteAgentFallback.ts
@@ -77,9 +77,18 @@ export async function terminateDeletedAgent(
for (let waited = 0; waited < killGraceMs; waited += POLL_MS) {
await deps.sleep(POLL_MS)
- if ((await check()).state === 'gone') return 'terminated'
+ const current = await check()
+ if (current.state === 'gone') return 'terminated'
}
+ // Revalidate at the escalation boundary. A process-table timeout or PID replacement after SIGTERM is
+ // not permission to send SIGKILL to the saved number.
+ const beforeKill = await check()
+ if (beforeKill.state === 'gone') return 'terminated'
+ if (beforeKill.state === 'unknown') {
+ deps.log(`[delete] could not revalidate ${session.engine} before SIGKILL: ${beforeKill.reason}`)
+ return 'failed'
+ }
deps.log(`[delete] ${session.engine} ignored SIGTERM — SIGKILL pid ${pid}`)
if (!signal('SIGKILL')) return (await check()).state === 'gone' ? 'gone' : 'failed'
await deps.sleep(POLL_MS)
diff --git a/cli/src/lib/discoveryScripts.spec.ts b/cli/src/lib/discoveryScripts.spec.ts
index 59020790b..21cfea115 100644
--- a/cli/src/lib/discoveryScripts.spec.ts
+++ b/cli/src/lib/discoveryScripts.spec.ts
@@ -17,7 +17,7 @@ function scratch(): string {
}
describe('generated discovery scripts', () => {
- it('lets the Pi extension post from any tmux pane without launcher metadata', async () => {
+ it('lets the Pi extension post from any terminal context without launcher metadata', async () => {
const piHome = scratch()
vi.resetModules()
process.env.PI_HOME = piHome
@@ -26,11 +26,12 @@ describe('generated discovery scripts', () => {
const src = readFileSync(join(piHome, 'agent', 'extensions', 'launcher-register.ts'), 'utf-8')
expect(src).toContain('process.env.TMUX_PANE')
+ expect(src).toContain('process.env.HERDR_PANE_ID')
expect(src).not.toContain('MACHINE_ID')
expect(src).not.toContain('launcherId')
})
- it('lets the OpenCode plugin post from any tmux pane without launcher metadata', async () => {
+ it('lets the OpenCode plugin post from any terminal context without launcher metadata', async () => {
const pluginDir = scratch()
vi.resetModules()
process.env.OPENCODE_PLUGIN_DIR = pluginDir
@@ -39,8 +40,9 @@ describe('generated discovery scripts', () => {
const src = readFileSync(join(pluginDir, 'launcher-register.js'), 'utf-8')
expect(src).toContain('process.env.TMUX_PANE')
+ expect(src).toContain('process.env.HERDR_PANE_ID')
expect(src).not.toContain('MACHINE_ID')
expect(src).not.toContain('launcherId')
- expect(src).toMatch(/if \(!pane/)
+ expect(src).toContain('if ((!pane && !herdrPane)')
})
})
diff --git a/cli/src/lib/engineBin.spec.ts b/cli/src/lib/engineBin.spec.ts
index 20325aee2..f5a56eb8a 100644
--- a/cli/src/lib/engineBin.spec.ts
+++ b/cli/src/lib/engineBin.spec.ts
@@ -8,6 +8,7 @@ import {
cursorRuntimeBin,
ENGINE_CLI_COMMANDS,
ENGINES,
+ installedEngineBin,
} from './engineBin.js'
const originalPath = process.env.PATH
@@ -59,10 +60,12 @@ describe('canonical engine CLI commands', () => {
expect(agentAliasOwner([snapshot.agentCandidates[0]?.fileKey], snapshot)).toBe('grok')
expect(agentAliasOwner([snapshot.agentCandidates[1]?.fileKey], snapshot)).toBe('cursor')
expect(cursorRuntimeBin(snapshot)).toBe('cursor-agent')
+ expect(installedEngineBin('cursor', snapshot)).toBe(join(cursorBin, 'cursor-agent'))
process.env.PATH = [cursorBin, grokBin].join(delimiter)
snapshot = agentCommandOwnershipSnapshot()
expect(agentAliasOwner([snapshot.agentCandidates[0]?.fileKey], snapshot)).toBe('cursor')
expect(cursorRuntimeBin(snapshot)).toBe('agent')
+ expect(installedEngineBin('cursor', snapshot)).toBe(join(cursorBin, 'agent'))
})
})
diff --git a/cli/src/lib/engineBin.ts b/cli/src/lib/engineBin.ts
index a253d4a73..4ac66b16f 100644
--- a/cli/src/lib/engineBin.ts
+++ b/cli/src/lib/engineBin.ts
@@ -183,6 +183,20 @@ export function cursorRuntimeBin(snapshot = agentCommandOwnershipSnapshot()): st
return null
}
+/** Resolve an installed executable for real-engine verification without trusting a colliding alias. */
+export function installedEngineBin(
+ engine: AgentEngine,
+ snapshot = agentCommandOwnershipSnapshot(),
+): string | null {
+ const command = engine === 'cursor' ? cursorRuntimeBin(snapshot) : engineBin(engine)
+ if (!command) return null
+ const candidates = commandCandidates(command)
+ if (engine === 'cursor' || engine === 'grok') {
+ return candidates.find((candidate) => agentAliasOwner([candidate.fileKey], snapshot) === engine)?.path ?? null
+ }
+ return candidates[0]?.path ?? null
+}
+
/** Existing env override only; process matching must not treat a default basename as ownership proof. */
export function enginePathOverride(engine: AgentEngine): string | undefined {
switch (engine) {
diff --git a/cli/src/lib/herdrApiClient.spec.ts b/cli/src/lib/herdrApiClient.spec.ts
new file mode 100644
index 000000000..355c5a8f3
--- /dev/null
+++ b/cli/src/lib/herdrApiClient.spec.ts
@@ -0,0 +1,224 @@
+import { createServer, type Server } from 'node:net'
+import { chmod, lstat, mkdir, mkdtemp, rm, symlink } from 'node:fs/promises'
+import { homedir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import {
+ HERDR_API_PROTOCOL,
+ HERDR_API_SCHEMA_VERSION,
+ HerdrApiClient,
+ HerdrEndpointError,
+ resolveHerdrEndpoint,
+ type HerdrEndpoint,
+} from './herdrApiClient.js'
+
+const dirs: string[] = []
+const servers: Server[] = []
+
+async function tempDir(): Promise<string> {
+ const dir = await mkdtemp(join(homedir(), '.harness-herdr-api-test-'))
+ dirs.push(dir)
+ await chmod(dir, 0o700)
+ return dir
+}
+
+async function socketServer(
+ handle: (request: Record<string, unknown>, socket: import('node:net').Socket) => void,
+): Promise<{ endpoint: HerdrEndpoint; socketPath: string }> {
+ const dir = await tempDir()
+ const socketPath = join(dir, 'herdr.sock')
+ const server = createServer((socket) => {
+ let input = ''
+ socket.setEncoding('utf8')
+ socket.on('data', (chunk) => {
+ input += chunk
+ const newline = input.indexOf('\n')
+ if (newline < 0) return
+ const request = JSON.parse(input.slice(0, newline)) as Record<string, unknown>
+ handle(request, socket)
+ })
+ })
+ servers.push(server)
+ await new Promise<void>((resolve, reject) => {
+ server.once('error', reject)
+ server.listen(socketPath, resolve)
+ })
+ await chmod(socketPath, 0o600)
+ return {
+ socketPath,
+ endpoint: await resolveHerdrEndpoint({ sessionName: 'test', socketPath }),
+ }
+}
+
+afterEach(async () => {
+ await Promise.all(servers.splice(0).map((server) => new Promise<void>((resolve) => server.close(() => resolve()))))
+ await Promise.all(dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })))
+})
+
+describe('HerdrApiClient', () => {
+ it('uses one bounded NDJSON request and validates the response id', async () => {
+ let observed: Record<string, unknown> | null = null
+ const { endpoint } = await socketServer((request, socket) => {
+ observed = request
+ socket.end(`${JSON.stringify({
+ id: request.id,
+ result: {
+ type: 'pong',
+ version: '0.8.0',
+ protocol: HERDR_API_PROTOCOL,
+ capabilities: { live_handoff: true, detached_server_daemon: true },
+ },
+ })}\n`)
+ })
+
+ const result = await new HerdrApiClient(endpoint).ping()
+
+ expect(result).toEqual({
+ ok: true,
+ result: {
+ type: 'pong',
+ version: '0.8.0',
+ protocol: HERDR_API_PROTOCOL,
+ capabilities: { live_handoff: true, detached_server_daemon: true },
+ },
+ })
+ expect(observed).toMatchObject({ method: 'ping', params: {} })
+ expect(typeof (observed as Record<string, unknown> | null)?.id).toBe('string')
+ })
+
+ it('classifies validation, connect, and pre-write abort failures as not started', async () => {
+ const dir = await tempDir()
+ const missing = join(dir, 'missing.sock')
+ await expect(resolveHerdrEndpoint({ sessionName: 'missing', socketPath: missing }))
+ .rejects.toBeInstanceOf(HerdrEndpointError)
+
+ const { endpoint } = await socketServer((_request, socket) => socket.end())
+ const controller = new AbortController()
+ controller.abort()
+ await expect(new HerdrApiClient(endpoint).request('pane.send_input', {
+ pane_id: 'w1:p1',
+ text: 'secret-prompt',
+ keys: ['Enter'],
+ }, { mutation: 'single_enqueue', signal: controller.signal })).resolves.toMatchObject({
+ ok: false,
+ dispatch: 'not_started',
+ })
+ })
+
+ it('classifies a lost response after write as possibly executed without leaking request text', async () => {
+ const { endpoint } = await socketServer((_request, socket) => socket.destroy())
+ const result = await new HerdrApiClient(endpoint, { timeoutMs: 250 }).request('pane.send_input', {
+ pane_id: 'w1:p1',
+ text: 'unique-secret-prompt',
+ keys: ['Enter'],
+ }, { mutation: 'single_enqueue' })
+
+ expect(result).toMatchObject({ ok: false, dispatch: 'possibly_executed' })
+ expect(JSON.stringify(result)).not.toContain('unique-secret-prompt')
+ expect(JSON.stringify(result)).not.toContain(endpoint.socketPath)
+ })
+
+ it('classifies only proven single-enqueue rejections as rejected', async () => {
+ const { endpoint } = await socketServer((request, socket) => {
+ socket.end(`${JSON.stringify({
+ id: request.id,
+ error: { code: 'pane_send_failed', message: 'queue full' },
+ })}\n`)
+ })
+ const client = new HerdrApiClient(endpoint)
+
+ await expect(client.request('pane.send_input', {
+ pane_id: 'w1:p1', text: 'hello', keys: ['Enter'],
+ }, { mutation: 'single_enqueue' })).resolves.toMatchObject({
+ ok: false,
+ dispatch: 'rejected',
+ code: 'pane_send_failed',
+ })
+ await expect(client.request('pane.send_keys', {
+ pane_id: 'w1:p1', keys: ['Down', 'Enter'],
+ }, { mutation: 'multi_enqueue' })).resolves.toMatchObject({
+ ok: false,
+ dispatch: 'possibly_executed',
+ code: 'pane_send_failed',
+ })
+ })
+
+ it('treats malformed, mismatched, and oversized post-write responses as ambiguous', async () => {
+ const cases = [
+ (request: Record<string, unknown>, socket: import('node:net').Socket) => socket.end('{bad json}\n'),
+ (_request: Record<string, unknown>, socket: import('node:net').Socket) => socket.end('{"id":"wrong","result":{"type":"ok"}}\n'),
+ (request: Record<string, unknown>, socket: import('node:net').Socket) => socket.end(`${JSON.stringify({ id: request.id, result: { type: 'ok', padding: 'x'.repeat(2_000) } })}\n`),
+ ]
+ for (const handle of cases) {
+ const { endpoint } = await socketServer(handle)
+ const result = await new HerdrApiClient(endpoint, { maxResponseBytes: 1_024 }).request(
+ 'pane.send_input',
+ { pane_id: 'w1:p1', text: 'hello', keys: ['Enter'] },
+ { mutation: 'single_enqueue' },
+ )
+ expect(result).toMatchObject({ ok: false, dispatch: 'possibly_executed' })
+ }
+ })
+
+ it('rejects oversized requests before connecting', async () => {
+ let requests = 0
+ const { endpoint } = await socketServer((_request, socket) => { requests++; socket.end() })
+ const result = await new HerdrApiClient(endpoint, { maxRequestBytes: 256 }).request(
+ 'pane.send_input',
+ { pane_id: 'w1:p1', text: 'x'.repeat(512), keys: ['Enter'] },
+ { mutation: 'single_enqueue' },
+ )
+ expect(result).toMatchObject({ ok: false, dispatch: 'not_started' })
+ expect(requests).toBe(0)
+ })
+
+ it('accepts an owner-owned 0775 socket parent under the local account-owner trust model', async () => {
+ const root = await tempDir()
+ const parent = join(root, 'herdr')
+ await mkdir(parent, { mode: 0o775 })
+ await chmod(parent, 0o775)
+ const socketPath = join(parent, 'herdr.sock')
+ const server = createServer()
+ servers.push(server)
+ await new Promise<void>((resolve) => server.listen(socketPath, resolve))
+ await chmod(socketPath, 0o600)
+
+ await expect(resolveHerdrEndpoint({ sessionName: 'shared-group', socketPath })).resolves.toMatchObject({
+ sessionName: 'shared-group', socketPath,
+ })
+ })
+
+ it('rejects symlinked, permissive, and changed endpoint artifacts', async () => {
+ const { endpoint, socketPath } = await socketServer((request, socket) => {
+ socket.end(`${JSON.stringify({ id: request.id, result: { type: 'ok' } })}\n`)
+ })
+ const linkPath = join(await tempDir(), 'linked.sock')
+ await symlink(socketPath, linkPath)
+ await expect(resolveHerdrEndpoint({ sessionName: 'linked', socketPath: linkPath }))
+ .rejects.toBeInstanceOf(HerdrEndpointError)
+
+ await chmod(socketPath, 0o666)
+ await expect(resolveHerdrEndpoint({ sessionName: 'permissive', socketPath }))
+ .rejects.toBeInstanceOf(HerdrEndpointError)
+ await chmod(socketPath, 0o600)
+
+ const parent = join(await tempDir(), 'unsafe')
+ await mkdir(parent, { mode: 0o777 })
+ await chmod(parent, 0o777)
+ const unsafeSocket = join(parent, 'herdr.sock')
+ const unsafeServer = createServer()
+ servers.push(unsafeServer)
+ await new Promise<void>((resolve) => unsafeServer.listen(unsafeSocket, resolve))
+ await chmod(unsafeSocket, 0o600)
+ await expect(resolveHerdrEndpoint({ sessionName: 'unsafe', socketPath: unsafeSocket }))
+ .rejects.toBeInstanceOf(HerdrEndpointError)
+
+ const before = await lstat(socketPath)
+ expect(endpoint.generation).toEqual({ device: before.dev, inode: before.ino })
+ })
+
+ it('pins the generated v0.8 schema and live protocol tuple', () => {
+ expect(HERDR_API_PROTOCOL).toBe(19)
+ expect(HERDR_API_SCHEMA_VERSION).toBe(1)
+ })
+})
diff --git a/cli/src/lib/herdrApiClient.ts b/cli/src/lib/herdrApiClient.ts
new file mode 100644
index 000000000..ab4b2783d
--- /dev/null
+++ b/cli/src/lib/herdrApiClient.ts
@@ -0,0 +1,303 @@
+import { createHash, randomUUID } from 'node:crypto'
+import { lstat, realpath } from 'node:fs/promises'
+import { createConnection, type Socket } from 'node:net'
+import { dirname, isAbsolute, parse, resolve, sep } from 'node:path'
+
+export const HERDR_API_PROTOCOL = 19
+export const HERDR_API_SCHEMA_VERSION = 1
+export const HERDR_API_MAX_REQUEST_BYTES = 1024 * 1024
+export const HERDR_API_MAX_RESPONSE_BYTES = 1024 * 1024
+
+const HERDR_VERSION_RE = /^0\.8\.\d+(?:[-+].*)?$/
+const SESSION_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/
+
+export interface HerdrEndpointGeneration {
+ device: number
+ inode: number
+}
+
+export interface HerdrEndpoint {
+ sessionName: string
+ endpointId: string
+ socketPath: string
+ generation: HerdrEndpointGeneration
+}
+
+export type HerdrMutationKind = 'none' | 'single_enqueue' | 'single_key' | 'multi_enqueue' | 'other'
+
+export type HerdrApiResult<T> =
+ | { ok: true; result: T }
+ | {
+ ok: false
+ dispatch: 'not_started' | 'rejected' | 'possibly_executed'
+ code?: string
+ reason: string
+ }
+
+export interface HerdrPong {
+ type: 'pong'
+ version: string
+ protocol: number
+ capabilities?: {
+ live_handoff: boolean
+ detached_server_daemon: boolean
+ } | null
+}
+
+export interface HerdrApiClientOptions {
+ timeoutMs?: number
+ maxRequestBytes?: number
+ maxResponseBytes?: number
+}
+
+export interface HerdrRequestOptions {
+ mutation?: HerdrMutationKind
+ signal?: AbortSignal
+}
+
+export class HerdrEndpointError extends Error {
+ constructor(public readonly code: string) {
+ super(`Herdr endpoint rejected (${code})`)
+ this.name = 'HerdrEndpointError'
+ }
+}
+
+function mode(value: number): number {
+ return value & 0o7777
+}
+
+function pathComponents(path: string): string[] {
+ const root = parse(path).root
+ const relative = path.slice(root.length)
+ const components = relative.split(sep).filter(Boolean)
+ const paths = [root]
+ for (const component of components) paths.push(resolve(paths.at(-1)!, component))
+ return paths
+}
+
+async function checkedSocket(socketPath: string): Promise<HerdrEndpointGeneration> {
+ if (!isAbsolute(socketPath)) throw new HerdrEndpointError('path_not_absolute')
+ const uid = typeof process.getuid === 'function' ? process.getuid() : null
+ if (uid === null) throw new HerdrEndpointError('uid_unavailable')
+
+ const parent = dirname(socketPath)
+ for (const path of pathComponents(parent)) {
+ let stat
+ try { stat = await lstat(path) } catch { throw new HerdrEndpointError('directory_unavailable') }
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new HerdrEndpointError('unsafe_directory_type')
+ if (stat.uid !== uid && stat.uid !== 0) throw new HerdrEndpointError('unsafe_directory_owner')
+ const permissions = mode(stat.mode)
+ if ((permissions & 0o002) !== 0 || (stat.uid === 0 && (permissions & 0o020) !== 0)) {
+ throw new HerdrEndpointError('unsafe_directory_mode')
+ }
+ }
+
+ let parentStat
+ try { parentStat = await lstat(parent) } catch { throw new HerdrEndpointError('parent_unavailable') }
+ if (parentStat.uid !== uid) throw new HerdrEndpointError('unsafe_parent_owner')
+
+ let socketStat
+ try { socketStat = await lstat(socketPath) } catch { throw new HerdrEndpointError('socket_unavailable') }
+ if (!socketStat.isSocket() || socketStat.isSymbolicLink()) throw new HerdrEndpointError('unsafe_socket_type')
+ if (socketStat.uid !== uid) throw new HerdrEndpointError('unsafe_socket_owner')
+ if (mode(socketStat.mode) !== 0o600) throw new HerdrEndpointError('unsafe_socket_mode')
+
+ let canonical
+ try { canonical = await realpath(socketPath) } catch { throw new HerdrEndpointError('socket_unavailable') }
+ if (canonical !== resolve(socketPath)) throw new HerdrEndpointError('socket_not_canonical')
+ return { device: socketStat.dev, inode: socketStat.ino }
+}
+
+export async function resolveHerdrEndpoint(input: {
+ sessionName: string
+ socketPath: string
+}): Promise<HerdrEndpoint> {
+ if (!SESSION_NAME_RE.test(input.sessionName)) throw new HerdrEndpointError('invalid_session_name')
+ const generation = await checkedSocket(input.socketPath)
+ const socketPath = await realpath(input.socketPath)
+ const endpointId = createHash('sha256')
+ .update('herdr\0')
+ .update(input.sessionName)
+ .update('\0')
+ .update(socketPath)
+ .digest('hex')
+ .slice(0, 16)
+ return { sessionName: input.sessionName, endpointId, socketPath, generation }
+}
+
+async function endpointGenerationMatches(endpoint: HerdrEndpoint): Promise<boolean> {
+ try {
+ const current = await checkedSocket(endpoint.socketPath)
+ return current.device === endpoint.generation.device && current.inode === endpoint.generation.inode
+ } catch {
+ return false
+ }
+}
+
+function failure(
+ dispatch: 'not_started' | 'rejected' | 'possibly_executed',
+ reason: string,
+ code?: string,
+): HerdrApiResult<never> {
+ return { ok: false, dispatch, reason, ...(code ? { code } : {}) }
+}
+
+function structuredErrorDispatch(code: string, mutation: HerdrMutationKind): 'rejected' | 'possibly_executed' {
+ if (mutation === 'none') return 'rejected'
+ if (code === 'invalid_request' || code === 'invalid_params' || code === 'pane_not_found' || code === 'invalid_key') {
+ return 'rejected'
+ }
+ if (code === 'pane_send_failed' && (mutation === 'single_enqueue' || mutation === 'single_key')) {
+ return 'rejected'
+ }
+ return 'possibly_executed'
+}
+
+function socketFailure(writeAttempted: boolean, reason: string): HerdrApiResult<never> {
+ return failure(writeAttempted ? 'possibly_executed' : 'not_started', reason)
+}
+
+function safeObject(value: unknown): value is Record<string, unknown> {
+ return !!value && typeof value === 'object' && !Array.isArray(value)
+}
+
+export class HerdrApiClient {
+ private readonly timeoutMs: number
+ private readonly maxRequestBytes: number
+ private readonly maxResponseBytes: number
+
+ constructor(
+ readonly endpoint: HerdrEndpoint,
+ options: HerdrApiClientOptions = {},
+ ) {
+ this.timeoutMs = Math.max(50, Math.min(10_000, options.timeoutMs ?? 2_000))
+ this.maxRequestBytes = Math.max(128, Math.min(HERDR_API_MAX_REQUEST_BYTES, options.maxRequestBytes ?? HERDR_API_MAX_REQUEST_BYTES))
+ this.maxResponseBytes = Math.max(128, Math.min(HERDR_API_MAX_RESPONSE_BYTES, options.maxResponseBytes ?? HERDR_API_MAX_RESPONSE_BYTES))
+ }
+
+ async ping(signal?: AbortSignal): Promise<HerdrApiResult<HerdrPong>> {
+ const response = await this.request<HerdrPong>('ping', {}, { mutation: 'none', signal })
+ if (!response.ok) return response
+ const pong = response.result
+ const capabilities = pong.capabilities
+ if (
+ pong.type !== 'pong'
+ || !HERDR_VERSION_RE.test(pong.version)
+ || pong.protocol !== HERDR_API_PROTOCOL
+ || (capabilities != null && (
+ typeof capabilities.live_handoff !== 'boolean'
+ || typeof capabilities.detached_server_daemon !== 'boolean'
+ ))
+ ) {
+ return failure('rejected', 'Herdr API protocol is incompatible', 'protocol_mismatch')
+ }
+ return response
+ }
+
+ async request<T = unknown>(
+ method: string,
+ params: Record<string, unknown>,
+ options: HerdrRequestOptions = {},
+ ): Promise<HerdrApiResult<T>> {
+ const mutation = options.mutation ?? 'none'
+ if (options.signal?.aborted) return failure('not_started', 'Herdr API request was aborted')
+
+ const id = randomUUID()
+ let frame: Buffer
+ try {
+ frame = Buffer.from(`${JSON.stringify({ id, method, params })}\n`, 'utf8')
+ } catch {
+ return failure('not_started', 'Herdr API request could not be serialized')
+ }
+ if (frame.byteLength > this.maxRequestBytes) {
+ return failure('not_started', 'Herdr API request exceeds the size limit')
+ }
+ if (!(await endpointGenerationMatches(this.endpoint))) {
+ return failure('not_started', 'Herdr endpoint is unavailable or changed')
+ }
+
+ return new Promise<HerdrApiResult<T>>((resolveResult) => {
+ let socket: Socket | null = null
+ let writeAttempted = false
+ let settled = false
+ let response = Buffer.alloc(0)
+
+ const finish = (result: HerdrApiResult<T>): void => {
+ if (settled) return
+ settled = true
+ clearTimeout(timer)
+ options.signal?.removeEventListener('abort', onAbort)
+ socket?.destroy()
+ resolveResult(result)
+ }
+ const onAbort = (): void => finish(socketFailure(writeAttempted, 'Herdr API request was aborted'))
+ const timer = setTimeout(() => finish(socketFailure(writeAttempted, 'Herdr API request timed out')), this.timeoutMs)
+ options.signal?.addEventListener('abort', onAbort, { once: true })
+
+ try {
+ socket = createConnection({ path: this.endpoint.socketPath })
+ } catch {
+ finish(failure('not_started', 'Herdr API connection could not be created'))
+ return
+ }
+
+ socket.once('connect', () => {
+ void endpointGenerationMatches(this.endpoint).then((matches) => {
+ if (settled) return
+ if (!matches) {
+ finish(failure('not_started', 'Herdr endpoint changed before dispatch'))
+ return
+ }
+ writeAttempted = true
+ try {
+ socket!.end(frame)
+ } catch {
+ finish(failure('possibly_executed', 'Herdr API request write failed'))
+ }
+ })
+ })
+ socket.on('data', (chunk: Buffer) => {
+ if (settled) return
+ response = Buffer.concat([response, chunk])
+ if (response.byteLength > this.maxResponseBytes) {
+ finish(socketFailure(writeAttempted, 'Herdr API response exceeds the size limit'))
+ return
+ }
+ const newline = response.indexOf(0x0a)
+ if (newline < 0) return
+ if (response.subarray(newline + 1).toString('utf8').trim() !== '') {
+ finish(socketFailure(writeAttempted, 'Herdr API returned multiple responses'))
+ return
+ }
+ let parsed: unknown
+ try { parsed = JSON.parse(response.subarray(0, newline).toString('utf8')) } catch {
+ finish(socketFailure(writeAttempted, 'Herdr API returned malformed JSON'))
+ return
+ }
+ if (!safeObject(parsed) || parsed.id !== id) {
+ finish(socketFailure(writeAttempted, 'Herdr API response correlation failed'))
+ return
+ }
+ if ('error' in parsed) {
+ const body = parsed.error
+ if (!safeObject(body) || typeof body.code !== 'string') {
+ finish(socketFailure(writeAttempted, 'Herdr API returned a malformed error'))
+ return
+ }
+ const dispatch = structuredErrorDispatch(body.code, mutation)
+ finish(failure(dispatch, `Herdr API request failed (${body.code})`, body.code))
+ return
+ }
+ if (!('result' in parsed)) {
+ finish(socketFailure(writeAttempted, 'Herdr API response is missing a result'))
+ return
+ }
+ finish({ ok: true, result: parsed.result as T })
+ })
+ socket.once('end', () => {
+ if (!settled) finish(socketFailure(writeAttempted, 'Herdr API response ended early'))
+ })
+ socket.once('error', () => finish(socketFailure(writeAttempted, 'Herdr API transport failed')))
+ })
+ }
+}
diff --git a/cli/src/lib/herdrBackend.real.spec.ts b/cli/src/lib/herdrBackend.real.spec.ts
new file mode 100644
index 000000000..4ee20d6ba
--- /dev/null
+++ b/cli/src/lib/herdrBackend.real.spec.ts
@@ -0,0 +1,518 @@
+import { execFile, spawn, spawnSync, type ChildProcess } from 'node:child_process'
+import { access, readFile, rm } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { dirname, join, resolve } from 'node:path'
+import { promisify } from 'node:util'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import type { AgentEngine } from '../engines/types.js'
+import {
+ agentCommandOwnershipSnapshot,
+ ENGINE_CLI_COMMANDS,
+ ENGINES,
+ installedEngineBin,
+} from './engineBin.js'
+import {
+ HERDR_API_PROTOCOL,
+ HERDR_API_SCHEMA_VERSION,
+ HerdrApiClient,
+ resolveHerdrEndpoint,
+ type HerdrApiResult,
+ type HerdrEndpoint,
+} from './herdrApiClient.js'
+import { HerdrBackend } from './herdrBackend.js'
+import { probeTerminalAgents } from './terminalAgentDiscovery.js'
+import { terminalRouteKey } from './terminalRuntime.js'
+import type { HerdrRuntimeRef } from './terminalTypes.js'
+import { probeTmuxAgents } from './tmuxAgentDiscovery.js'
+
+const exec = promisify(execFile)
+const herdrBin = process.env.HERDR_BIN || 'herdr'
+const enabled = process.env.RUN_REAL_HERDR === '1'
+const installed = spawnSync(herdrBin, ['--version'], { encoding: 'utf8' }).status === 0
+if (enabled && !installed) console.warn(`[herdr-real] skipped: ${herdrBin} is not installed`)
+const realDescribe = enabled && installed ? describe : describe.skip
+
+interface SessionListRow {
+ name: string
+ running: boolean
+ session_dir: string
+ socket_path: string
+}
+
+interface PaneInfo {
+ pane_id: string
+ terminal_id: string
+ workspace_id: string
+ tab_id: string
+ cwd?: string
+ title?: string
+ terminal_title?: string
+ terminal_title_stripped?: string
+}
+
+interface PaneProcessInfo {
+ pane_id: string
+ shell_pid?: number
+ foreground_processes?: Array<{ pid: number; name: string; argv?: string[]; cmdline?: string }>
+}
+
+interface SessionFixture {
+ name: string
+ child: ChildProcess
+ row: SessionListRow
+ endpoint: HerdrEndpoint
+ client: HerdrApiClient
+}
+
+const runId = `ah-u1-${process.pid}-${Date.now().toString(36)}`
+const sessionNames = [`${runId}-a`, `${runId}-b`]
+const sessions: SessionFixture[] = []
+const tmuxSessions = new Set<string>()
+const fixtureDir = join(tmpdir(), runId)
+const ptyFixture = resolve(dirname(new URL(import.meta.url).pathname), '__fixtures__/herdr/pty-capture.mjs')
+const ownership = agentCommandOwnershipSnapshot()
+const engines: Array<[AgentEngine, string, string | null]> = ENGINES.map((engine) => [
+ engine,
+ ENGINE_CLI_COMMANDS[engine],
+ installedEngineBin(engine, ownership),
+])
+
+function minimalEnv(): NodeJS.ProcessEnv {
+ return Object.fromEntries(Object.entries({
+ HOME: process.env.HOME,
+ PATH: process.env.PATH,
+ LANG: process.env.LANG || 'C.UTF-8',
+ TERM: 'xterm-256color',
+ XDG_CONFIG_HOME: process.env.XDG_CONFIG_HOME,
+ XDG_DATA_HOME: process.env.XDG_DATA_HOME,
+ }).filter((entry): entry is [string, string] => typeof entry[1] === 'string'))
+}
+
+async function eventually<T>(read: () => Promise<T | null>, timeoutMs = 10_000): Promise<T> {
+ const deadline = Date.now() + timeoutMs
+ let lastError: unknown
+ while (Date.now() < deadline) {
+ try {
+ const value = await read()
+ if (value !== null) return value
+ } catch (error) { lastError = error }
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, 50))
+ }
+ throw lastError ?? new Error('timed out waiting for real Herdr state')
+}
+
+async function sessionList(): Promise<SessionListRow[]> {
+ const result = await exec(herdrBin, ['session', 'list', '--json'], {
+ timeout: 2_000,
+ maxBuffer: 512 * 1024,
+ env: minimalEnv(),
+ })
+ const parsed = JSON.parse(result.stdout) as { sessions?: SessionListRow[] }
+ return Array.isArray(parsed.sessions) ? parsed.sessions : []
+}
+
+async function startSession(name: string): Promise<SessionFixture> {
+ const child = spawn(herdrBin, ['--session', name, 'server'], {
+ env: minimalEnv(),
+ stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ let diagnostics = ''
+ child.stdout?.on('data', (chunk) => { diagnostics += String(chunk).slice(0, 4_096) })
+ child.stderr?.on('data', (chunk) => { diagnostics += String(chunk).slice(0, 4_096) })
+ const row = await eventually(async () => {
+ if (child.exitCode !== null) throw new Error(`Herdr test server exited ${child.exitCode}: ${diagnostics}`)
+ return (await sessionList()).find((candidate) => candidate.name === name && candidate.running) ?? null
+ })
+ const endpoint = await resolveHerdrEndpoint({ sessionName: name, socketPath: row.socket_path })
+ const client = new HerdrApiClient(endpoint, { timeoutMs: 2_000 })
+ const ping = await client.ping()
+ if (!ping.ok) throw new Error(`Herdr test server ping failed: ${ping.reason}`)
+ const fixture = { name, child, row, endpoint, client }
+ sessions.push(fixture)
+ return fixture
+}
+
+async function call<T>(
+ client: HerdrApiClient,
+ method: string,
+ params: Record<string, unknown> = {},
+ mutation: 'none' | 'single_enqueue' | 'single_key' | 'multi_enqueue' | 'other' = 'none',
+): Promise<T> {
+ const result = await client.request<T>(method, params, { mutation })
+ if (!result.ok) throw new Error(`${method} failed: ${result.code ?? result.dispatch}`)
+ return result.result
+}
+
+async function createWorkspace(fixture: SessionFixture, label: string): Promise<PaneInfo> {
+ const result = await call<{ type: 'workspace_created'; root_pane: PaneInfo }>(
+ fixture.client,
+ 'workspace.create',
+ { cwd: process.cwd(), focus: false, label, env: {} },
+ 'other',
+ )
+ return result.root_pane
+}
+
+async function panes(fixture: SessionFixture): Promise<PaneInfo[]> {
+ return (await call<{ type: 'pane_list'; panes: PaneInfo[] }>(fixture.client, 'pane.list')).panes
+}
+
+async function processInfo(fixture: SessionFixture, paneId: string): Promise<PaneProcessInfo> {
+ return (await call<{ type: 'pane_process_info'; process_info: PaneProcessInfo }>(
+ fixture.client,
+ 'pane.process_info',
+ { pane_id: paneId },
+ )).process_info
+}
+
+async function stopSession(fixture: SessionFixture): Promise<void> {
+ await exec(herdrBin, ['--session', fixture.name, 'server', 'stop'], {
+ timeout: 3_000,
+ env: minimalEnv(),
+ }).catch(() => {})
+ if (fixture.child.exitCode === null) fixture.child.kill('SIGTERM')
+ await new Promise<void>((resolvePromise) => {
+ if (fixture.child.exitCode !== null) { resolvePromise(); return }
+ const timer = setTimeout(() => { fixture.child.kill('SIGKILL'); resolvePromise() }, 2_000)
+ fixture.child.once('exit', () => { clearTimeout(timer); resolvePromise() })
+ })
+ await exec(herdrBin, ['session', 'delete', fixture.name], {
+ timeout: 3_000,
+ env: minimalEnv(),
+ }).catch(() => {})
+}
+
+async function waitForFile(path: string): Promise<void> {
+ await eventually(async () => access(path).then(() => true).catch(() => null), 10_000)
+}
+
+function shellQuote(value: string): string {
+ return `'${value.replaceAll("'", `'\\''`)}'`
+}
+
+async function captureSubmission(
+ fixture: SessionFixture,
+ runtime: HerdrRuntimeRef,
+ name: string,
+ payload: string,
+): Promise<Buffer> {
+ const output = join(fixtureDir, `${name}.json`)
+ const ready = join(fixtureDir, `${name}.ready`)
+ await rm(output, { force: true })
+ await rm(ready, { force: true })
+ const command = `node ${shellQuote(ptyFixture)} ${shellQuote(output)} ${shellQuote(ready)}`
+ await call(fixture.client, 'pane.send_input', {
+ pane_id: runtime.paneId,
+ text: command,
+ keys: ['Enter'],
+ }, 'single_enqueue')
+ try {
+ await waitForFile(ready)
+ } catch (error) {
+ const capture = await fixture.client.request<{ type: 'pane_read'; read: { text: string } }>('pane.read', {
+ pane_id: runtime.paneId,
+ source: 'recent_unwrapped',
+ lines: 30,
+ format: 'text',
+ strip_ansi: true,
+ })
+ throw new Error(`PTY fixture did not become ready: ${capture.ok ? capture.result.read.text : capture.reason}`, { cause: error })
+ }
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, 100))
+ const submitted = await new HerdrBackend(fixture.endpoint).submitText(runtime, payload)
+ expect(submitted).toEqual({ state: 'succeeded', dispatch: 'executed' })
+ await waitForFile(output)
+ const result = JSON.parse(await readFile(output, 'utf8')) as {
+ base64: string
+ bracketedStarts: number
+ bracketedEnds: number
+ carriageReturnsAfterPaste: number
+ }
+ expect(result.bracketedStarts).toBe(1)
+ expect(result.bracketedEnds).toBe(1)
+ expect(result.carriageReturnsAfterPaste).toBe(1)
+ return Buffer.from(result.base64, 'base64')
+}
+
+realDescribe.sequential('real Herdr 0.8 socket backend', () => {
+ let first: SessionFixture
+ let second: SessionFixture
+ let firstPane: PaneInfo
+ let secondPane: PaneInfo
+
+ const runtime = (fixture: SessionFixture, pane: PaneInfo): HerdrRuntimeRef => ({
+ backend: 'herdr',
+ endpointId: fixture.endpoint.endpointId,
+ sessionName: fixture.name,
+ terminalId: pane.terminal_id,
+ paneId: pane.pane_id,
+ })
+
+ beforeAll(async () => {
+ await exec('mkdir', ['-p', fixtureDir])
+ first = await startSession(sessionNames[0])
+ second = await startSession(sessionNames[1])
+ }, 20_000)
+
+ afterAll(async () => {
+ for (const name of tmuxSessions) {
+ await exec('tmux', ['kill-session', '-t', name], { timeout: 2_000 }).catch(() => {})
+ }
+ await Promise.all([...sessions].reverse().map(stopSession))
+ await rm(fixtureDir, { recursive: true, force: true })
+ }, 20_000)
+
+ it('negotiates protocol/schema and distinguishes successful empty inventory', async () => {
+ const schema = await exec(herdrBin, ['api', 'schema', '--json'], {
+ timeout: 3_000,
+ maxBuffer: 2 * 1024 * 1024,
+ env: minimalEnv(),
+ })
+ const generated = JSON.parse(schema.stdout) as { protocol: number; schema_version: number }
+ expect(generated).toMatchObject({ protocol: HERDR_API_PROTOCOL, schema_version: HERDR_API_SCHEMA_VERSION })
+ await expect(panes(first)).resolves.toEqual([])
+ await expect(panes(second)).resolves.toEqual([])
+ })
+
+ it('namespaces duplicate routes and exposes stable endpoint-scoped identity', async () => {
+ firstPane = await createWorkspace(first, 'harness-u1-a')
+ secondPane = await createWorkspace(second, 'harness-u1-b')
+ expect(firstPane.pane_id).toBe('w1:p1')
+ expect(secondPane.pane_id).toBe('w1:p1')
+ expect(first.endpoint.endpointId).not.toBe(second.endpoint.endpointId)
+ expect(firstPane.terminal_id).not.toBe(secondPane.terminal_id)
+ const [a, b] = await Promise.all([
+ processInfo(first, firstPane.pane_id),
+ processInfo(second, secondPane.pane_id),
+ ])
+ expect(a.shell_pid).toBeGreaterThan(1)
+ expect(b.shell_pid).toBeGreaterThan(1)
+ expect(a.shell_pid).not.toBe(b.shell_pid)
+ expect(firstPane.cwd).toBe(process.cwd())
+ const inventory = await new HerdrBackend(first.endpoint).inventory()
+ expect(inventory.state).toBe('available')
+ if (inventory.state === 'available') {
+ expect(inventory.roots.some((root) => root.runtime.backend === 'herdr'
+ && root.runtime.terminalId === firstPane.terminal_id && root.rootPid === a.shell_pid)).toBe(true)
+ }
+ })
+
+ it('creates, notifies, and closes a test-owned workspace through the shared backend contract', async () => {
+ const backend = new HerdrBackend(first.endpoint)
+ const created = await backend.create({ cwd: process.cwd(), label: 'harness-lifecycle' })
+ expect(created.state).toBe('succeeded')
+ if (created.state !== 'succeeded') return
+ await expect(backend.notify(created.runtime, 'Harness test', 'Lifecycle message'))
+ .resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })
+ await expect(backend.kill(created.runtime))
+ .resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })
+ await expect(eventually(async () => (await panes(first)).some(
+ (pane) => pane.terminal_id === created.runtime.terminalId,
+ ) ? null : true)).resolves.toBe(true)
+ })
+
+ it('types literally, presses logical keys, and captures ANSI without implicit focus', async () => {
+ const backend = new HerdrBackend(first.endpoint)
+ const current = runtime(first, firstPane)
+ const marker = join(fixtureDir, 'literal-executed')
+ await expect(backend.typeLiteral(current, `touch ${shellQuote(marker)}`)).resolves.toEqual({
+ state: 'succeeded', dispatch: 'executed',
+ })
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, 200))
+ await expect(access(marker)).rejects.toBeTruthy()
+ await expect(backend.sendKey(current, 'enter')).resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })
+ await waitForFile(marker)
+
+ await call(first.client, 'pane.send_input', {
+ pane_id: firstPane.pane_id,
+ text: `printf '\\033[31mHERDR_ANSI_CAPTURE\\033[0m\\n'; printf '\\033]0;HERDR_U1_TITLE\\007'`,
+ keys: ['Enter'],
+ }, 'single_enqueue')
+ const read = await eventually(async () => {
+ const result = await backend.capture(current, { mode: 'recent_unwrapped', historyLines: 100, ansi: true })
+ return result.state === 'succeeded' && result.value.includes('HERDR_ANSI_CAPTURE') ? result.value : null
+ })
+ expect(read).toMatch(/\u001b\[[0-9;]*mHERDR_ANSI_CAPTURE\u001b\[0m/)
+ const titled = await eventually(async () => {
+ const result = await call<{ type: 'pane_info'; pane: PaneInfo }>(first.client, 'pane.get', { pane_id: firstPane.pane_id })
+ return result.pane.terminal_title_stripped === 'HERDR_U1_TITLE' ? result.pane : null
+ })
+ expect(titled.terminal_title_stripped).toBe('HERDR_U1_TITLE')
+ await expect(backend.setTitle(current, 'Harness Herdr title')).resolves.toEqual({
+ state: 'succeeded', dispatch: 'executed',
+ })
+ const titles = await backend.titles()
+ expect(titles.state).toBe('succeeded')
+ if (titles.state === 'succeeded') expect(titles.value.get(terminalRouteKey(current))).toBe('Harness Herdr title')
+ })
+
+ for (const [engine, bin, path] of engines) {
+ if (!path) console.warn(`[herdr-real] unavailable matrix row: ${engine} (${bin} has no verified installed executable)`)
+ const matrixIt = path ? it : it.skip
+ matrixIt(`discovers ${engine} once and process-only deletion preserves its terminal`, async () => {
+ const pane = await createWorkspace(first, `matrix-${engine}`)
+ const current = runtime(first, pane)
+ const backend = new HerdrBackend(first.endpoint)
+ await expect(backend.submitText(current, shellQuote(path!))).resolves.toEqual({
+ state: 'succeeded', dispatch: 'executed',
+ })
+
+ const discovered = await eventually(async () => {
+ const result = await probeTerminalAgents([backend], ['herdr'], [first.name], -1)
+ const inPane = result.agents.filter((candidate) => candidate.runtimes.some(
+ (candidateRuntime) => terminalRouteKey(candidateRuntime) === terminalRouteKey(current),
+ ))
+ return inPane.length === 1 && inPane[0].engine === engine ? inPane[0] : null
+ }, 20_000)
+ const capture = await backend.capture(current, { mode: 'recent_unwrapped', historyLines: 30, ansi: false })
+ expect(discovered, `${bin} was not discovered in ${current.paneId}\n${capture.state === 'succeeded' ? capture.value : capture.reason}`).not.toBeNull()
+
+ const pid = discovered.processIdentity.pid
+ process.kill(pid, 'SIGTERM')
+ const gone = await eventually(async () => {
+ try { process.kill(pid, 0) } catch { return true }
+ return null
+ }, 2_000).catch(() => false)
+ if (!gone) {
+ try { process.kill(pid, 'SIGKILL') } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error
+ }
+ }
+
+ const absent = await eventually(async () => {
+ const result = await probeTerminalAgents([backend], ['herdr'], [first.name], -1)
+ return result.agents.some((candidate) => candidate.processIdentity.pid === pid) ? null : true
+ }, 5_000)
+ expect(absent, `${bin} remained discoverable after its exact saved PID was terminated`).toBe(true)
+ const paneAfterDelete = await first.client.request<{ type: 'pane_info'; pane: PaneInfo }>(
+ 'pane.get', { pane_id: current.paneId },
+ )
+ expect(paneAfterDelete.ok).toBe(true)
+ if (paneAfterDelete.ok) expect(paneAfterDelete.result.pane.terminal_id).toBe(current.terminalId)
+ }, 35_000)
+ }
+
+ it.each([
+ ['short', 'u1 short input'],
+ ['multiline', 'line one\nline two\nline three\nline four'],
+ ['long', '0123456789abcdef'.repeat(1_792)],
+ ])('submits %s text byte-for-byte exactly once through one API request', async (name, payload) => {
+ const bytes = await captureSubmission(first, runtime(first, firstPane), name, payload)
+ expect(bytes).toEqual(Buffer.from(`\u001b[200~${payload}\u001b[201~\r`))
+ expect(Buffer.byteLength(payload)).toBe(name === 'long' ? 28_672 : Buffer.byteLength(payload))
+
+ const processArgs = (await exec('ps', ['-axo', 'args='], { timeout: 2_000 })).stdout
+ expect(processArgs).not.toContain(payload)
+ const serverLog = join(first.row.session_dir, 'herdr-server.log')
+ const log = await readFile(serverLog, 'utf8').catch(() => '')
+ expect(log).not.toContain(payload)
+ }, 20_000)
+
+ it('preserves terminal identity across a workspace move and records alias behavior', async () => {
+ const before = firstPane
+ const moved = await call<{ type: 'pane_move'; move_result: { pane: PaneInfo; previous_pane_id: string } }>(
+ first.client,
+ 'pane.move',
+ {
+ pane_id: before.pane_id,
+ destination: { type: 'new_workspace', label: 'harness-u1-moved', tab_label: 'harness-u1-moved' },
+ focus: false,
+ },
+ 'other',
+ )
+ firstPane = moved.move_result.pane
+ expect(firstPane.pane_id).not.toBe(before.pane_id)
+ expect(firstPane.terminal_id).toBe(before.terminal_id)
+ expect((await processInfo(first, firstPane.pane_id)).shell_pid).toBeGreaterThan(1)
+
+ const oldRouteImmediately = await first.client.request<{ type: 'pane_info'; pane: PaneInfo }>(
+ 'pane.get', { pane_id: before.pane_id },
+ )
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, 10_000))
+ const oldRouteAfterTenSeconds = await first.client.request<{ type: 'pane_info'; pane: PaneInfo }>(
+ 'pane.get', { pane_id: before.pane_id },
+ )
+ console.log('[herdr-real] route alias', JSON.stringify({
+ immediate: oldRouteImmediately.ok,
+ afterTenSeconds: oldRouteAfterTenSeconds.ok,
+ oldRoute: before.pane_id,
+ currentRoute: firstPane.pane_id,
+ }))
+ expect(oldRouteImmediately.ok).toBe(true)
+ }, 20_000)
+
+ it('keeps the direct inventory/process probe below half the 5s reconcile interval', async () => {
+ const samples: Record<string, number[]> = { '1': [], '10': [], '50': [] }
+ let count = (await panes(second)).length
+ for (const target of [1, 10, 50]) {
+ while (count < target) {
+ await createWorkspace(second, `bench-${count + 1}`)
+ count++
+ }
+ for (let sample = 0; sample < 10; sample++) {
+ const started = performance.now()
+ const listed = await panes(second)
+ await Promise.all(listed.map((pane) => processInfo(second, pane.pane_id)))
+ samples[String(target)].push(performance.now() - started)
+ }
+ }
+ const p95 = Object.fromEntries(Object.entries(samples).map(([key, values]) => {
+ const ordered = values.toSorted((a, b) => a - b)
+ return [key, ordered[Math.ceil(ordered.length * 0.95) - 1]]
+ })) as Record<string, number>
+ const safeMinimumMs = Math.max(250, Math.ceil((Math.max(...Object.values(p95)) * 2) / 50) * 50)
+ console.log('[herdr-real] reconcile benchmark', JSON.stringify({ p95Ms: p95, safeMinimumMs }))
+ expect(p95['50']).toBeLessThan(2_500)
+ }, 60_000)
+
+ it('classifies stopped transport as unavailable rather than an empty snapshot', async () => {
+ const isolated = await startSession(`${runId}-availability`)
+ await expect(panes(isolated)).resolves.toEqual([])
+ await stopSession(isolated)
+ sessions.splice(sessions.indexOf(isolated), 1)
+ const unavailable: HerdrApiResult<unknown> = await isolated.client.request('pane.list', {})
+ expect(unavailable).toMatchObject({ ok: false, dispatch: 'not_started' })
+ })
+
+ it('observes both real nested multiplexer topologies without duplicate engine ownership', async () => {
+ const amp = (await exec('/bin/sh', ['-lc', 'command -v amp'], { timeout: 2_000 })).stdout.trim()
+ expect(amp).not.toBe('')
+
+ const innerTmux = `${runId}-tmux-in-herdr`
+ tmuxSessions.add(innerTmux)
+ await call(first.client, 'pane.send_input', {
+ pane_id: firstPane.pane_id,
+ text: `tmux new-session -d -s ${shellQuote(innerTmux)} ${shellQuote(amp)}`,
+ keys: ['Enter'],
+ }, 'single_enqueue')
+ const tmuxAgent = await eventually(async () => {
+ const result = await probeTmuxAgents()
+ if (!result.ok) return null
+ return result.agents.find((agent) => agent.engine === 'amp' && agent.processIdentity.pid > 0) ?? null
+ }, 20_000)
+ const outerHerdr = await processInfo(first, firstPane.pane_id)
+ expect(outerHerdr.foreground_processes?.some((process) => process.pid === tmuxAgent.processIdentity.pid)).toBe(false)
+
+ const outerTmux = `${runId}-herdr-in-tmux`
+ tmuxSessions.add(outerTmux)
+ await exec('tmux', ['new-session', '-d', '-s', outerTmux], { timeout: 5_000 })
+ const outerPane = (await exec('tmux', ['list-panes', '-t', outerTmux, '-F', '#{pane_id}'], { timeout: 2_000 })).stdout.trim()
+ await exec('tmux', ['send-keys', '-t', outerPane, '-l', '--', `${herdrBin} --session ${second.name}`], { timeout: 2_000 })
+ await exec('tmux', ['send-keys', '-t', outerPane, 'Enter'], { timeout: 2_000 })
+ await call(second.client, 'pane.send_input', {
+ pane_id: secondPane.pane_id,
+ text: shellQuote(amp),
+ keys: ['Enter'],
+ }, 'single_enqueue')
+ const herdrAmp = await eventually(async () => {
+ const info = await processInfo(second, secondPane.pane_id)
+ return info.foreground_processes?.find((process) => process.name === 'amp') ?? null
+ }, 20_000)
+ const observed = await probeTmuxAgents()
+ expect(observed.ok && observed.agents.some((agent) => agent.tmuxPane === outerPane && agent.processIdentity.pid === herdrAmp.pid)).toBe(false)
+ console.log('[herdr-real] nested topology', JSON.stringify({
+ tmuxInsideHerdr: { enginePid: tmuxAgent.processIdentity.pid, locators: ['tmux'] },
+ herdrInsideTmux: { enginePid: herdrAmp.pid, locators: ['herdr'] },
+ }))
+ }, 45_000)
+})
diff --git a/cli/src/lib/herdrBackend.spec.ts b/cli/src/lib/herdrBackend.spec.ts
new file mode 100644
index 000000000..37d1dd73d
--- /dev/null
+++ b/cli/src/lib/herdrBackend.spec.ts
@@ -0,0 +1,138 @@
+import { describe, expect, it, vi } from 'vitest'
+import { HerdrBackend } from './herdrBackend.js'
+import type { HerdrApiClient, HerdrEndpoint } from './herdrApiClient.js'
+import { terminalRouteKey } from './terminalRuntime.js'
+import type { HerdrRuntimeRef } from './terminalTypes.js'
+
+const endpoint: HerdrEndpoint = {
+ sessionName: 'default',
+ endpointId: 'endpoint-a',
+ socketPath: '/configured/herdr.sock',
+ generation: { device: 1, inode: 2 },
+}
+const runtime: HerdrRuntimeRef = {
+ backend: 'herdr', endpointId: 'endpoint-a', sessionName: 'default', terminalId: 'terminal-a', paneId: 'w1:p1',
+}
+
+function backendWith(request: unknown, ping: unknown = vi.fn(async () => ({
+ ok: true as const,
+ result: { type: 'pong' as const, version: '0.8.0', protocol: 19 },
+}))): HerdrBackend {
+ return new HerdrBackend(endpoint, { request, ping, endpoint } as HerdrApiClient)
+}
+
+describe('HerdrBackend', () => {
+ it('reads endpoint-scoped pane labels and terminal titles from the API snapshot', async () => {
+ const backend = backendWith(vi.fn(async () => ({
+ ok: true as const,
+ result: {
+ type: 'session_snapshot',
+ snapshot: {
+ version: '0.8.0', protocol: 19, panes: [
+ { pane_id: 'w1:p1', terminal_id: 'terminal-a', label: 'manual label', terminal_title_stripped: 'shell title' },
+ { pane_id: 'w1:p2', terminal_id: 'terminal-b', terminal_title_stripped: 'terminal title' },
+ ],
+ },
+ },
+ })))
+ const result = await backend.titles()
+ expect(result.state).toBe('succeeded')
+ if (result.state !== 'succeeded') return
+ expect([...result.value.values()]).toEqual(['manual label', 'terminal title'])
+ expect([...result.value.keys()]).toEqual([
+ terminalRouteKey(runtime),
+ terminalRouteKey({ ...runtime, terminalId: 'terminal-b', paneId: 'w1:p2' }),
+ ])
+ })
+
+ it('distinguishes a successful empty snapshot from unavailable transport', async () => {
+ const empty = backendWith(vi.fn(async () => ({
+ ok: true as const,
+ result: { type: 'session_snapshot', snapshot: { version: '0.8.0', protocol: 19, panes: [] } },
+ })))
+ expect(await empty.inventory()).toEqual({ state: 'available', roots: [] })
+
+ const unavailable = backendWith(vi.fn(), vi.fn(async () => ({
+ ok: false as const, dispatch: 'not_started' as const, reason: 'Herdr API unavailable',
+ })))
+ expect(await unavailable.inventory()).toEqual({ state: 'unavailable', reason: 'Herdr API unavailable' })
+ })
+
+ it('builds endpoint-scoped roots from snapshot and pane process info', async () => {
+ const request = vi.fn(async (method: string) => method === 'session.snapshot'
+ ? { ok: true as const, result: { type: 'session_snapshot', snapshot: { version: '0.8.0', protocol: 19, panes: [{ pane_id: 'w1:p1', terminal_id: 'terminal-a', cwd: '/work' }] } } }
+ : { ok: true as const, result: { type: 'pane_process_info', process_info: { pane_id: 'w1:p1', shell_pid: 42 } } })
+ expect(await backendWith(request).inventory()).toEqual({
+ state: 'available',
+ roots: [{ runtime, rootPid: 42, cwd: '/work' }],
+ })
+ })
+
+ it('submits stripped multiline text once and preserves ambiguous dispatch evidence', async () => {
+ const request = vi.fn(async () => ({
+ ok: false as const,
+ dispatch: 'possibly_executed' as const,
+ reason: 'Herdr API response ended early',
+ }))
+ const result = await backendWith(request).submitText(runtime, 'one\ntwo\n\n')
+ expect(request).toHaveBeenCalledOnce()
+ expect(request).toHaveBeenCalledWith('pane.send_input', {
+ pane_id: 'w1:p1', text: 'one\ntwo', keys: ['Enter'],
+ }, { mutation: 'single_enqueue' })
+ expect(result).toEqual({
+ state: 'unknown', dispatch: 'possibly_executed', reason: 'Herdr API response ended early',
+ })
+ })
+
+ it('uses explicit pane routes for capture and logical keys', async () => {
+ const request = vi.fn(async (method: string) => method === 'pane.read'
+ ? { ok: true as const, result: { type: 'pane_read', read: { text: '\u001b[31mred\u001b[0m' } } }
+ : { ok: true as const, result: { type: 'ok' } })
+ const backend = backendWith(request)
+ await expect(backend.capture(runtime, { historyLines: 60 })).resolves.toEqual({ state: 'succeeded', value: '\u001b[31mred\u001b[0m' })
+ await expect(backend.sendKey(runtime, 'ctrl-c')).resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })
+ expect(request).toHaveBeenLastCalledWith('pane.send_keys', { pane_id: 'w1:p1', keys: ['Ctrl+C'] }, { mutation: 'single_key' })
+ })
+
+ it('creates a workspace and closes the workspace resolved from its root pane', async () => {
+ const request = vi.fn(async (method: string) => {
+ if (method === 'workspace.create') {
+ return {
+ ok: true as const,
+ result: {
+ type: 'workspace_created',
+ root_pane: { pane_id: 'w2:p1', terminal_id: 'terminal-created', workspace_id: 'workspace-created' },
+ },
+ }
+ }
+ if (method === 'pane.get') {
+ return {
+ ok: true as const,
+ result: {
+ type: 'pane_info',
+ pane: { pane_id: 'w2:p1', terminal_id: 'terminal-created', workspace_id: 'workspace-created' },
+ },
+ }
+ }
+ return { ok: true as const, result: { type: 'ok' } }
+ })
+ const backend = backendWith(request)
+
+ const created = await backend.create({ cwd: '/tmp/work', label: 'Harness test' })
+ expect(created).toEqual({
+ state: 'succeeded',
+ dispatch: 'executed',
+ runtime: {
+ backend: 'herdr', endpointId: 'endpoint-a', sessionName: 'default',
+ terminalId: 'terminal-created', paneId: 'w2:p1',
+ },
+ })
+ if (created.state !== 'succeeded') return
+ await expect(backend.kill(created.runtime)).resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })
+ expect(request.mock.calls).toEqual([
+ ['workspace.create', { cwd: '/tmp/work', focus: false, label: 'Harness test', env: {} }, { mutation: 'other' }],
+ ['pane.get', { pane_id: 'w2:p1' }],
+ ['workspace.close', { workspace_id: 'workspace-created' }, { mutation: 'other' }],
+ ])
+ })
+})
diff --git a/cli/src/lib/herdrBackend.ts b/cli/src/lib/herdrBackend.ts
new file mode 100644
index 000000000..b42a2c907
--- /dev/null
+++ b/cli/src/lib/herdrBackend.ts
@@ -0,0 +1,321 @@
+import type { TerminalBackend } from './terminalBackend.js'
+import { HerdrApiClient, type HerdrApiResult, type HerdrEndpoint } from './herdrApiClient.js'
+import {
+ TERMINAL_ACTION_SUCCEEDED,
+ terminalActionNotStarted,
+ terminalActionPossiblyExecuted,
+ terminalActionRejected,
+ type HerdrRuntimeRef,
+ type RuntimeValidation,
+ type TerminalActionResult,
+ type TerminalCaptureOptions,
+ type TerminalCreateRequest,
+ type TerminalCreateResult,
+ type TerminalInventoryResult,
+ type TerminalLogicalKey,
+ type TerminalProcessExpectation,
+ type TerminalReadResult,
+} from './terminalTypes.js'
+import { engineProcessMatchScore, processRows } from './tmux.js'
+import { terminalRouteKey } from './terminalRuntime.js'
+
+interface HerdrPaneInfo {
+ pane_id: string
+ terminal_id: string
+ workspace_id?: string
+ cwd?: string
+ label?: string
+ title?: string
+ terminal_title_stripped?: string
+}
+
+interface HerdrSessionSnapshotResult {
+ type: 'session_snapshot'
+ snapshot: {
+ version: string
+ protocol: number
+ panes: HerdrPaneInfo[]
+ }
+}
+
+interface HerdrPaneProcessInfoResult {
+ type: 'pane_process_info'
+ process_info: {
+ pane_id: string
+ shell_pid?: number
+ }
+}
+
+interface HerdrPaneReadResult {
+ type: 'pane_read'
+ read: { text: string }
+}
+
+interface HerdrPaneInfoResult {
+ type: 'pane_info'
+ pane: HerdrPaneInfo
+}
+
+interface HerdrWorkspaceCreatedResult {
+ type: 'workspace_created'
+ root_pane: HerdrPaneInfo
+}
+
+const HERDR_KEYS: Record<TerminalLogicalKey, string> = {
+ enter: 'Enter',
+ escape: 'Escape',
+ tab: 'Tab',
+ backtab: 'BackTab',
+ up: 'Up',
+ down: 'Down',
+ left: 'Left',
+ right: 'Right',
+ home: 'Home',
+ end: 'End',
+ backspace: 'Backspace',
+ delete: 'Delete',
+ pageup: 'PageUp',
+ pagedown: 'PageDown',
+ 'ctrl-c': 'Ctrl+C',
+ 'ctrl-d': 'Ctrl+D',
+ 'ctrl-u': 'Ctrl+U',
+ 'ctrl-w': 'Ctrl+W',
+ space: 'Space',
+ '0': '0',
+ '1': '1',
+ '2': '2',
+ '3': '3',
+ '4': '4',
+ '5': '5',
+ '6': '6',
+ '7': '7',
+ '8': '8',
+ '9': '9',
+}
+
+function actionResult(result: HerdrApiResult<unknown>): TerminalActionResult {
+ if (result.ok) return TERMINAL_ACTION_SUCCEEDED
+ if (result.dispatch === 'not_started') return terminalActionNotStarted(result.reason)
+ if (result.dispatch === 'rejected') return terminalActionRejected(result.reason)
+ return terminalActionPossiblyExecuted(result.reason)
+}
+
+function runtimeFor(endpoint: HerdrEndpoint, pane: HerdrPaneInfo): HerdrRuntimeRef {
+ return {
+ backend: 'herdr',
+ endpointId: endpoint.endpointId,
+ sessionName: endpoint.sessionName,
+ terminalId: pane.terminal_id,
+ paneId: pane.pane_id,
+ }
+}
+
+function paneTitle(pane: HerdrPaneInfo): string | null {
+ for (const candidate of [pane.label, pane.terminal_title_stripped, pane.title]) {
+ if (typeof candidate === 'string' && candidate.trim()) return candidate
+ }
+ return null
+}
+
+export class HerdrBackend implements TerminalBackend<HerdrRuntimeRef> {
+ readonly name = 'herdr' as const
+ readonly instanceId: string
+ readonly client: HerdrApiClient
+
+ constructor(
+ readonly endpoint: HerdrEndpoint,
+ client = new HerdrApiClient(endpoint),
+ ) {
+ this.instanceId = `herdr:${endpoint.endpointId}`
+ this.client = client
+ }
+
+ async create(request: TerminalCreateRequest): Promise<TerminalCreateResult<HerdrRuntimeRef>> {
+ const result = await this.client.request<HerdrWorkspaceCreatedResult>('workspace.create', {
+ ...(request.cwd ? { cwd: request.cwd } : {}),
+ focus: false,
+ ...(request.label ? { label: request.label } : {}),
+ env: {},
+ }, { mutation: 'other' })
+ if (!result.ok) {
+ if (result.dispatch === 'not_started') return terminalActionNotStarted(result.reason)
+ if (result.dispatch === 'rejected') return terminalActionRejected(result.reason)
+ return terminalActionPossiblyExecuted(result.reason)
+ }
+ if (result.result.type !== 'workspace_created'
+ || typeof result.result.root_pane?.pane_id !== 'string'
+ || typeof result.result.root_pane?.terminal_id !== 'string') {
+ return terminalActionPossiblyExecuted('Herdr created a workspace without returning its root pane')
+ }
+ return {
+ state: 'succeeded',
+ dispatch: 'executed',
+ runtime: runtimeFor(this.endpoint, result.result.root_pane),
+ }
+ }
+
+ async kill(runtime: HerdrRuntimeRef): Promise<TerminalActionResult> {
+ if (!this.owns(runtime)) return terminalActionNotStarted('Herdr runtime belongs to another configured endpoint')
+ const info = await this.client.request<HerdrPaneInfoResult>('pane.get', { pane_id: runtime.paneId })
+ if (!info.ok
+ || info.result.type !== 'pane_info'
+ || info.result.pane?.terminal_id !== runtime.terminalId
+ || typeof info.result.pane.workspace_id !== 'string') {
+ return terminalActionNotStarted('Herdr workspace could not be resolved from terminal runtime')
+ }
+ return actionResult(await this.client.request('workspace.close', {
+ workspace_id: info.result.pane.workspace_id,
+ }, { mutation: 'other' }))
+ }
+
+ async titles(): Promise<TerminalReadResult<Map<string, string>>> {
+ const snapshot = await this.client.request<HerdrSessionSnapshotResult>('session.snapshot', {})
+ if (!snapshot.ok) return { state: 'failed', reason: snapshot.reason }
+ if (snapshot.result.type !== 'session_snapshot' || !Array.isArray(snapshot.result.snapshot?.panes)) {
+ return { state: 'failed', reason: 'Herdr session snapshot has an incompatible shape' }
+ }
+ const titles = new Map<string, string>()
+ for (const pane of snapshot.result.snapshot.panes) {
+ if (!pane || typeof pane.pane_id !== 'string' || typeof pane.terminal_id !== 'string') continue
+ const title = paneTitle(pane)
+ if (title) titles.set(terminalRouteKey(runtimeFor(this.endpoint, pane)), title)
+ }
+ return { state: 'succeeded', value: titles }
+ }
+
+ private owns(runtime: HerdrRuntimeRef): boolean {
+ return runtime.endpointId === this.endpoint.endpointId && runtime.sessionName === this.endpoint.sessionName
+ }
+
+ async inventory(): Promise<TerminalInventoryResult> {
+ const ping = await this.client.ping()
+ if (!ping.ok) {
+ return ping.code === 'protocol_mismatch'
+ ? { state: 'incompatible', reason: ping.reason }
+ : { state: 'unavailable', reason: ping.reason }
+ }
+ const snapshot = await this.client.request<HerdrSessionSnapshotResult>('session.snapshot', {})
+ if (!snapshot.ok) return { state: 'unavailable', reason: snapshot.reason }
+ if (snapshot.result.type !== 'session_snapshot' || !Array.isArray(snapshot.result.snapshot?.panes)) {
+ return { state: 'incompatible', reason: 'Herdr session snapshot has an incompatible shape' }
+ }
+ const roots = await Promise.all(snapshot.result.snapshot.panes.map(async (pane) => {
+ if (!pane || typeof pane.pane_id !== 'string' || typeof pane.terminal_id !== 'string') return null
+ const info = await this.client.request<HerdrPaneProcessInfoResult>('pane.process_info', { pane_id: pane.pane_id })
+ if (!info.ok
+ || info.result.type !== 'pane_process_info'
+ || !Number.isSafeInteger(info.result.process_info?.shell_pid)
+ || info.result.process_info.shell_pid! <= 0) return null
+ return {
+ runtime: runtimeFor(this.endpoint, pane),
+ rootPid: info.result.process_info.shell_pid!,
+ cwd: typeof pane.cwd === 'string' ? pane.cwd : '',
+ }
+ }))
+ if (roots.some((root) => root === null)) {
+ return { state: 'unavailable', reason: 'Herdr pane process inventory failed' }
+ }
+ return { state: 'available', roots: roots.filter((root) => root !== null) }
+ }
+
+ async resolveRuntimeHint(paneId: string): Promise<TerminalReadResult<HerdrRuntimeRef>> {
+ const info = await this.client.request<HerdrPaneInfoResult>('pane.get', { pane_id: paneId })
+ if (!info.ok || info.result.type !== 'pane_info' || typeof info.result.pane?.terminal_id !== 'string') {
+ return { state: 'failed', reason: info.ok ? 'Herdr pane response is incompatible' : info.reason }
+ }
+ return { state: 'succeeded', value: runtimeFor(this.endpoint, info.result.pane) }
+ }
+
+ async validate(runtime: HerdrRuntimeRef, _expected: TerminalProcessExpectation): Promise<RuntimeValidation> {
+ if (!this.owns(runtime)) return { state: 'gone', reason: 'Herdr runtime belongs to another configured endpoint' }
+ const resolved = await this.resolveRuntimeHint(runtime.paneId)
+ if (resolved.state === 'failed') return { state: 'unknown', reason: resolved.reason }
+ if (resolved.value.terminalId !== runtime.terminalId) {
+ return { state: 'gone', reason: 'Herdr terminal identity changed under pane route' }
+ }
+ if (!_expected.processIdentity) return { state: 'alive' }
+ const [info, rows] = await Promise.all([
+ this.client.request<HerdrPaneProcessInfoResult>('pane.process_info', { pane_id: runtime.paneId }),
+ processRows(),
+ ])
+ if (!info.ok || !rows || info.result.type !== 'pane_process_info'
+ || !Number.isSafeInteger(info.result.process_info?.shell_pid)) {
+ return { state: 'unknown', reason: 'Herdr process identity could not be verified' }
+ }
+ const expected = rows.find((row) => row.pid === _expected.processIdentity!.pid)
+ if (!expected || expected.startMarker !== _expected.processIdentity.startMarker) {
+ return { state: 'gone', reason: 'Herdr engine process identity changed' }
+ }
+ if (engineProcessMatchScore(expected, _expected.engine) <= 0) {
+ return { state: 'gone', reason: 'Herdr process no longer matches the registered engine' }
+ }
+ const byPid = new Map(rows.map((row) => [row.pid, row]))
+ const rootPid = info.result.process_info.shell_pid!
+ let pid = expected.pid
+ const visited = new Set<number>()
+ while (pid > 0 && !visited.has(pid)) {
+ if (pid === rootPid) return { state: 'alive' }
+ visited.add(pid)
+ pid = byPid.get(pid)?.parentPid ?? 0
+ }
+ return { state: 'gone', reason: 'Herdr engine process is no longer under the terminal root' }
+ }
+
+ async capture(runtime: HerdrRuntimeRef, options: TerminalCaptureOptions = {}): Promise<TerminalReadResult<string>> {
+ if (!this.owns(runtime)) return { state: 'failed', reason: 'Herdr runtime belongs to another configured endpoint' }
+ const result = await this.client.request<HerdrPaneReadResult>('pane.read', {
+ pane_id: runtime.paneId,
+ source: options.mode ?? 'recent_unwrapped',
+ lines: Math.max(20, Math.min(300, Math.floor(options.historyLines ?? 100))),
+ format: options.ansi === false ? 'text' : 'ansi',
+ strip_ansi: options.ansi === false,
+ })
+ if (!result.ok) return { state: 'failed', reason: result.reason }
+ if (result.result.type !== 'pane_read' || typeof result.result.read?.text !== 'string') {
+ return { state: 'failed', reason: 'Herdr pane capture has an incompatible shape' }
+ }
+ return { state: 'succeeded', value: result.result.read.text }
+ }
+
+ async typeLiteral(runtime: HerdrRuntimeRef, text: string): Promise<TerminalActionResult> {
+ if (!this.owns(runtime)) return terminalActionNotStarted('Herdr runtime belongs to another configured endpoint')
+ return actionResult(await this.client.request('pane.send_text', {
+ pane_id: runtime.paneId,
+ text,
+ }, { mutation: 'single_enqueue' }))
+ }
+
+ async submitText(runtime: HerdrRuntimeRef, text: string): Promise<TerminalActionResult> {
+ if (!this.owns(runtime)) return terminalActionNotStarted('Herdr runtime belongs to another configured endpoint')
+ return actionResult(await this.client.request('pane.send_input', {
+ pane_id: runtime.paneId,
+ text: text.replace(/[\r\n]+$/, ''),
+ keys: ['Enter'],
+ }, { mutation: 'single_enqueue' }))
+ }
+
+ async sendKey(runtime: HerdrRuntimeRef, key: TerminalLogicalKey): Promise<TerminalActionResult> {
+ if (!this.owns(runtime)) return terminalActionNotStarted('Herdr runtime belongs to another configured endpoint')
+ return actionResult(await this.client.request('pane.send_keys', {
+ pane_id: runtime.paneId,
+ keys: [HERDR_KEYS[key]],
+ }, { mutation: 'single_key' }))
+ }
+
+ async setTitle(runtime: HerdrRuntimeRef, title: string): Promise<TerminalActionResult> {
+ if (!this.owns(runtime)) return terminalActionNotStarted('Herdr runtime belongs to another configured endpoint')
+ return actionResult(await this.client.request('pane.rename', {
+ pane_id: runtime.paneId,
+ label: title.slice(0, 200),
+ }, { mutation: 'other' }))
+ }
+
+ async notify(runtime: HerdrRuntimeRef, title: string, body: string): Promise<TerminalActionResult> {
+ if (!this.owns(runtime)) return terminalActionNotStarted('Herdr runtime belongs to another configured endpoint')
+ return actionResult(await this.client.request('notification.show', {
+ title: title.slice(0, 200),
+ body: body.slice(0, 1_000),
+ sound: 'none',
+ }, { mutation: 'other' }))
+ }
+}
diff --git a/cli/src/lib/herdrSessions.spec.ts b/cli/src/lib/herdrSessions.spec.ts
new file mode 100644
index 000000000..fe9ad86c5
--- /dev/null
+++ b/cli/src/lib/herdrSessions.spec.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from 'vitest'
+import { parseHerdrSessionList, resolveConfiguredHerdrSessions } from './herdrSessions.js'
+
+describe('configured Herdr session bootstrap', () => {
+ it('parses bounded session-list output without treating pane content as CLI data', () => {
+ expect(parseHerdrSessionList(JSON.stringify({ sessions: [{
+ name: 'default', running: true, session_dir: '/config/default', socket_path: '/config/default/herdr.sock',
+ }] }))).toEqual([{
+ name: 'default', running: true, session_dir: '/config/default', socket_path: '/config/default/herdr.sock',
+ }])
+ })
+
+ it('reports configured targets independently and never falls back to an unconfigured session', async () => {
+ const result = await resolveConfiguredHerdrSessions(['default', 'work'], async () => [{
+ name: 'other', running: true, session_dir: '/other', socket_path: '/other/herdr.sock',
+ }])
+ expect(result).toEqual([
+ { state: 'unavailable', sessionName: 'default', reason: 'configured Herdr session is not running' },
+ { state: 'unavailable', sessionName: 'work', reason: 'configured Herdr session is not running' },
+ ])
+ })
+
+ it('rejects configured aliases that resolve to the same canonical endpoint', async () => {
+ const result = await resolveConfiguredHerdrSessions(
+ ['default', 'alias'],
+ async () => [
+ { name: 'default', running: true, session_dir: '/safe', socket_path: '/safe/herdr.sock' },
+ { name: 'alias', running: true, session_dir: '/safe', socket_path: '/safe/herdr.sock' },
+ ],
+ async ({ sessionName, socketPath }) => ({
+ sessionName,
+ socketPath,
+ endpointId: `endpoint-${sessionName}`,
+ generation: { device: 1, inode: 2 },
+ }),
+ )
+ expect(result).toEqual([
+ {
+ state: 'unavailable', sessionName: 'default',
+ reason: 'configured Herdr sessions resolve to the same canonical endpoint',
+ },
+ {
+ state: 'unavailable', sessionName: 'alias',
+ reason: 'configured Herdr sessions resolve to the same canonical endpoint',
+ },
+ ])
+ })
+
+ it('rejects malformed and oversized output', () => {
+ expect(() => parseHerdrSessionList('{"sessions":[{}]}')).toThrow('incompatible shape')
+ expect(() => parseHerdrSessionList('x'.repeat(512 * 1024 + 1))).toThrow('size limit')
+ })
+})
diff --git a/cli/src/lib/herdrSessions.ts b/cli/src/lib/herdrSessions.ts
new file mode 100644
index 000000000..fc09d4600
--- /dev/null
+++ b/cli/src/lib/herdrSessions.ts
@@ -0,0 +1,102 @@
+import { execFile } from 'node:child_process'
+import { promisify } from 'node:util'
+import { HerdrEndpointError, resolveHerdrEndpoint, type HerdrEndpoint } from './herdrApiClient.js'
+
+const exec = promisify(execFile)
+const MAX_LIST_BYTES = 512 * 1024
+
+export interface HerdrSessionListRow {
+ name: string
+ running: boolean
+ session_dir: string
+ socket_path: string
+}
+
+export type HerdrTargetResolution =
+ | { state: 'available'; sessionName: string; endpoint: HerdrEndpoint }
+ | { state: 'unavailable'; sessionName: string; reason: string }
+
+function validRow(value: unknown): value is HerdrSessionListRow {
+ if (!value || typeof value !== 'object') return false
+ const row = value as Partial<HerdrSessionListRow>
+ return typeof row.name === 'string'
+ && row.name.length <= 64
+ && typeof row.running === 'boolean'
+ && typeof row.session_dir === 'string'
+ && row.session_dir.length <= 4_096
+ && typeof row.socket_path === 'string'
+ && row.socket_path.length <= 4_096
+}
+
+export function parseHerdrSessionList(stdout: string): HerdrSessionListRow[] {
+ if (Buffer.byteLength(stdout) > MAX_LIST_BYTES) throw new Error('Herdr session list exceeds the size limit')
+ const parsed = JSON.parse(stdout) as { sessions?: unknown }
+ if (!Array.isArray(parsed.sessions) || !parsed.sessions.every(validRow)) {
+ throw new Error('Herdr session list has an incompatible shape')
+ }
+ return parsed.sessions
+}
+
+/** CLI bootstrap contains no prompt/session transcript content and is never used for pane control. */
+export async function listInstalledHerdrSessions(herdrBin = 'herdr'): Promise<HerdrSessionListRow[]> {
+ const result = await exec(herdrBin, ['session', 'list', '--json'], {
+ timeout: 2_000,
+ maxBuffer: MAX_LIST_BYTES,
+ encoding: 'utf8',
+ })
+ return parseHerdrSessionList(result.stdout)
+}
+
+export async function resolveConfiguredHerdrSessions(
+ sessionNames: readonly string[],
+ list: () => Promise<HerdrSessionListRow[]> = listInstalledHerdrSessions,
+ resolveEndpoint: typeof resolveHerdrEndpoint = resolveHerdrEndpoint,
+): Promise<HerdrTargetResolution[]> {
+ let rows: HerdrSessionListRow[]
+ try {
+ rows = await list()
+ } catch {
+ return sessionNames.map((sessionName) => ({
+ state: 'unavailable',
+ sessionName,
+ reason: 'Herdr session discovery failed',
+ }))
+ }
+
+ const targets = await Promise.all(sessionNames.map(async (sessionName): Promise<HerdrTargetResolution> => {
+ const matches = rows.filter((row) => row.name === sessionName)
+ if (matches.length !== 1 || !matches[0].running) {
+ return { state: 'unavailable', sessionName, reason: 'configured Herdr session is not running' }
+ }
+ try {
+ return {
+ state: 'available',
+ sessionName,
+ endpoint: await resolveEndpoint({ sessionName, socketPath: matches[0].socket_path }),
+ }
+ } catch (error) {
+ return {
+ state: 'unavailable',
+ sessionName,
+ reason: error instanceof HerdrEndpointError
+ ? `configured Herdr endpoint failed validation (${error.code})`
+ : 'configured Herdr endpoint failed validation',
+ }
+ }
+ }))
+
+ const canonicalPaths = new Map<string, number>()
+ for (const target of targets) {
+ if (target.state === 'available') {
+ canonicalPaths.set(target.endpoint.socketPath, (canonicalPaths.get(target.endpoint.socketPath) ?? 0) + 1)
+ }
+ }
+ return targets.map((target) => target.state === 'available'
+ && (canonicalPaths.get(target.endpoint.socketPath) ?? 0) > 1
+ ? {
+ state: 'unavailable',
+ sessionName: target.sessionName,
+ reason: 'configured Herdr sessions resolve to the same canonical endpoint',
+ }
+ : target)
+}
diff --git a/cli/src/lib/hookAuth.spec.ts b/cli/src/lib/hookAuth.spec.ts
new file mode 100644
index 000000000..433d0455c
--- /dev/null
+++ b/cli/src/lib/hookAuth.spec.ts
@@ -0,0 +1,60 @@
+import { execFileSync, spawnSync } from 'node:child_process'
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, statSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { hookCredentialMatches, hookCredentialPath, loadOrCreateHookCredential, readHookCredential } from './hookAuth.js'
+
+const dirs: string[] = []
+afterEach(() => dirs.splice(0).forEach((dir) => rmSync(dir, { recursive: true, force: true })))
+
+describe('hook channel credential', () => {
+ it('creates and reuses a high-entropy mode-0600 credential', () => {
+ const root = mkdtempSync(join(tmpdir(), 'hook-auth-'))
+ dirs.push(root)
+ const dir = join(root, 'data')
+ mkdirSync(dir, { mode: 0o755 })
+ chmodSync(dir, 0o755)
+ const first = loadOrCreateHookCredential(dir)
+ expect(first).toHaveLength(43)
+ expect(loadOrCreateHookCredential(dir)).toBe(first)
+ expect(readHookCredential(dir)).toBe(first)
+ expect(statSync(dir).mode & 0o777).toBe(0o700)
+ expect(statSync(hookCredentialPath(dir)).mode & 0o777).toBe(0o600)
+ expect(hookCredentialMatches(first, first)).toBe(true)
+ expect(hookCredentialMatches(first, `${first.slice(0, -1)}x`)).toBe(false)
+ })
+
+ it('rejects a credential file with permissive mode', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'hook-auth-'))
+ dirs.push(dir)
+ loadOrCreateHookCredential(dir)
+ chmodSync(hookCredentialPath(dir), 0o644)
+ expect(readHookCredential(dir)).toBeNull()
+ })
+
+ it('refuses to read or create credentials in a group-writable state directory', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'hook-auth-'))
+ dirs.push(dir)
+ chmodSync(dir, 0o770)
+ expect(readHookCredential(dir)).toBeNull()
+ expect(() => loadOrCreateHookCredential(dir)).toThrow('unsafe owner, mode, or type')
+ })
+
+ it('rejects a credential FIFO without blocking', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'hook-auth-'))
+ dirs.push(dir)
+ execFileSync('mkfifo', [hookCredentialPath(dir)])
+ const script = `import('./src/lib/hookAuth.ts').then(({ readHookCredential }) => process.exit(readHookCredential(${JSON.stringify(dir)}) === null ? 0 : 2))`
+
+ const result = spawnSync(process.execPath, ['--import', 'tsx', '--eval', script], {
+ cwd: process.cwd(),
+ encoding: 'utf8',
+ timeout: 1_500,
+ })
+
+ expect(result.error).toBeUndefined()
+ expect(result.status).toBe(0)
+ expect(statSync(hookCredentialPath(dir)).isFIFO()).toBe(true)
+ })
+})
diff --git a/cli/src/lib/hookAuth.ts b/cli/src/lib/hookAuth.ts
new file mode 100644
index 000000000..448c6698c
--- /dev/null
+++ b/cli/src/lib/hookAuth.ts
@@ -0,0 +1,75 @@
+import { randomBytes, timingSafeEqual } from 'node:crypto'
+import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, openSync, readFileSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { secureStateDirectory } from './secureState.js'
+
+const FILE_NAME = 'hook-credential'
+const TOKEN_RE = /^[A-Za-z0-9_-]{43}$/
+
+export function hookCredentialPath(dataDir: string): string {
+ return join(dataDir, FILE_NAME)
+}
+
+function secureDataDirectory(dataDir: string): boolean {
+ try {
+ secureStateDirectory(dataDir, false)
+ return true
+ } catch {
+ return false
+ }
+}
+
+export function readHookCredential(dataDir: string): string | null {
+ let fd: number | null = null
+ try {
+ if (!secureDataDirectory(dataDir)) return null
+ const file = hookCredentialPath(dataDir)
+ fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
+ const stat = fstatSync(fd)
+ const uid = typeof process.getuid === 'function' ? process.getuid() : null
+ if (!stat.isFile() || stat.size > 128) return null
+ if (uid !== null && stat.uid !== uid) return null
+ if ((stat.mode & 0o777) !== 0o600) return null
+ const value = readFileSync(fd, 'utf8').trim()
+ return TOKEN_RE.test(value) ? value : null
+ } catch {
+ return null
+ } finally {
+ if (fd !== null) closeSync(fd)
+ }
+}
+
+export function loadOrCreateHookCredential(dataDir: string): string {
+ const existing = readHookCredential(dataDir)
+ if (existing) return existing
+ try {
+ secureStateDirectory(dataDir)
+ } catch {
+ throw new Error('hook credential directory has unsafe owner, mode, or type')
+ }
+ const value = randomBytes(32).toString('base64url')
+ const file = hookCredentialPath(dataDir)
+ let fd: number
+ try {
+ fd = openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)
+ } catch (error) {
+ const raced = readHookCredential(dataDir)
+ if (raced) return raced
+ throw error
+ }
+ try {
+ writeFileSync(fd, `${value}\n`)
+ fchmodSync(fd, 0o600)
+ fsyncSync(fd)
+ } finally {
+ closeSync(fd)
+ }
+ const directoryFd = openSync(dataDir, 'r')
+ try { fsyncSync(directoryFd) } finally { closeSync(directoryFd) }
+ return value
+}
+
+export function hookCredentialMatches(expected: string, supplied: unknown): boolean {
+ if (typeof supplied !== 'string' || supplied.length !== expected.length) return false
+ return timingSafeEqual(Buffer.from(expected), Buffer.from(supplied))
+}
diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.ts
index eb600bf58..0822603ef 100644
--- a/cli/src/lib/hooks.ts
+++ b/cli/src/lib/hooks.ts
@@ -284,22 +284,31 @@ function forkPluginSource(engine: 'opencode' | 'kilo', port: number): string {
const product = engine === 'kilo' ? 'Kilo' : 'OpenCode'
return `// session-register — auto-installed by the machine adapter. Binds this ${product} session to the
// local machine daemon (127.0.0.1:${port}) so it can be mirrored to web/device. No-op if machine isn't running.
+import { readFileSync } from "node:fs"
+const hookToken = () => { try { return readFileSync(${JSON.stringify(join(env.ADAPTER_DATA_DIR, 'hook-credential'))}, "utf8").trim() } catch { return "" } }
export const MachineRegister = async ({ directory, worktree, project }) => {
const seen = new Set()
const post = async (sessionID) => {
const pane = process.env.TMUX_PANE
- if (!pane || !sessionID || seen.has(sessionID)) return
+ const herdrPane = process.env.HERDR_PANE_ID
+ const token = hookToken()
+ if ((!pane && !herdrPane) || !token || !sessionID || seen.has(sessionID)) return
seen.add(sessionID)
try {
await fetch("http://127.0.0.1:${port}/api/hook/session-start", {
method: "POST",
- headers: { "content-type": "application/json" },
+ headers: { "content-type": "application/json", "x-harness-hook-token": token },
body: JSON.stringify({
engine: "${engine}",
pluginVersion: ${JSON.stringify(VERSION)},
sessionId: sessionID,
cwd: directory || worktree || (project && project.worktree) || null,
tmuxPane: pane,
+ callerPid: process.pid,
+ runtimeHints: [
+ ...(pane ? [{ backend: "tmux", paneId: pane }] : []),
+ ...(herdrPane ? [{ backend: "herdr", paneId: herdrPane, sessionName: process.env.HERDR_SESSION, socketPath: process.env.HERDR_SOCKET_PATH }] : []),
+ ],
}),
})
} catch {}
@@ -552,7 +561,7 @@ const PI_EXTENSION_PATH = join(env.PI_HOME, 'agent', 'extensions', 'launcher-reg
function piExtensionSource(port: number): string {
return `// session-register — auto-installed by the machine adapter. Binds this Pi session to the local
// machine daemon (127.0.0.1:${port}) so it can be mirrored to web/device. No-op if machine isn't running.
-import { existsSync } from "node:fs";
+import { existsSync, readFileSync } from "node:fs";
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
export default function (pi: ExtensionAPI) {
@@ -561,7 +570,10 @@ export default function (pi: ExtensionAPI) {
const register = async (ctx: any) => {
const pane = process.env.TMUX_PANE;
- if (!pane) return; // tmux-only, like every other engine
+ const herdrPane = process.env.HERDR_PANE_ID;
+ let token = "";
+ try { token = readFileSync(${JSON.stringify(join(env.ADAPTER_DATA_DIR, 'hook-credential'))}, "utf8").trim(); } catch {}
+ if ((!pane && !herdrPane) || !token) return;
// Pi knows the session file path immediately but only WRITES it once the first assistant message
// lands. Sending a path that isn't on disk yet is rejected by the daemon (it validates the file),
// so announce without one first and attach the real path on a later turn.
@@ -573,7 +585,7 @@ export default function (pi: ExtensionAPI) {
try {
const res = await fetch("http://127.0.0.1:${port}/api/hook/session-start", {
method: "POST",
- headers: { "content-type": "application/json" },
+ headers: { "content-type": "application/json", "x-harness-hook-token": token },
body: JSON.stringify({
engine: "pi",
pluginVersion: ${JSON.stringify(VERSION)},
@@ -581,6 +593,11 @@ export default function (pi: ExtensionAPI) {
transcriptPath: ready ? file : undefined,
cwd: ctx?.cwd ?? undefined,
tmuxPane: pane,
+ callerPid: process.pid,
+ runtimeHints: [
+ ...(pane ? [{ backend: "tmux", paneId: pane }] : []),
+ ...(herdrPane ? [{ backend: "herdr", paneId: herdrPane, sessionName: process.env.HERDR_SESSION, socketPath: process.env.HERDR_SOCKET_PATH }] : []),
+ ],
}),
});
if (!res.ok) return; // daemon refused (e.g. transcript not readable yet) — retry on the next turn
@@ -658,7 +675,7 @@ function ampPluginSource(port: number, sessionsDir: string): string {
return `// session-register — auto-installed by the machine adapter. Binds this Amp thread to the local
// machine daemon (127.0.0.1:${port}) and writes the transcript the daemon tails, because Amp keeps none
// on disk. No-op outside tmux.
-import { appendFileSync, existsSync, mkdirSync } from 'node:fs'
+import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
export const description = 'Mirrors this Amp thread to the machine adapter (web + device)'
@@ -667,7 +684,8 @@ const SESSIONS_DIR = ${JSON.stringify(sessionsDir)}
export default function (amp: any) {
const pane = process.env.TMUX_PANE
- if (!pane) return
+ const herdrPane = process.env.HERDR_PANE_ID
+ if (!pane && !herdrPane) return
// NOT \`process.cwd()\`: Bun runs a plugin with the PLUGIN's directory as its cwd, so that reports
// \`<project>/.amp/plugins\` (measured). \`PWD\` is inherited from the shell that launched plain Amp.
@@ -706,9 +724,11 @@ export default function (amp: any) {
open(threadId)
if (registered || !existsSync(file)) return
try {
+ const token = readFileSync(${JSON.stringify(join(env.ADAPTER_DATA_DIR, 'hook-credential'))}, 'utf8').trim()
+ if (!token) return
const res = await fetch('http://127.0.0.1:${port}/api/hook/session-start', {
method: 'POST',
- headers: { 'content-type': 'application/json' },
+ headers: { 'content-type': 'application/json', 'x-harness-hook-token': token },
body: JSON.stringify({
engine: 'amp',
pluginVersion: ${JSON.stringify(VERSION)},
@@ -716,6 +736,11 @@ export default function (amp: any) {
transcriptPath: file,
cwd: workdir,
tmuxPane: pane,
+ callerPid: process.pid,
+ runtimeHints: [
+ ...(pane ? [{ backend: 'tmux', paneId: pane }] : []),
+ ...(herdrPane ? [{ backend: 'herdr', paneId: herdrPane, sessionName: process.env.HERDR_SESSION, socketPath: process.env.HERDR_SOCKET_PATH }] : []),
+ ],
}),
})
if (res.ok) registered = true
diff --git a/cli/src/lib/oneshot.ts b/cli/src/lib/oneshot.ts
index 244aa3078..6b3d9030a 100644
--- a/cli/src/lib/oneshot.ts
+++ b/cli/src/lib/oneshot.ts
@@ -15,6 +15,7 @@ import {
type DisposableWorker,
type OneShotEngine,
} from './disposableOneShotPool.js'
+import { scrubTerminalContext } from './terminalEnvironment.js'
function claudeBin(): string {
return env.CLAUDE_PATH || 'claude'
@@ -286,9 +287,7 @@ class CodexWorker extends ProcessWorker {
...(effort ? ['-c', `model_reasoning_effort="${effort}"`] : []),
'-',
]
- const processEnv = { ...process.env }
- delete processEnv.TMUX
- delete processEnv.TMUX_PANE
+ const processEnv = scrubTerminalContext({ ...process.env })
const child = spawn(process.env.CODEX_PATH || 'codex', args, {
cwd, env: processEnv, detached: true, stdio: ['pipe', 'ignore', 'pipe'],
})
@@ -377,9 +376,7 @@ class CursorWorker extends ProcessWorker {
'--output-format', 'stream-json',
...(model ? ['--model', model] : []),
]
- const processEnv = { ...process.env }
- delete processEnv.TMUX
- delete processEnv.TMUX_PANE
+ const processEnv = scrubTerminalContext({ ...process.env })
const child = spawn(cursorBin(), args, {
cwd, env: processEnv, detached: true, stdio: ['pipe', 'pipe', 'pipe'],
})
@@ -503,9 +500,7 @@ class OpencodeWorker extends ProcessWorker {
// self-registers this ephemeral recap session). `--format json` streams `{type:'text',part:{text}}`.
mkdirSync(OPENCODE_RECAP_DATA_DIR, { recursive: true })
const args = ['run', '--pure', '--format', 'json', ...(model ? ['--model', model] : [])]
- const processEnv = { ...process.env }
- delete processEnv.TMUX
- delete processEnv.TMUX_PANE
+ const processEnv = scrubTerminalContext({ ...process.env })
processEnv.OPENCODE_DATA_DIR = OPENCODE_RECAP_DATA_DIR
const child = spawn(opencodeBin(), args, {
cwd: OPENCODE_RECAP_DATA_DIR, env: processEnv, detached: true, stdio: ['pipe', 'pipe', 'pipe'],
@@ -615,9 +610,7 @@ export function kiloOneShotSpawn(
'run', '--pure', '--auto', '--format', 'json', '--dir', dataDir,
...(model ? ['--model', model] : []),
]
- const childEnv = { ...parentEnv }
- delete childEnv.TMUX
- delete childEnv.TMUX_PANE
+ const childEnv = scrubTerminalContext({ ...parentEnv })
childEnv.XDG_DATA_HOME = dataDir
// Belt and braces with `--dir`. `spawn({cwd})` does NOT rewrite `PWD`, and kilo resolves its project
// from that variable, so without this the child inherits the DAEMON's directory.
@@ -754,9 +747,7 @@ class PiWorker extends ProcessWorker {
// answer, so the worker can be pre-warmed and fed later. `--no-session` keeps the recap out of the
// user's session store; `--no-extensions` stops the machine discovery extension from registering it.
const args = ['-p', '--no-session', '--no-extensions', ...(model ? ['--model', model] : [])]
- const processEnv = { ...process.env }
- delete processEnv.TMUX
- delete processEnv.TMUX_PANE
+ const processEnv = scrubTerminalContext({ ...process.env })
const child = spawn(piBin(), args, {
cwd, env: processEnv, detached: true, stdio: ['pipe', 'pipe', 'pipe'],
})
@@ -831,12 +822,10 @@ class CommandCodeWorker extends ProcessWorker {
constructor(cwd: string, model?: string) {
// `commandcode -p` reads the prompt from piped stdin (verified), so the worker pre-warms and is fed
// later. `--no-session` keeps the recap out of the user's project/session list — without it every
- // recap shows up as a session. There is no --no-hooks flag; the scrubbed TMUX_PANE below is what
+ // recap shows up as a session. There is no --no-hooks flag; the scrubbed terminal context below
// stops our own SessionStart hook registering this process.
const args = ['-p', '--no-session', ...(model ? ['-m', model] : [])]
- const processEnv = { ...process.env }
- delete processEnv.TMUX
- delete processEnv.TMUX_PANE
+ const processEnv = scrubTerminalContext({ ...process.env })
const child = spawn(commandCodeBin(), args, {
cwd, env: processEnv, detached: true, stdio: ['pipe', 'pipe', 'pipe'],
})
@@ -1014,9 +1003,7 @@ export function grokOneShotSpawn(
...(opts.effort ? ['--reasoning-effort', opts.effort] : []),
'-p', opts.prompt,
]
- const childEnv: NodeJS.ProcessEnv = { ...parentEnv, GROK_HOME: scratchHome }
- delete childEnv.TMUX
- delete childEnv.TMUX_PANE
+ const childEnv: NodeJS.ProcessEnv = scrubTerminalContext({ ...parentEnv, GROK_HOME: scratchHome })
delete childEnv.MACHINE_ID
return { args, env: childEnv }
}
@@ -1103,8 +1090,8 @@ function hermesBin(): string {
*
* Notably we do NOT pass `--safe-mode`: it implies `--ignore-user-config`, which would discard the
* user's model/provider (their whole reason for a working recap). Self-registration is prevented the
- * same way every other worker does it — `TMUX`/`TMUX_PANE` are scrubbed, and the machine hook only
- * registers a session that has a tmux pane. `--source tool` keeps it out of the user's session list.
+ * same way every other worker does it: every terminal location variable is scrubbed. `--source tool`
+ * keeps it out of the user's session list.
*/
function museBin(): string {
return env.MUSE_PATH || 'muse'
@@ -1115,15 +1102,13 @@ function museBin(): string {
*
* Prompt goes as ARGV (muse has no stdin mode), so this worker cannot be pre-warmed the way a stdin-fed
* CLI can — it is deliberately outside the pool. `--json` is not used: the recap wants the answer, not
- * the event stream. TMUX vars are stripped so the worker cannot register itself as an agent, and
+ * the event stream. Terminal context is stripped so the worker cannot register itself as an agent, and
* MUSE_NO_AUTO_UPDATE keeps a background self-update from swapping the binary mid-run.
*/
export function runMuseOneShot(opts: OneShotOptions): Promise<OneShotResult> {
if (opts.signal?.aborted) return Promise.reject(Object.assign(new Error('muse one-shot aborted'), { name: 'AbortError' }))
const args = ['exec', opts.prompt, ...(opts.model ? ['--model', opts.model] : [])]
- const processEnv: NodeJS.ProcessEnv = { ...process.env, MUSE_NO_AUTO_UPDATE: '1' }
- delete processEnv.TMUX
- delete processEnv.TMUX_PANE
+ const processEnv: NodeJS.ProcessEnv = scrubTerminalContext({ ...process.env, MUSE_NO_AUTO_UPDATE: '1' })
const timeoutMs = opts.timeoutMs ?? 60_000
return new Promise<OneShotResult>((resolve, reject) => {
@@ -1177,7 +1162,7 @@ export function runMuseOneShot(opts: OneShotOptions): Promise<OneShotResult> {
* is what chooses one. `low` is both the cheapest and plenty for a one-sentence recap.
*
* Self-registration is prevented twice over. The adapter's Amp plugin already refuses to do anything
- * without `MACHINE_ID` and `TMUX_PANE`, and both are scrubbed here; `AMP_DISABLE_PLUGINS` then stops it
+ * without machine and terminal context, and both are scrubbed here; `AMP_DISABLE_PLUGINS` then stops it
* loading at all, which also keeps a user's own plugins out of a recap. `-x` archives the thread it
* creates once it finishes, so recaps do not accumulate in the user's thread list.
*/
@@ -1192,9 +1177,7 @@ export function runMuseOneShot(opts: OneShotOptions): Promise<OneShotResult> {
*/
function ampOneShotAttempt(opts: OneShotOptions, timeoutMs: number): Promise<OneShotResult | null> {
const args = ['-x', '--no-notifications', '-m', opts.model || env.AMP_SUMMARY_MODE]
- const processEnv: NodeJS.ProcessEnv = { ...process.env, AMP_DISABLE_PLUGINS: '1' }
- delete processEnv.TMUX
- delete processEnv.TMUX_PANE
+ const processEnv: NodeJS.ProcessEnv = scrubTerminalContext({ ...process.env, AMP_DISABLE_PLUGINS: '1' })
delete processEnv.MACHINE_ID
return new Promise<OneShotResult | null>((resolve, reject) => {
@@ -1259,9 +1242,7 @@ export async function runAmpOneShot(opts: OneShotOptions): Promise<OneShotResult
export function runHermesOneShot(opts: OneShotOptions): Promise<OneShotResult> {
if (opts.signal?.aborted) return Promise.reject(Object.assign(new Error('hermes one-shot aborted'), { name: 'AbortError' }))
const args = ['chat', '-q', opts.prompt, '-Q', '--source', 'tool', ...(opts.model ? ['-m', opts.model] : [])]
- const processEnv = { ...process.env }
- delete processEnv.TMUX
- delete processEnv.TMUX_PANE
+ const processEnv = scrubTerminalContext({ ...process.env })
const timeoutMs = opts.timeoutMs ?? 60_000
return new Promise<OneShotResult>((resolve, reject) => {
@@ -1317,16 +1298,14 @@ function devinBin(): string {
* so a worker cannot be pre-warmed and Devin is deliberately absent from `OneShotEngine`/the warm pool.
*
* `devin -p "<prompt>"` prints just the answer and exits 0. There is no `--no-session` equivalent, so the
- * recap does leave a row in `sessions.db`; it cannot register as an agent, because `TMUX`/`TMUX_PANE` are
- * scrubbed and the machine hook only registers a session that has a tmux pane.
+ * recap does leave a row in `sessions.db`; it cannot register as an agent because every terminal
+ * location variable is scrubbed.
*/
export function runDevinOneShot(opts: OneShotOptions): Promise<OneShotResult> {
if (opts.signal?.aborted) return Promise.reject(Object.assign(new Error('devin one-shot aborted'), { name: 'AbortError' }))
if (opts.cwd) trustDevinWorkspace(opts.cwd, (m) => console.warn('[recap] could not trust the devin scratch dir:', m))
const args = ['-p', opts.prompt, ...(opts.model ? ['--model', opts.model] : [])]
- const processEnv = { ...process.env }
- delete processEnv.TMUX
- delete processEnv.TMUX_PANE
+ const processEnv = scrubTerminalContext({ ...process.env })
const timeoutMs = opts.timeoutMs ?? 60_000
return new Promise<OneShotResult>((resolve, reject) => {
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index 3d56183e6..a53b6831c 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import type { AgentEngine } from '../engines/types.js'
@@ -13,6 +13,11 @@ const processIdentity = (pid: number) => ({
startMarker: `Mon Aug 10 10:00:${String(pid % 60).padStart(2, '0')} 2026`,
})
+function writeLegacyStateFile(path: string, value: string): void {
+ writeFileSync(path, value, { mode: 0o644 })
+ chmodSync(path, 0o644)
+}
+
function registerProcess(
registry: {
byPaneEngine: (pane: string, engine: AgentEngine) => RegisteredSession | undefined
@@ -98,8 +103,9 @@ describe('registry remote display names', () => {
it('loads persisted names for active sessions', async () => {
const transcriptPath = join(dataDir, 'session-2.jsonl')
writeFileSync(transcriptPath, '{}\n')
- writeFileSync(join(dataDir, 'agent-names.json'), JSON.stringify({ 'session-2': 'Research box' }))
- writeFileSync(join(dataDir, 'registry.json'), JSON.stringify([{
+ chmodSync(dataDir, 0o755)
+ writeLegacyStateFile(join(dataDir, 'agent-names.json'), JSON.stringify({ 'session-2': 'Research box' }))
+ writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([{
launcherId: 'h1',
sessionId: 'session-2',
transcriptPath,
@@ -124,6 +130,9 @@ describe('registry remote display names', () => {
engine: 'claude',
tmuxPane: '%2',
})
+ expect(statSync(dataDir).mode & 0o777).toBe(0o700)
+ expect(statSync(join(dataDir, 'agent-names.json')).mode & 0o777).toBe(0o600)
+ expect(statSync(join(dataDir, 'registry.json')).mode & 0o777).toBe(0o600)
})
it('auto-follows the tmux pane title until renamed, then the manual name stays fixed', async () => {
@@ -162,7 +171,7 @@ describe('registry remote display names', () => {
it('only adds or updates agent-names.json entries', async () => {
const transcriptPath = join(dataDir, 'session-3.jsonl')
writeFileSync(transcriptPath, '{}\n')
- writeFileSync(join(dataDir, 'agent-names.json'), JSON.stringify({ old: 'Keep me' }))
+ writeLegacyStateFile(join(dataDir, 'agent-names.json'), JSON.stringify({ old: 'Keep me' }))
const { registry } = await loadRegistryModule()
registry.load()
@@ -175,7 +184,7 @@ describe('registry remote display names', () => {
})
})
- it('persists Codex engine metadata and rejects records without a valid pane', async () => {
+ it('persists Codex engine metadata and preserves a malformed v2 row for operator recovery', async () => {
const sessionsDir = join(dataDir, 'sessions')
const transcriptPath = join(sessionsDir, 'codex-session.jsonl')
mkdirSync(sessionsDir)
@@ -195,13 +204,205 @@ describe('registry remote display names', () => {
expect(valid?.engine).toBe('codex')
const persisted = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))
- persisted.push({ ...persisted[0], sessionId: 'invalid-session', tmuxPane: 'not-a-pane' })
- writeFileSync(join(dataDir, 'registry.json'), JSON.stringify(persisted))
+ persisted.push({
+ ...persisted[0],
+ sessionId: 'invalid-session',
+ tmuxPane: 'not-a-pane',
+ runtimes: [{ backend: 'tmux', paneId: 'not-a-pane' }],
+ })
+ const malformed = JSON.stringify(persisted)
+ writeFileSync(join(dataDir, 'registry.json'), malformed)
registry.load()
- expect(registry.get('codex-session')?.engine).toBe('codex')
+ expect(registry.list()).toEqual([])
expect(registry.get('invalid-session')).toBeUndefined()
- expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))).toHaveLength(1)
+ expect(readFileSync(join(dataDir, 'registry.json'), 'utf-8')).toBe(malformed)
+ })
+
+ it('migrates legacy tmux rows additively without changing agent identity or binding', async () => {
+ const transcriptPath = join(dataDir, 'legacy.jsonl')
+ writeFileSync(transcriptPath, '{}\n')
+ writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([{
+ agentId: 'stable-agent',
+ sessionId: 'legacy-session',
+ engine: 'claude',
+ transcriptPath,
+ projectDir: 'demo',
+ cwd: '/tmp/demo',
+ tmuxPane: '%17',
+ processIdentity: processIdentity(317),
+ registeredAt: 10,
+ updatedAt: 20,
+ }]))
+
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ expect(registry.get('legacy-session')).toMatchObject({
+ agentId: 'stable-agent',
+ tmuxPane: '%17',
+ runtimes: [{ backend: 'tmux', paneId: '%17' }],
+ schemaVersion: 2,
+ })
+ expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))[0]).toMatchObject({
+ agentId: 'stable-agent',
+ tmuxPane: '%17',
+ runtimes: [{ backend: 'tmux', paneId: '%17' }],
+ })
+ expect(JSON.parse(readFileSync(join(dataDir, 'registry.pre-v2.json'), 'utf8'))[0]).toMatchObject({
+ agentId: 'stable-agent', sessionId: 'legacy-session', tmuxPane: '%17',
+ })
+ expect(statSync(join(dataDir, 'registry.pre-v2.json')).mode & 0o777).toBe(0o600)
+ })
+
+ it.each([
+ ['truncated JSON', '[{"agentId":'],
+ ['non-array root', '{"schemaVersion":2}'],
+ ['unknown row schema', JSON.stringify([{ schemaVersion: 99, agentId: 'future' }])],
+ ['nonnumeric row schema', JSON.stringify([{ schemaVersion: '3', agentId: 'future' }])],
+ ['empty legacy row', JSON.stringify([{}])],
+ ['primitive legacy row', JSON.stringify([7])],
+ ['legacy row without runtime', JSON.stringify([{ agentId: 'legacy-agent' }])],
+ ])('preserves %s byte-for-byte and blocks later writes', async (_label, bytes) => {
+ const file = join(dataDir, 'registry.json')
+ writeLegacyStateFile(file, bytes)
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ registry.openProcessAgent({
+ agentId: 'must-not-write',
+ engine: 'claude',
+ tmuxPane: '%88',
+ processIdentity: processIdentity(888),
+ })
+ expect(readFileSync(file, 'utf8')).toBe(bytes)
+ expect(registry.list()).toEqual([])
+ })
+
+ it('rejects a group-writable registry without tightening or overwriting it', async () => {
+ const file = join(dataDir, 'registry.json')
+ const bytes = '[]'
+ writeFileSync(file, bytes, { mode: 0o600 })
+ chmodSync(file, 0o660)
+
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ registry.openProcessAgent({
+ agentId: 'must-not-write',
+ engine: 'claude',
+ tmuxPane: '%89',
+ processIdentity: processIdentity(889),
+ })
+
+ expect(readFileSync(file, 'utf8')).toBe(bytes)
+ expect(statSync(file).mode & 0o777).toBe(0o660)
+ expect(registry.list()).toEqual([])
+ })
+
+ it('merges a daemon-down writer committed after load instead of overwriting it', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ registry.openProcessAgent({
+ agentId: 'daemon-agent', engine: 'claude', tmuxPane: '%31', processIdentity: processIdentity(831),
+ })
+ const file = join(dataDir, 'registry.json')
+ const [daemonRow] = JSON.parse(readFileSync(file, 'utf8')) as Array<Record<string, unknown>>
+ const external = {
+ ...daemonRow,
+ agentId: 'offline-agent',
+ sessionId: '',
+ tmuxPane: '%32',
+ runtimes: [{ backend: 'tmux', paneId: '%32' }],
+ primaryRuntimeKey: 'tmux\u0000%32',
+ processIdentity: processIdentity(832),
+ }
+ writeFileSync(file, JSON.stringify([daemonRow, external]), { mode: 0o600 })
+
+ registry.updateTitle('daemon-agent', 'updated by daemon')
+
+ expect(JSON.parse(readFileSync(file, 'utf8'))).toHaveLength(2)
+ expect(registry.byAgent('offline-agent')?.processIdentity?.pid).toBe(832)
+ expect(registry.byAgent('daemon-agent')?.title).toBe('updated by daemon')
+ })
+
+ it('reclaims a crashed lock whose PID has been reused by another process generation', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const lockDir = join(dataDir, 'registry.json.lock')
+ mkdirSync(lockDir, { mode: 0o700 })
+ writeFileSync(join(lockDir, 'owner.json'), JSON.stringify({
+ pid: process.pid,
+ startMarker: 'different-process-generation',
+ token: 'stale-owner',
+ }), { mode: 0o600 })
+
+ expect(registry.openProcessAgent({
+ agentId: 'after-reused-pid-lock',
+ engine: 'claude',
+ tmuxPane: '%33',
+ processIdentity: processIdentity(833),
+ })?.entry.agentId).toBe('after-reused-pid-lock')
+ expect(registry.byAgent('after-reused-pid-lock')).toBeTruthy()
+ })
+
+ it('deduplicates nested backends by process identity while scoping Herdr routes to endpoints', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const identity = processIdentity(700)
+ const tmux = registry.openProcessAgent({
+ agentId: 'nested-agent',
+ engine: 'claude',
+ tmuxPane: '%7',
+ processIdentity: identity,
+ })
+ const herdrRuntime = {
+ backend: 'herdr' as const,
+ endpointId: 'herdr:default:abc',
+ sessionName: 'default',
+ terminalId: 'terminal-a',
+ paneId: 'w1:p1',
+ }
+ const nested = registry.openProcessAgent({
+ engine: 'claude',
+ runtimes: [herdrRuntime],
+ processIdentity: identity,
+ })
+ const other = registry.openProcessAgent({
+ agentId: 'other-endpoint-agent',
+ engine: 'claude',
+ runtimes: [{ ...herdrRuntime, endpointId: 'herdr:work:def', sessionName: 'work', terminalId: 'terminal-b' }],
+ processIdentity: processIdentity(701),
+ })
+
+ expect(nested?.entry.agentId).toBe(tmux?.entry.agentId)
+ expect(nested?.entry.runtimes).toHaveLength(2)
+ expect(other?.entry.agentId).toBe('other-endpoint-agent')
+ expect(registry.list()).toHaveLength(2)
+ })
+
+ it('persists Herdr-only rows without a legacy tmuxPane projection', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ registry.openProcessAgent({
+ agentId: 'herdr-agent',
+ engine: 'codex',
+ runtimes: [{
+ backend: 'herdr',
+ endpointId: 'herdr:default:abc',
+ sessionName: 'default',
+ terminalId: 'terminal-1',
+ paneId: 'w1:p1',
+ }],
+ processIdentity: processIdentity(900),
+ })
+
+ const [persisted] = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))
+ expect(persisted).not.toHaveProperty('tmuxPane')
+ expect(persisted).toMatchObject({
+ schemaVersion: 2,
+ agentId: 'herdr-agent',
+ runtimes: [{ backend: 'herdr', endpointId: 'herdr:default:abc', paneId: 'w1:p1' }],
+ })
+ registry.load()
+ expect(registry.byAgent('herdr-agent')?.runtimes[0]).toMatchObject({ backend: 'herdr', terminalId: 'terminal-1' })
})
it('repairs a Codex parent registry entry overwritten with a child rollout', async () => {
@@ -222,7 +423,7 @@ describe('registry remote display names', () => {
source: { subagent: { thread_spawn: { parent_thread_id: parentId, depth: 1 } } },
},
}) + '\n')
- writeFileSync(join(dataDir, 'registry.json'), JSON.stringify([{
+ writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([{
launcherId: 'h1',
sessionId: parentId,
engine: 'codex',
@@ -610,7 +811,7 @@ describe('agent identity: the process owns the agent, the session is bound to it
// uuid IS the agent id.
const path = transcript('legacy')
const now = Date.now()
- writeFileSync(join(dataDir, 'registry.json'), JSON.stringify([{
+ writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([{
sessionId: 'legacy-session', engine: 'claude', launcherId: 'legacy-agent', transcriptPath: path,
projectDir: 'x', cwd: '/tmp/demo', tmuxPane: '%3', source: null, title: null, model: null,
cliVersion: null, processIdentity: null, registeredAt: now, updatedAt: now,
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 93bd4c2e9..68177654d 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -13,7 +13,23 @@
* Module singleton (like the ws `clients` set) — imported by routes + reaper.
*/
-import { mkdirSync, readFileSync, writeFileSync, renameSync, realpathSync, statSync } from 'fs'
+import {
+ closeSync,
+ constants,
+ existsSync,
+ fchmodSync,
+ fsyncSync,
+ lstatSync,
+ mkdirSync,
+ openSync,
+ readFileSync,
+ realpathSync,
+ renameSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+} from 'fs'
+import { execFileSync } from 'node:child_process'
import { randomUUID } from 'crypto'
import { join, basename, dirname, relative } from 'path'
import { uptime } from 'os'
@@ -21,12 +37,11 @@ import { env } from '../config/env.js'
import { readCodexRolloutMeta, resolveCodexRollout } from '../engines/codex/rollout.js'
import type { AgentEngine } from '../engines/types.js'
import { commandcodeTranscriptPath } from '../engines/commandcode/transcript.js'
+import { hardenPrivateStateFileIfPresent, readPrivateStateFile, secureStateDirectory } from './secureState.js'
+import { mergeTerminalRuntimes, processIdentityKey, terminalPlacementKey, terminalRouteKey } from './terminalRuntime.js'
+import type { HookTerminalHint, ProcessIdentity, TerminalRuntimeRef } from './terminalTypes.js'
-export interface ProcessIdentity {
- pid: number
- executable: string
- startMarker: string
-}
+export type { ProcessIdentity } from './terminalTypes.js'
/** Claude Code's hooks report `model` as {id, display_name}; Codex/Cursor report a plain string. This is
* the boundary where hook JSON becomes persisted state, so anything else is dropped rather than stored —
@@ -39,6 +54,10 @@ function modelString(value: unknown): string | null {
}
export interface RegisteredSession {
+ /** Per-row marker; the top-level array is retained for backward-reader safety. */
+ schemaVersion: 2
+ /** Dormant records retain identity/bindings but are not advertised until a runtime is verified again. */
+ active: boolean
/**
* THE AGENT. Public identity: this is what web tabs, device tiles and every inbound frame address.
*
@@ -59,6 +78,10 @@ export interface RegisteredSession {
transcriptPath: string | null
projectDir: string
cwd: string | null
+ /** Authoritative backend-neutral terminal placements for this one process-owned agent. */
+ runtimes: TerminalRuntimeRef[]
+ primaryRuntimeKey: string
+ /** Additive rollback/wire projection. Empty in memory and omitted on disk for Herdr-only agents. */
tmuxPane: string
source: string | null
title: string | null
@@ -84,6 +107,11 @@ export interface RegisterInput {
model?: string
cliVersion?: string
processIdentity?: ProcessIdentity
+ /** New authenticated hooks may supply resolved runtime hints. Legacy hooks continue to use tmuxPane. */
+ runtimes?: TerminalRuntimeRef[]
+ primaryRuntimeKey?: string
+ runtimeHints?: HookTerminalHint[]
+ callerPid?: number
hookEvent?: string
}
@@ -98,10 +126,305 @@ export function projectDisplayName(s: RegisteredSession): string {
const FILE = join(env.ADAPTER_DATA_DIR, 'registry.json')
const NAMES_FILE = join(env.ADAPTER_DATA_DIR, 'agent-names.json')
const BOOT_FILE = join(env.ADAPTER_DATA_DIR, 'registry-boot')
+const LOCK_DIR = join(env.ADAPTER_DATA_DIR, 'registry.json.lock')
+const PRE_V2_BACKUP_FILE = join(env.ADAPTER_DATA_DIR, 'registry.pre-v2.json')
const NAME_OVERRIDES = new Map<string, string>()
const PANE_RE = /^%\d+$/
const GROK_SESSION_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
+const AGENT_ENGINES = new Set<AgentEngine>([
+ 'claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin', 'muse', 'amp', 'kilo', 'grok',
+])
+const LOCK_WAIT_MS = 20
+const LOCK_ATTEMPTS = 100
+
+function sleepSync(ms: number): void {
+ const view = new Int32Array(new SharedArrayBuffer(4))
+ Atomics.wait(view, 0, 0, ms)
+}
+
+function processExists(pid: number): boolean {
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false
+ try { process.kill(pid, 0); return true } catch (error) {
+ return (error as NodeJS.ErrnoException).code === 'EPERM'
+ }
+}
+
+function processStartMarker(pid: number): string | null {
+ if (!Number.isSafeInteger(pid) || pid <= 0) return null
+ try {
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8')
+ const fields = stat.slice(stat.lastIndexOf(')') + 2).trim().split(/\s+/)
+ if (fields[19]) return `linux:${fields[19]}`
+ } catch { /* non-Linux or exited process; use ps below */ }
+ try {
+ const started = execFileSync('ps', ['-p', String(pid), '-o', 'lstart='], {
+ encoding: 'utf8', timeout: 1_000,
+ }).trim()
+ return started ? `ps:${started}` : null
+ } catch { return null }
+}
+
+function lockOwnerAlive(pid: number, startMarker: string): boolean {
+ if (!processExists(pid)) return false
+ if (!startMarker) return true
+ const current = processStartMarker(pid)
+ return current === null || current === startMarker
+}
+
+function removeRegistryLockOwnedBy(token: string): void {
+ try {
+ const saved = JSON.parse(readFileSync(join(LOCK_DIR, 'owner.json'), 'utf8')) as { token?: unknown }
+ if (saved.token === token) rmSync(LOCK_DIR, { recursive: true, force: true })
+ } catch { /* another owner or an unsafe artifact must not be removed */ }
+}
+
+function withRegistryFileLock<T>(apply: () => T): T {
+ secureStateDirectory(env.ADAPTER_DATA_DIR)
+ const uid = typeof process.getuid === 'function' ? process.getuid() : null
+ const processMarker = processStartMarker(process.pid) ?? ''
+ for (let attempt = 0; attempt < LOCK_ATTEMPTS; attempt++) {
+ const token = randomUUID()
+ let created = false
+ try {
+ mkdirSync(LOCK_DIR, { mode: 0o700 })
+ created = true
+ const owner = join(LOCK_DIR, 'owner.json')
+ const fd = openSync(owner, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)
+ try {
+ writeFileSync(fd, JSON.stringify({ pid: process.pid, startMarker: processMarker, token }))
+ fsyncSync(fd)
+ } finally { closeSync(fd) }
+ try {
+ return apply()
+ } finally {
+ removeRegistryLockOwnedBy(token)
+ }
+ } catch (error) {
+ if (created) removeRegistryLockOwnedBy(token)
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
+ let ownerPid = 0
+ let ownerStartMarker = ''
+ let ownerToken = ''
+ try {
+ const stat = lstatSync(LOCK_DIR)
+ if (!stat.isDirectory() || stat.isSymbolicLink() || (uid !== null && stat.uid !== uid)
+ || (stat.mode & 0o777) !== 0o700) throw new Error('registry lock has unsafe owner, mode, or type')
+ const ownerStat = lstatSync(join(LOCK_DIR, 'owner.json'))
+ if (!ownerStat.isFile() || ownerStat.isSymbolicLink() || (uid !== null && ownerStat.uid !== uid)
+ || (ownerStat.mode & 0o777) !== 0o600) throw new Error('registry lock owner has unsafe owner, mode, or type')
+ const owner = JSON.parse(readFileSync(join(LOCK_DIR, 'owner.json'), 'utf8')) as {
+ pid?: unknown; startMarker?: unknown; token?: unknown
+ }
+ ownerPid = Number(owner.pid)
+ ownerStartMarker = typeof owner.startMarker === 'string' ? owner.startMarker : ''
+ ownerToken = typeof owner.token === 'string' ? owner.token : ''
+ } catch (inspectionError) {
+ if (inspectionError instanceof Error && inspectionError.message.startsWith('registry lock')) throw inspectionError
+ }
+ if (ownerPid > 0 && ownerToken && !lockOwnerAlive(ownerPid, ownerStartMarker)) {
+ try {
+ const current = JSON.parse(readFileSync(join(LOCK_DIR, 'owner.json'), 'utf8')) as {
+ pid?: unknown; startMarker?: unknown; token?: unknown
+ }
+ if (Number(current.pid) === ownerPid
+ && current.startMarker === ownerStartMarker
+ && current.token === ownerToken
+ && !lockOwnerAlive(ownerPid, ownerStartMarker)) {
+ rmSync(LOCK_DIR, { recursive: true, force: true })
+ continue
+ }
+ } catch { /* lock changed or disappeared; retry without deleting another owner's lock */ }
+ }
+ sleepSync(LOCK_WAIT_MS)
+ }
+ }
+ throw new Error('registry lock is busy')
+}
+
+function rowId(row: unknown): string {
+ if (!row || typeof row !== 'object') return ''
+ const candidate = row as { agentId?: unknown; launcherId?: unknown }
+ return typeof candidate.agentId === 'string' && candidate.agentId
+ ? candidate.agentId
+ : typeof candidate.launcherId === 'string' ? candidate.launcherId : ''
+}
+
+function rowFingerprint(row: unknown): string {
+ return JSON.stringify(row)
+}
+
+function atomicWriteJson(file: string, value: unknown, exclusive = false): void {
+ const exists = hardenPrivateStateFileIfPresent(file)
+ if (exclusive && exists) return
+ const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`
+ let renamed = false
+ try {
+ const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)
+ try {
+ writeFileSync(fd, JSON.stringify(value, null, 2))
+ fchmodSync(fd, 0o600)
+ fsyncSync(fd)
+ } finally { closeSync(fd) }
+ renameSync(temporary, file)
+ renamed = true
+ const directoryFd = openSync(dirname(file), 'r')
+ try { fsyncSync(directoryFd) } finally { closeSync(directoryFd) }
+ } finally {
+ if (!renamed) rmSync(temporary, { force: true })
+ }
+}
+
+function boundedIdentityPart(value: unknown, max = 200): value is string {
+ return typeof value === 'string' && value.length > 0 && value.length <= max && !/[\u0000-\u001f\u007f]/.test(value)
+}
+
+export function validTerminalRuntime(value: unknown): value is TerminalRuntimeRef {
+ if (!value || typeof value !== 'object') return false
+ const runtime = value as Partial<TerminalRuntimeRef>
+ if (runtime.backend === 'tmux') return typeof runtime.paneId === 'string' && PANE_RE.test(runtime.paneId)
+ return runtime.backend === 'herdr'
+ && boundedIdentityPart(runtime.endpointId)
+ && boundedIdentityPart(runtime.sessionName, 100)
+ && boundedIdentityPart(runtime.terminalId)
+ && boundedIdentityPart(runtime.paneId)
+}
+
+function normalizedRuntimes(raw: unknown, legacyTmuxPane?: unknown): TerminalRuntimeRef[] {
+ const fromArray = Array.isArray(raw) ? raw.filter(validTerminalRuntime) : []
+ const legacy = typeof legacyTmuxPane === 'string' && PANE_RE.test(legacyTmuxPane)
+ ? [{ backend: 'tmux' as const, paneId: legacyTmuxPane }]
+ : []
+ return mergeTerminalRuntimes([], [...fromArray, ...legacy])
+}
+
+function tmuxProjection(runtimes: readonly TerminalRuntimeRef[]): string {
+ return runtimes.find((runtime) => runtime.backend === 'tmux')?.paneId ?? ''
+}
+
+function persistedRow(entry: RegisteredSession): RegisteredSession | Omit<RegisteredSession, 'tmuxPane'> {
+ if (entry.tmuxPane) return { ...entry, runtimes: entry.runtimes.map((runtime) => ({ ...runtime })) }
+ const { tmuxPane: _legacy, ...row } = entry
+ return { ...row, runtimes: row.runtimes.map((runtime) => ({ ...runtime })) }
+}
+
+function strictPersistedRow(value: unknown): RegisteredSession | null {
+ if (!value || typeof value !== 'object') return null
+ const row = value as Partial<RegisteredSession>
+ const runtimes = normalizedRuntimes(row.runtimes, row.tmuxPane)
+ const primary = typeof row.primaryRuntimeKey === 'string' ? row.primaryRuntimeKey : ''
+ const active = row.active === true
+ const projectedTmuxPane = tmuxProjection(runtimes)
+ if (row.schemaVersion !== 2
+ || typeof row.active !== 'boolean'
+ || typeof row.agentId !== 'string' || !row.agentId
+ || typeof row.sessionId !== 'string'
+ || typeof row.engine !== 'string' || !AGENT_ENGINES.has(row.engine as AgentEngine)
+ || typeof row.projectDir !== 'string'
+ || typeof row.primaryRuntimeKey !== 'string'
+ || !Array.isArray(row.runtimes) || runtimes.length !== row.runtimes.length || !runtimes.length
+ || (projectedTmuxPane ? row.tmuxPane !== projectedTmuxPane : row.tmuxPane !== undefined)
+ || (active && !runtimes.some((runtime) => terminalRouteKey(runtime) === primary))
+ || (!active && primary !== '')
+ || (row.processIdentity !== null && !validProcessIdentity(row.processIdentity))) return null
+ const placements = runtimes.map(terminalPlacementKey)
+ if (new Set(placements).size !== placements.length) return null
+ return {
+ ...row,
+ schemaVersion: 2,
+ active,
+ agentId: row.agentId,
+ sessionId: row.sessionId,
+ boundAt: typeof row.boundAt === 'number' ? row.boundAt : null,
+ engine: row.engine as AgentEngine,
+ transcriptPath: typeof row.transcriptPath === 'string' ? row.transcriptPath : null,
+ projectDir: row.projectDir,
+ cwd: typeof row.cwd === 'string' ? row.cwd : null,
+ runtimes,
+ primaryRuntimeKey: primary,
+ tmuxPane: projectedTmuxPane,
+ source: typeof row.source === 'string' ? row.source : null,
+ title: typeof row.title === 'string' ? row.title : null,
+ model: modelString(row.model),
+ cliVersion: typeof row.cliVersion === 'string' ? row.cliVersion : null,
+ processIdentity: row.processIdentity ?? null,
+ registeredAt: typeof row.registeredAt === 'number' ? row.registeredAt : Date.now(),
+ updatedAt: typeof row.updatedAt === 'number' ? row.updatedAt : Date.now(),
+ lastHookAt: typeof row.lastHookAt === 'number' ? row.lastHookAt : Date.now(),
+ lastTranscriptAt: typeof row.lastTranscriptAt === 'number' ? row.lastTranscriptAt : Date.now(),
+ }
+}
+
+function validatedRows(values: readonly unknown[]): RegisteredSession[] | null {
+ const rows: RegisteredSession[] = []
+ const agents = new Set<string>()
+ const sessions = new Set<string>()
+ const processes = new Set<string>()
+ const routes = new Set<string>()
+ for (const value of values) {
+ const row = strictPersistedRow(value)
+ if (!row || agents.has(row.agentId)) return null
+ agents.add(row.agentId)
+ if (row.sessionId) {
+ if (sessions.has(row.sessionId)) return null
+ sessions.add(row.sessionId)
+ }
+ if (row.processIdentity) {
+ const key = processIdentityKey(row.engine, row.processIdentity)
+ if (processes.has(key)) return null
+ processes.add(key)
+ }
+ for (const runtime of row.runtimes) {
+ const key = terminalRouteKey(runtime)
+ if (routes.has(key)) return null
+ routes.add(key)
+ }
+ rows.push(row)
+ }
+ return rows
+}
+
+function hasUnknownRowSchema(value: unknown): boolean {
+ return !!value && typeof value === 'object'
+ && Object.hasOwn(value, 'schemaVersion')
+ && (value as { schemaVersion?: unknown }).schemaVersion !== 2
+}
+
+function validLegacyRegistryRow(value: unknown): boolean {
+ if (!value || typeof value !== 'object' || Array.isArray(value) || Object.hasOwn(value, 'schemaVersion')) return false
+ const row = value as Partial<RegisteredSession>
+ const id = rowId(row)
+ if (!boundedIdentityPart(id)) return false
+ if (row.engine !== undefined && (typeof row.engine !== 'string' || !AGENT_ENGINES.has(row.engine))) return false
+ if (row.tmuxPane !== undefined && (typeof row.tmuxPane !== 'string' || !PANE_RE.test(row.tmuxPane))) return false
+ if (row.runtimes !== undefined
+ && (!Array.isArray(row.runtimes) || !row.runtimes.length || !row.runtimes.every(validTerminalRuntime))) return false
+ return normalizedRuntimes(row.runtimes, row.tmuxPane).length > 0
+}
+
+function threeWayRow(
+ baselineJson: string | undefined,
+ current: Record<string, unknown>,
+ latest: Record<string, unknown>,
+): Record<string, unknown> {
+ let baseline: Record<string, unknown> = {}
+ try { baseline = baselineJson ? JSON.parse(baselineJson) as Record<string, unknown> : {} } catch { /* empty */ }
+ const merged: Record<string, unknown> = { ...latest }
+ for (const key of Object.keys(baseline)) {
+ if (!(key in current)) delete merged[key]
+ }
+ for (const [key, value] of Object.entries(current)) {
+ if (JSON.stringify(value) !== JSON.stringify(baseline[key])) merged[key] = value
+ }
+ return merged
+}
+
+function selectedRuntimeKey(runtimes: readonly TerminalRuntimeRef[], requested: unknown): string {
+ const keys = new Set(runtimes.map(terminalRouteKey))
+ return typeof requested === 'string' && keys.has(requested)
+ ? requested
+ : runtimes[0] ? terminalRouteKey(runtimes[0]) : ''
+}
function isWithin(root: string, file: string): boolean {
const rel = relative(root, file)
@@ -143,21 +466,40 @@ export function validTranscriptPath(engine: AgentEngine, filePath: string): bool
}
}
-/** Seconds-since-epoch of the last machine boot (now − uptime). Persisted next to the registry so a
- * reload can tell it was written BEFORE a reboot — after which every cached tmux pane id (%N) belongs to
- * a DEAD tmux server and can FALSELY collide with a reused id in the new server (%0→%0), slipping past
- * the pane-liveness reaper and leaving ghost agents in the list. On a boot change we drop the whole
- * cache and start clean (live sessions re-register via the SessionStart hook). NB: a `tmux kill-server`
- * WITHOUT a reboot isn't caught here (boot time unchanged) — that would need tmux-server-id tracking. */
+/** Prefer the kernel boot UUID; retain numeric marker compatibility for one migration. */
const BOOT_TOLERANCE_SEC = 120 // clock/NTP drift is seconds; a reboot shifts boot time by the whole uptime
function bootTimeSec(): number {
return Math.round(Date.now() / 1000 - uptime())
}
-function readSavedBoot(): number | null {
- try { const n = Number(readFileSync(BOOT_FILE, 'utf-8').trim()); return Number.isFinite(n) ? n : null } catch { return null }
+function currentBootId(): string {
+ try {
+ const value = readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim()
+ if (/^[0-9a-f-]{36}$/i.test(value)) return `linux:${value}`
+ } catch { /* non-Linux fallback below */ }
+ return `time:${bootTimeSec()}`
+}
+function readSavedBoot(): string | null {
+ try {
+ const raw = readPrivateStateFile(BOOT_FILE, 256).trim()
+ if (!raw) return null
+ try {
+ const parsed = JSON.parse(raw) as unknown
+ return typeof parsed === 'string' ? parsed : raw
+ } catch { return raw }
+ } catch { return null }
}
-function writeBoot(): void {
- try { mkdirSync(env.ADAPTER_DATA_DIR, { recursive: true }); writeFileSync(BOOT_FILE, String(bootTimeSec())) } catch { /* best effort */ }
+function bootChanged(saved: string | null, current: string): boolean {
+ if (!saved) return false
+ if (saved.startsWith('linux:')) return saved !== current
+ const savedNumber = Number(saved.replace(/^time:/, ''))
+ const currentNumber = current.startsWith('time:') ? Number(current.slice(5)) : bootTimeSec()
+ return !Number.isFinite(savedNumber) || Math.abs(currentNumber - savedNumber) > BOOT_TOLERANCE_SEC
+}
+function writeBoot(bootId: string): void {
+ try {
+ secureStateDirectory(env.ADAPTER_DATA_DIR)
+ atomicWriteJson(BOOT_FILE, bootId)
+ } catch { /* registry load will remain conservative on the next restart */ }
}
class Registry {
@@ -167,10 +509,22 @@ class Registry {
* `sessionId` (`cancel`, `question_response`, `compact`, `session_get`) while everything else
* addresses the agent. `resolve()` is the one lookup that accepts either. */
private sessionIndex = new Map<string, string>()
+ /** backend-scoped route → agentId. Public Herdr pane ids are never indexed without endpointId. */
+ private runtimeIndex = new Map<string, string>()
+ /** engine + PID start marker → agentId. This is authoritative across nested multiplexers. */
+ private processIndex = new Map<string, string>()
+ private transactionDepth = 0
+ private savePending = false
+ /** Root corruption/unknown schemas are read-only until the operator restores valid bytes. */
+ private writeBlocked = false
+ /** Last committed row bytes, used for a three-way merge with daemon-down hook writes. */
+ private persistedBaseline = new Map<string, string>()
private index(entry: RegisteredSession): void {
this.agents.set(entry.agentId, entry)
if (entry.sessionId) this.sessionIndex.set(entry.sessionId, entry.agentId)
+ for (const runtime of entry.runtimes) this.runtimeIndex.set(terminalRouteKey(runtime), entry.agentId)
+ if (entry.processIdentity) this.processIndex.set(processIdentityKey(entry.engine, entry.processIdentity), entry.agentId)
}
private drop(entry: RegisteredSession | undefined): void {
@@ -179,6 +533,14 @@ class Registry {
if (entry.sessionId && this.sessionIndex.get(entry.sessionId) === entry.agentId) {
this.sessionIndex.delete(entry.sessionId)
}
+ for (const runtime of entry.runtimes) {
+ const key = terminalRouteKey(runtime)
+ if (this.runtimeIndex.get(key) === entry.agentId) this.runtimeIndex.delete(key)
+ }
+ if (entry.processIdentity) {
+ const key = processIdentityKey(entry.engine, entry.processIdentity)
+ if (this.processIndex.get(key) === entry.agentId) this.processIndex.delete(key)
+ }
}
private releaseBinding(entry: RegisteredSession): void {
@@ -197,12 +559,55 @@ class Registry {
load(): void {
this.agents.clear()
this.sessionIndex.clear()
+ this.runtimeIndex.clear()
+ this.processIndex.clear()
+ this.writeBlocked = false
+ this.persistedBaseline.clear()
+ try {
+ secureStateDirectory(env.ADAPTER_DATA_DIR)
+ } catch (error) {
+ this.writeBlocked = true
+ console.error('[registry] unsafe state directory; refusing to load or write state:', error)
+ return
+ }
this.loadNames()
const savedBoot = readSavedBoot()
- const rebooted = savedBoot !== null && Math.abs(bootTimeSec() - savedBoot) > BOOT_TOLERANCE_SEC
- writeBoot() // refresh the reference so a reboot is detected exactly once, even across same-boot restarts
+ const bootId = currentBootId()
+ const rebooted = bootChanged(savedBoot, bootId)
+ writeBoot(bootId) // refresh the reference so a reboot is detected exactly once, even across same-boot restarts
try {
- const arr = JSON.parse(readFileSync(FILE, 'utf-8')) as RegisteredSession[]
+ const parsed = JSON.parse(readPrivateStateFile(FILE)) as unknown
+ if (!Array.isArray(parsed)) {
+ this.writeBlocked = true
+ console.error('[registry] registry root is not an array; refusing to overwrite it')
+ return
+ }
+ if (parsed.some(hasUnknownRowSchema)) {
+ this.writeBlocked = true
+ console.error('[registry] registry contains an unknown row schema; refusing to overwrite it')
+ return
+ }
+ const legacyRows = parsed.filter((row) => !row || typeof row !== 'object' || !Object.hasOwn(row, 'schemaVersion'))
+ if (legacyRows.some((row) => !validLegacyRegistryRow(row))) {
+ this.writeBlocked = true
+ console.error('[registry] registry contains a malformed legacy row; refusing to overwrite it')
+ return
+ }
+ const v2Rows = parsed.filter((row) => !!row && typeof row === 'object'
+ && (row as { schemaVersion?: unknown }).schemaVersion === 2)
+ if (v2Rows.length && !validatedRows(v2Rows)) {
+ this.writeBlocked = true
+ console.error('[registry] registry contains a malformed v2 row; refusing to overwrite it')
+ return
+ }
+ const arr = parsed as Array<Partial<RegisteredSession>>
+ for (const row of arr) {
+ const id = rowId(row)
+ if (id) this.persistedBaseline.set(id, rowFingerprint(row))
+ }
+ if (arr.some((row) => row.schemaVersion !== 2)) {
+ atomicWriteJson(PRE_V2_BACKUP_FILE, arr, true)
+ }
if (rebooted) {
console.log(`[registry] machine rebooted since last run — dropping ${Array.isArray(arr) ? arr.length : 0} cached tmux session(s) (stale panes)`)
this.save() // overwrite the stale on-disk snapshot so a same-boot restart can't reload it
@@ -211,25 +616,27 @@ class Registry {
let changed = false
for (const raw of Array.isArray(arr) ? arr : []) {
const engine: AgentEngine = raw?.engine === 'codex' || raw?.engine === 'cursor' || raw?.engine === 'opencode' || raw?.engine === 'pi' || raw?.engine === 'hermes' || raw?.engine === 'commandcode' || raw?.engine === 'devin' || raw?.engine === 'muse' || raw?.engine === 'amp' || raw?.engine === 'kilo' || raw?.engine === 'grok' ? raw.engine : 'claude'
- const pane = typeof raw?.tmuxPane === 'string' && PANE_RE.test(raw.tmuxPane) ? raw.tmuxPane : ''
+ const runtimes = normalizedRuntimes(raw?.runtimes, raw?.tmuxPane)
+ const pane = tmuxProjection(runtimes)
let transcriptPath =
typeof raw?.transcriptPath === 'string' && raw.transcriptPath
? raw.transcriptPath
: null
let bound = typeof raw?.sessionId === 'string' && raw.sessionId !== ''
+ const rawSessionId = typeof raw?.sessionId === 'string' ? raw.sessionId : ''
let repairedCodexTranscript = false
if (engine === 'codex' && transcriptPath) {
const meta = readCodexRolloutMeta(transcriptPath)
if (meta?.isSubagent) {
- const repaired = meta.parentThreadId === raw.sessionId
- ? resolveCodexRollout(raw.sessionId, join(env.CODEX_HOME, 'sessions'))
+ const repaired = meta.parentThreadId === rawSessionId
+ ? resolveCodexRollout(rawSessionId, join(env.CODEX_HOME, 'sessions'))
: null
if (!repaired || !validTranscriptPath('codex', repaired) || readCodexRolloutMeta(repaired)?.isSubagent) {
changed = true
bound = false
transcriptPath = null
} else {
- console.log(`[registry] repaired Codex parent ${raw.sessionId.slice(0, 8)} transcript after child hook overwrite`)
+ console.log(`[registry] repaired Codex parent ${rawSessionId.slice(0, 8)} transcript after child hook overwrite`)
transcriptPath = repaired
repairedCodexTranscript = true
changed = true
@@ -239,7 +646,7 @@ class Registry {
// A process agent remains valid without a session. A missing/invalid transcript releases only the
// binding so the discovery/store repair path can bind it again if appropriate.
if (!bound) transcriptPath = null
- if (!pane) {
+ if (!runtimes.length) {
changed = true
continue
}
@@ -258,19 +665,24 @@ class Registry {
if (!agentId) { changed = true; continue }
if (agentId !== raw.agentId) changed = true
const now = Date.now()
+ const active = raw.active !== false
const s: RegisteredSession = {
+ schemaVersion: 2,
+ active,
agentId,
boundAt: bound ? (typeof raw.boundAt === 'number' ? raw.boundAt : (raw.registeredAt ?? now)) : null,
engine,
transcriptPath,
title: titleDisplayName(typeof raw.title === 'string' ? raw.title : null),
- sessionId: bound ? raw.sessionId : '',
+ sessionId: bound ? rawSessionId : '',
projectDir: !repairedCodexTranscript && typeof raw.projectDir === 'string' && raw.projectDir
? raw.projectDir
: transcriptPath
? basename(dirname(transcriptPath))
- : (bound ? raw.sessionId : agentId),
+ : (bound ? rawSessionId : agentId),
tmuxPane: pane,
+ runtimes,
+ primaryRuntimeKey: active ? selectedRuntimeKey(runtimes, raw.primaryRuntimeKey) : '',
cwd: typeof raw.cwd === 'string' ? raw.cwd : null,
source: bound && typeof raw.source === 'string' ? raw.source : null,
cliVersion: typeof raw.cliVersion === 'string' ? raw.cliVersion : null,
@@ -283,29 +695,50 @@ class Registry {
}
if (
raw.engine !== engine
+ || raw.schemaVersion !== 2
+ || typeof raw.active !== 'boolean'
|| raw.tmuxPane !== pane
+ || JSON.stringify(raw.runtimes) !== JSON.stringify(runtimes)
+ || raw.primaryRuntimeKey !== s.primaryRuntimeKey
|| raw.transcriptPath !== transcriptPath
|| raw.title !== s.title
|| raw.lastHookAt == null
|| raw.lastTranscriptAt == null
|| legacyLauncherId !== ''
) changed = true
- // Two records claiming one agent id cannot both be right; keep the
- // one that registered last, exactly as a re-register would.
- const clash = this.agents.get(s.agentId)
- if (clash && clash.registeredAt > s.registeredAt) { changed = true; continue }
- if (clash) { this.drop(clash); changed = true }
+ if (this.agents.has(s.agentId)) {
+ this.agents.clear()
+ this.sessionIndex.clear()
+ this.runtimeIndex.clear()
+ this.processIndex.clear()
+ this.writeBlocked = true
+ console.error('[registry] registry contains duplicate agent identities; refusing to load or overwrite it')
+ return
+ }
this.index(s)
}
+ if (!validatedRows(this.list().map(persistedRow))) {
+ this.agents.clear()
+ this.sessionIndex.clear()
+ this.runtimeIndex.clear()
+ this.processIndex.clear()
+ this.writeBlocked = true
+ console.error('[registry] registry violates global identity invariants; refusing to load or overwrite it')
+ return
+ }
if (changed) this.save()
- } catch {
- // no file yet / unreadable — start empty
+ } catch (error) {
+ if (existsSync(FILE)) {
+ this.writeBlocked = true
+ console.error('[registry] registry is unreadable; refusing to overwrite it:', error instanceof Error ? error.message : error)
+ }
+ // A genuinely absent file starts empty. Any existing unreadable file is preserved byte-for-byte.
}
}
private loadNames(): void {
try {
- const obj = JSON.parse(readFileSync(NAMES_FILE, 'utf-8')) as Record<string, unknown>
+ const obj = JSON.parse(readPrivateStateFile(NAMES_FILE, 1024 * 1024)) as Record<string, unknown>
for (const [id, name] of Object.entries(obj)) {
if (typeof name === 'string' && name.trim()) NAME_OVERRIDES.set(id, name.trim())
}
@@ -318,36 +751,58 @@ class Registry {
openProcessAgent(input: {
agentId?: string
engine: AgentEngine
- tmuxPane: string
+ tmuxPane?: string
+ runtimes?: TerminalRuntimeRef[]
+ primaryRuntimeKey?: string
cwd?: string | null
processIdentity: ProcessIdentity
}):
{ entry: RegisteredSession; isNew: boolean; evicted: string | null } | null {
- const { engine, tmuxPane, processIdentity } = input
- if (!tmuxPane || !PANE_RE.test(tmuxPane) || !validProcessIdentity(processIdentity)) return null
- const existing = [...this.agents.values()].find((agent) =>
- agent.tmuxPane === tmuxPane
- && agent.engine === engine
- && (!agent.processIdentity || (
+ if (this.writeBlocked) return null
+ const { engine, processIdentity } = input
+ const runtimes = normalizedRuntimes(input.runtimes, input.tmuxPane)
+ if (!runtimes.length || !validProcessIdentity(processIdentity)) return null
+ const processAgentId = this.processIndex.get(processIdentityKey(engine, processIdentity))
+ const processAgent = processAgentId ? this.agents.get(processAgentId) : undefined
+ const routeAgent = runtimes
+ .map((runtime) => this.byRuntimeEngine(runtime, engine))
+ .find((agent) => !agent?.processIdentity || (
agent.processIdentity.pid === processIdentity.pid
&& agent.processIdentity.startMarker === processIdentity.startMarker
- )))
+ ))
+ const existing = processAgent ?? routeAgent
if (existing) {
- existing.tmuxPane = tmuxPane
+ this.drop(existing)
+ existing.runtimes = mergeTerminalRuntimes(existing.runtimes, runtimes)
+ existing.tmuxPane = tmuxProjection(existing.runtimes)
+ existing.primaryRuntimeKey = selectedRuntimeKey(existing.runtimes, input.primaryRuntimeKey || existing.primaryRuntimeKey)
existing.cwd = input.cwd ?? existing.cwd
existing.processIdentity = processIdentity
+ existing.active = true
existing.updatedAt = Date.now()
+ this.index(existing)
this.save()
return { entry: existing, isNew: false, evicted: null }
}
const agentId = input.agentId || randomUUID()
let evicted: string | null = null
- for (const other of this.agents.values()) {
- if (other.tmuxPane === tmuxPane) { this.drop(other); evicted = other.sessionId || other.agentId; break }
+ for (const runtime of runtimes) {
+ const otherId = this.runtimeIndex.get(terminalRouteKey(runtime))
+ const other = otherId ? this.agents.get(otherId) : undefined
+ if (!other) continue
+ this.drop(other)
+ other.runtimes = other.runtimes.filter((candidate) => terminalRouteKey(candidate) !== terminalRouteKey(runtime))
+ other.tmuxPane = tmuxProjection(other.runtimes)
+ other.primaryRuntimeKey = selectedRuntimeKey(other.runtimes, other.primaryRuntimeKey)
+ other.active = other.runtimes.length > 0
+ if (other.runtimes.length) this.index(other)
+ evicted ??= other.sessionId || other.agentId
}
const now = Date.now()
const entry: RegisteredSession = {
+ schemaVersion: 2,
+ active: true,
agentId,
sessionId: '',
boundAt: null,
@@ -355,7 +810,9 @@ class Registry {
transcriptPath: null,
projectDir: basename(input.cwd ?? '') || agentId,
cwd: input.cwd ?? null,
- tmuxPane,
+ runtimes,
+ primaryRuntimeKey: selectedRuntimeKey(runtimes, input.primaryRuntimeKey),
+ tmuxPane: tmuxProjection(runtimes),
source: null,
title: null,
model: null,
@@ -384,6 +841,7 @@ class Registry {
* can skip re-announcing), evicted = the sessionId displaced from this pane (caller removes it).
*/
register(input: RegisterInput): { entry: RegisteredSession; isNew: boolean; evicted: string | null; rebound: string | null } | null {
+ if (this.writeBlocked) return null
const transcriptPath = input.transcriptPath
const sessionId =
input.sessionId || (transcriptPath ? basename(transcriptPath).replace(/\.jsonl$/, '') : '')
@@ -392,13 +850,16 @@ class Registry {
const pane = input.tmuxPane
// Hooks carry process metadata, not ownership. The already-discovered pane+engine process chooses the
// agent; an optional legacy launcherId is intentionally ignored.
- const processAgent = pane ? this.byPaneEngine(pane, engine) : undefined
+ const inputRuntimes = normalizedRuntimes(input.runtimes, pane)
+ const processAgent = (validProcessIdentity(input.processIdentity)
+ ? this.byProcess(engine, input.processIdentity)
+ : undefined)
+ ?? inputRuntimes.map((runtime) => this.byRuntimeEngine(runtime, engine)).find(Boolean)
const agentId = processAgent?.agentId ?? ''
if (
!sessionId
|| !agentId
- || !pane
- || !PANE_RE.test(pane)
+ || !inputRuntimes.length
|| (engine === 'grok' && !GROK_SESSION_RE.test(sessionId))
|| (engine !== 'cursor' && engine !== 'opencode' && engine !== 'kilo' && engine !== 'pi' && engine !== 'hermes' && engine !== 'commandcode' && engine !== 'devin' && engine !== 'grok' && !transcriptPath)
|| (transcriptPath && !validTranscriptPath(engine, transcriptPath))
@@ -436,6 +897,8 @@ class Registry {
: null
const effectiveTranscriptPath = transcriptPath ?? existing?.transcriptPath ?? derived ?? null
const entry: RegisteredSession = {
+ schemaVersion: 2,
+ active: existing?.active ?? true,
agentId,
sessionId,
boundAt: isNew ? now : existing?.boundAt ?? now,
@@ -447,7 +910,9 @@ class Registry {
? basename(dirname(effectiveTranscriptPath))
: basename(input.cwd ?? existing?.cwd ?? '') || sessionId,
cwd: input.cwd ?? existing?.cwd ?? null,
- tmuxPane: pane,
+ runtimes: mergeTerminalRuntimes(existing?.runtimes ?? [], inputRuntimes),
+ primaryRuntimeKey: '',
+ tmuxPane: '',
source: input.source ?? existing?.source ?? null,
title: titleDisplayName(input.title ?? existing?.title ?? null),
model: modelString(input.model) ?? existing?.model ?? null,
@@ -458,6 +923,8 @@ class Registry {
lastHookAt: now,
lastTranscriptAt: existing?.lastTranscriptAt ?? now,
}
+ entry.tmuxPane = tmuxProjection(entry.runtimes)
+ entry.primaryRuntimeKey = selectedRuntimeKey(entry.runtimes, input.primaryRuntimeKey || existing?.primaryRuntimeKey)
if (rebound) this.sessionIndex.delete(rebound)
this.index(entry)
this.save()
@@ -505,7 +972,43 @@ class Registry {
}
byPaneEngine(tmuxPane: string, engine: AgentEngine): RegisteredSession | undefined {
- return [...this.agents.values()].find((entry) => entry.tmuxPane === tmuxPane && entry.engine === engine)
+ return this.byRuntimeEngine({ backend: 'tmux', paneId: tmuxPane }, engine)
+ }
+
+ byRuntimeEngine(runtime: TerminalRuntimeRef, engine: AgentEngine): RegisteredSession | undefined {
+ const agentId = this.runtimeIndex.get(terminalRouteKey(runtime))
+ const entry = agentId ? this.agents.get(agentId) : undefined
+ return entry?.engine === engine ? entry : undefined
+ }
+
+ byProcess(engine: AgentEngine, identity: ProcessIdentity): RegisteredSession | undefined {
+ const agentId = this.processIndex.get(processIdentityKey(engine, identity))
+ return agentId ? this.agents.get(agentId) : undefined
+ }
+
+ updateRuntimes(agentId: string, runtimes: readonly TerminalRuntimeRef[], primaryRuntimeKey?: string): boolean {
+ const entry = this.agents.get(agentId)
+ const normalized = normalizedRuntimes(runtimes)
+ if (!entry || !normalized.length) return false
+ this.drop(entry)
+ entry.runtimes = normalized
+ entry.tmuxPane = tmuxProjection(normalized)
+ entry.primaryRuntimeKey = selectedRuntimeKey(normalized, primaryRuntimeKey)
+ entry.active = true
+ entry.updatedAt = Date.now()
+ this.index(entry)
+ this.save()
+ return true
+ }
+
+ setActive(agentId: string, active: boolean): boolean {
+ const entry = this.agents.get(agentId)
+ if (!entry || entry.active === active) return !!entry
+ entry.active = active
+ entry.primaryRuntimeKey = active ? selectedRuntimeKey(entry.runtimes, entry.primaryRuntimeKey) : ''
+ entry.updatedAt = Date.now()
+ this.save()
+ return true
}
/** The one lookup for anything that arrives from outside: web and device address an agent by `agentId`
@@ -521,8 +1024,10 @@ class Registry {
updateProcessIdentity(sessionId: string, processIdentity: ProcessIdentity): boolean {
const session = this.resolve(sessionId)
if (!session || !validProcessIdentity(processIdentity)) return false
+ this.drop(session)
session.processIdentity = processIdentity
session.updatedAt = Date.now()
+ this.index(session)
this.save()
return true
}
@@ -583,17 +1088,126 @@ class Registry {
return Array.from(this.agents.values())
}
+ active(): RegisteredSession[] {
+ return this.list().filter((entry) => entry.active)
+ }
+
+ async transaction<T>(apply: () => T | Promise<T>): Promise<T> {
+ this.transactionDepth++
+ try {
+ return await apply()
+ } finally {
+ this.transactionDepth--
+ if (this.transactionDepth === 0 && this.savePending) {
+ this.savePending = false
+ this.save()
+ }
+ }
+ }
+
flush(): void {
this.save()
this.saveNames()
}
private save(): void {
+ if (this.transactionDepth > 0) {
+ this.savePending = true
+ return
+ }
+ if (this.writeBlocked) {
+ console.error('[registry] save skipped because the loaded registry requires operator repair')
+ return
+ }
try {
- mkdirSync(env.ADAPTER_DATA_DIR, { recursive: true })
- const tmp = `${FILE}.${process.pid}.tmp`
- writeFileSync(tmp, JSON.stringify(this.list(), null, 2))
- renameSync(tmp, FILE)
+ secureStateDirectory(env.ADAPTER_DATA_DIR)
+ withRegistryFileLock(() => {
+ const currentRows = new Map(this.list().map((entry) => {
+ const row = persistedRow(entry) as unknown as Record<string, unknown>
+ return [entry.agentId, row] as const
+ }))
+ const latestValues: unknown[] = (() => {
+ if (!existsSync(FILE)) return []
+ const parsed = JSON.parse(readPrivateStateFile(FILE)) as unknown
+ if (!Array.isArray(parsed)) throw new Error('registry root changed to a non-array value')
+ if (parsed.some(hasUnknownRowSchema)) {
+ throw new Error('registry contains an unknown row schema')
+ }
+ const legacyRows = parsed.filter((row) => !row || typeof row !== 'object' || !Object.hasOwn(row, 'schemaVersion'))
+ if (legacyRows.some((row) => !validLegacyRegistryRow(row))) {
+ throw new Error('registry contains a malformed legacy row')
+ }
+ const v2Rows = parsed.filter((row) => !!row && typeof row === 'object'
+ && (row as { schemaVersion?: unknown }).schemaVersion === 2)
+ if (v2Rows.length && !validatedRows(v2Rows)) throw new Error('registry contains a malformed v2 row')
+ return parsed
+ })()
+ const latest = new Map<string, Record<string, unknown>>()
+ for (const value of latestValues) {
+ const id = rowId(value)
+ if (id) latest.set(id, value as Record<string, unknown>)
+ }
+
+ const merged = new Map(latest)
+ for (const baselineId of this.persistedBaseline.keys()) {
+ if (!currentRows.has(baselineId)) merged.delete(baselineId)
+ }
+ for (const [agentId, current] of currentRows) {
+ const baseline = this.persistedBaseline.get(agentId)
+ if (baseline === rowFingerprint(current)) continue
+ let candidate = latest.has(agentId)
+ ? threeWayRow(baseline, current, latest.get(agentId)!)
+ : current
+ const process = strictPersistedRow(candidate)?.processIdentity
+ const engine = candidate.engine
+ const sessionId = typeof candidate.sessionId === 'string' ? candidate.sessionId : ''
+ const routes = new Set(normalizedRuntimes(candidate.runtimes, candidate.tmuxPane).map(terminalRouteKey))
+ for (const [otherId, other] of [...merged]) {
+ if (otherId === agentId) continue
+ const otherRow = strictPersistedRow(other)
+ if (!otherRow) continue
+ const sameProcess = !!process && !!otherRow.processIdentity && otherRow.engine === engine
+ && process.pid === otherRow.processIdentity.pid
+ && process.startMarker === otherRow.processIdentity.startMarker
+ const sameSession = !!sessionId && otherRow.sessionId === sessionId
+ const sameRoute = otherRow.runtimes.some((runtime) => routes.has(terminalRouteKey(runtime)))
+ if (!sameProcess && !sameSession && !sameRoute) continue
+ // A daemon-down hook may bind a session while startup discovery is opening the same process.
+ // Preserve that binding, then let the scanner-owned agent id/runtime state win deterministically.
+ if (sameProcess && !candidate.sessionId && otherRow.sessionId) {
+ candidate = {
+ ...candidate,
+ sessionId: otherRow.sessionId,
+ boundAt: otherRow.boundAt,
+ transcriptPath: otherRow.transcriptPath,
+ source: otherRow.source,
+ lastHookAt: otherRow.lastHookAt,
+ }
+ }
+ merged.delete(otherId)
+ }
+ merged.set(agentId, candidate)
+ }
+
+ const rows = validatedRows([...merged.values()])
+ if (!rows) throw new Error('registry transaction would violate global identity invariants')
+ const serialized = rows.map(persistedRow)
+ atomicWriteJson(FILE, serialized)
+
+ // Refresh external daemon-down writes into the in-memory revision without replacing object
+ // identities already held by controllers.
+ const previous = new Map(this.agents)
+ this.agents.clear()
+ this.sessionIndex.clear()
+ this.runtimeIndex.clear()
+ this.processIndex.clear()
+ for (const row of rows) {
+ const entry = previous.get(row.agentId) ?? row
+ if (entry !== row) Object.assign(entry, row)
+ this.index(entry)
+ }
+ this.persistedBaseline = new Map(serialized.map((row) => [rowId(row), rowFingerprint(row)]))
+ })
} catch (err) {
console.error('[registry] save failed:', err)
}
@@ -601,15 +1215,15 @@ class Registry {
private saveNames(): void {
try {
- mkdirSync(env.ADAPTER_DATA_DIR, { recursive: true })
+ secureStateDirectory(env.ADAPTER_DATA_DIR)
let existing: Record<string, string> = {}
try {
- const obj = JSON.parse(readFileSync(NAMES_FILE, 'utf-8')) as Record<string, unknown>
+ const obj = JSON.parse(readPrivateStateFile(NAMES_FILE, 1024 * 1024)) as Record<string, unknown>
existing = Object.fromEntries(Object.entries(obj).filter(([, v]) => typeof v === 'string')) as Record<string, string>
} catch {
// no file yet / unreadable — write the in-memory overrides
}
- writeFileSync(NAMES_FILE, JSON.stringify({ ...existing, ...Object.fromEntries(NAME_OVERRIDES) }, null, 2))
+ atomicWriteJson(NAMES_FILE, { ...existing, ...Object.fromEntries(NAME_OVERRIDES) })
} catch (err) {
console.error('[registry] save names failed:', err)
}
diff --git a/cli/src/lib/runtimeProfile.spec.ts b/cli/src/lib/runtimeProfile.spec.ts
index 6fb11bd79..ae11c92c2 100644
--- a/cli/src/lib/runtimeProfile.spec.ts
+++ b/cli/src/lib/runtimeProfile.spec.ts
@@ -20,8 +20,11 @@ afterEach(async () => {
function session(engine: RegisteredSession['engine']): RegisteredSession {
return {
+ schemaVersion: 2,
+ active: true,
sessionId: 'session:1', engine, launcherId: 'h1', agentId: 'h1', boundAt: 0, transcriptPath: '/tmp/session.jsonl', projectDir: 'tmp', cwd: '/tmp',
tmuxPane: '%1', source: null, title: null, model: null,
+ runtimes: [{ backend: 'tmux', paneId: '%1' }], primaryRuntimeKey: 'tmux\u0000%1',
cliVersion: engine === 'codex' ? '0.144.5' : engine === 'cursor' ? '2026.07.20-8cc9c0b' : '2.1.212', processIdentity: null,
registeredAt: 1, updatedAt: 1, lastHookAt: 1, lastTranscriptAt: 1,
}
diff --git a/cli/src/lib/runtimeProfileController.spec.ts b/cli/src/lib/runtimeProfileController.spec.ts
index 885ddaf76..57c2f3a5d 100644
--- a/cli/src/lib/runtimeProfileController.spec.ts
+++ b/cli/src/lib/runtimeProfileController.spec.ts
@@ -16,8 +16,11 @@ import {
// the catalog minted, and the catalog is agent-scoped. `setProfile` is still addressed with either id.
function session(engine: 'claude' | 'codex' | 'cursor'): RegisteredSession {
return {
+ schemaVersion: 2,
+ active: true,
sessionId: 's1', engine, launcherId: 'h1', agentId: 'h1', boundAt: 0, transcriptPath: '/tmp/s1.jsonl', projectDir: 'tmp', cwd: '/tmp',
tmuxPane: '%1', source: null, title: null, model: null,
+ runtimes: [{ backend: 'tmux', paneId: '%1' }], primaryRuntimeKey: 'tmux\u0000%1',
cliVersion: engine === 'codex' ? '0.144.5' : engine === 'cursor' ? '2026.07.20-8cc9c0b' : '2.1.212', processIdentity: null,
registeredAt: 1, updatedAt: 1, lastHookAt: 1, lastTranscriptAt: 1,
}
diff --git a/cli/src/lib/runtimeProfileController.ts b/cli/src/lib/runtimeProfileController.ts
index 4d1f74005..7a53db3c1 100644
--- a/cli/src/lib/runtimeProfileController.ts
+++ b/cli/src/lib/runtimeProfileController.ts
@@ -60,11 +60,11 @@ export interface RuntimeProfileControllerDeps {
manager: RuntimeProfileManager
getSession: (sessionId: string) => RegisteredSession | undefined
validateRuntime: (session: RegisteredSession) => Promise<boolean>
- capture: (pane: string, historyLines?: number) => Promise<string | null>
- sendText: (pane: string, text: string) => Promise<boolean>
- /** Type without submitting — see sendLiteralToTmux. */
- sendLiteral: (pane: string, text: string) => Promise<boolean>
- sendKey: (pane: string, key: string) => Promise<boolean>
+ capture: (terminalTarget: string, historyLines?: number) => Promise<string | null>
+ sendText: (terminalTarget: string, text: string) => Promise<boolean>
+ /** Type without submitting. */
+ sendLiteral: (terminalTarget: string, text: string) => Promise<boolean>
+ sendKey: (terminalTarget: string, key: string) => Promise<boolean>
acquireInput: (sessionId: string) => (() => void) | null
}
@@ -335,7 +335,7 @@ export class RuntimeProfileController {
let pickerOpen = false
try {
if (!await this.deps.validateRuntime(session)) throw new RuntimeProfileControlError('TMUX_FAILED')
- const capture = await this.deps.capture(session.tmuxPane, 100)
+ const capture = await this.deps.capture(session.agentId, 100)
if (!capture) throw new RuntimeProfileControlError('TMUX_FAILED')
const inspection = inspectRuntimePane(session.engine, capture)
if (session.engine === 'codex' && inspection.plan) throw new RuntimeProfileControlError('PLAN_SCOPE_AMBIGUOUS')
@@ -377,9 +377,9 @@ export class RuntimeProfileController {
} catch (error) {
if (pickerOpen) {
for (let attempt = 0; attempt < 3; attempt++) {
- await this.deps.sendKey(session.tmuxPane, 'Escape').catch(() => false)
+ await this.deps.sendKey(session.agentId, 'Escape').catch(() => false)
await sleep(100)
- const next = await this.deps.capture(session.tmuxPane, 100).catch(() => null)
+ const next = await this.deps.capture(session.agentId, 100).catch(() => null)
if (!next || !inspectRuntimePane(session.engine, next).dialog) break
}
}
@@ -402,7 +402,7 @@ export class RuntimeProfileController {
options: Array<{ id: string }>,
): Promise<void> {
if (current?.model !== target.model) {
- if (!await this.deps.sendText(session.tmuxPane, `/model ${target.model}`)) {
+ if (!await this.deps.sendText(session.agentId, `/model ${target.model}`)) {
throw new RuntimeProfileControlError('TMUX_FAILED')
}
if (!await this.waitClaudeModel(session)) throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
@@ -421,11 +421,11 @@ export class RuntimeProfileController {
this.deps.manager.confirmEffort(session.sessionId, 'auto')
return
}
- if (!await this.deps.sendText(session.tmuxPane, `/effort ${target.effort}`)) {
+ if (!await this.deps.sendText(session.agentId, `/effort ${target.effort}`)) {
throw new RuntimeProfileControlError('TMUX_FAILED')
}
if (!await this.deps.manager.waitForProfile(session.sessionId, COMMAND_CONFIRM_MS)) {
- await this.deps.sendKey(session.tmuxPane, 'Enter')
+ await this.deps.sendKey(session.agentId, 'Enter')
if (!await this.deps.manager.waitForProfile(session.sessionId, 2_000)) {
throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
}
@@ -434,12 +434,12 @@ export class RuntimeProfileController {
private async waitClaudeModel(session: RegisteredSession): Promise<boolean> {
if (await this.deps.manager.waitForModel(session.sessionId, 1_200)) return true
- const capture = await this.deps.capture(session.tmuxPane, 80)
+ const capture = await this.deps.capture(session.agentId, 80)
if (capture && /switch model|change model|continue.*model|re-read.*history/i.test(stripAnsi(capture))) {
- await this.deps.sendKey(session.tmuxPane, 'Enter')
+ await this.deps.sendKey(session.agentId, 'Enter')
} else {
- // Claude and Codex can swallow the first Enter immediately after a tmux literal write.
- await this.deps.sendKey(session.tmuxPane, 'Enter')
+ // Claude and Codex can swallow the first Enter immediately after a terminal literal write.
+ await this.deps.sendKey(session.agentId, 'Enter')
}
return this.deps.manager.waitForModel(session.sessionId, COMMAND_CONFIRM_MS)
}
@@ -453,11 +453,11 @@ export class RuntimeProfileController {
private async setDevin(session: RegisteredSession, target: RuntimeProfile): Promise<void> {
const devin = this.deps.manager.devinTarget(session.sessionId, target.id)
if (!devin) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
- if (!await this.deps.sendText(session.tmuxPane, `/model ${devin.id}`)) {
+ if (!await this.deps.sendText(session.agentId, `/model ${devin.id}`)) {
throw new RuntimeProfileControlError('TMUX_FAILED')
}
const answered = await this.waitPane(
- session.tmuxPane,
+ session.agentId,
(value) => devinModelCommandResult(stripAnsi(value)) !== null,
COMMAND_CONFIRM_MS,
)
@@ -484,7 +484,7 @@ export class RuntimeProfileController {
current: RuntimeProfile | null,
): Promise<void> {
if (current?.model !== target.model) {
- if (!await this.deps.sendText(session.tmuxPane, `/model ${target.model}`)) {
+ if (!await this.deps.sendText(session.agentId, `/model ${target.model}`)) {
throw new RuntimeProfileControlError('TMUX_FAILED')
}
if (!await this.deps.manager.waitForModel(session.sessionId, COMMAND_CONFIRM_MS)) {
@@ -500,20 +500,20 @@ export class RuntimeProfileController {
private async setPiThinking(session: RegisteredSession, target: RuntimeProfile): Promise<void> {
const effort = target.effort
- if (!await this.deps.sendText(session.tmuxPane, '/settings')) {
+ if (!await this.deps.sendText(session.agentId, '/settings')) {
throw new RuntimeProfileControlError('TMUX_FAILED')
}
- if (!await this.waitPane(session.tmuxPane, (v) => /Type to search/i.test(stripAnsi(v)), PICKER_OPEN_MS)) {
+ if (!await this.waitPane(session.agentId, (v) => /Type to search/i.test(stripAnsi(v)), PICKER_OPEN_MS)) {
throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
}
// Typing alone is enough: the settings filter opens a row the moment it narrows to one. Submitting
// here would land an Enter on the ladder that just opened and pick the level already highlighted —
// which is the CURRENT one, so the switch silently did nothing.
- if (!await this.deps.sendLiteral(session.tmuxPane, 'thinking level')) {
+ if (!await this.deps.sendLiteral(session.agentId, 'thinking level')) {
throw new RuntimeProfileControlError('TMUX_FAILED')
}
const ladder = await this.waitPane(
- session.tmuxPane,
+ session.agentId,
(v) => /Select reasoning depth/i.test(stripAnsi(v)),
PICKER_OPEN_MS,
)
@@ -530,11 +530,11 @@ export class RuntimeProfileController {
for (let guard = 0; selection !== effort && guard < PI_LADDER_MAX_STEPS; guard++) {
const steps = piThinkingSteps(selection as string, effort)
if (steps === null || steps === 0) break
- if (!await this.deps.sendKey(session.tmuxPane, steps > 0 ? 'Down' : 'Up')) {
+ if (!await this.deps.sendKey(session.agentId, steps > 0 ? 'Down' : 'Up')) {
throw new RuntimeProfileControlError('TMUX_FAILED')
}
const moved = await this.waitPane(
- session.tmuxPane,
+ session.agentId,
(value) => {
const next = parsePiThinkingSelection(stripAnsi(value))
return !!next && next !== selection
@@ -546,9 +546,9 @@ export class RuntimeProfileController {
selection = parsePiThinkingSelection(stripAnsi(moved))
}
if (selection !== effort) throw new RuntimeProfileControlError('EFFORT_UNSUPPORTED')
- await this.deps.sendKey(session.tmuxPane, 'Enter')
+ await this.deps.sendKey(session.agentId, 'Enter')
// The ladder returns to the settings list; Escape closes it so the pane is idle again.
- await this.deps.sendKey(session.tmuxPane, 'Escape')
+ await this.deps.sendKey(session.agentId, 'Escape')
if (!await this.waitObservedProfile(session, target)) {
throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
}
@@ -556,7 +556,7 @@ export class RuntimeProfileController {
/** Poll the pane INTO the manager until it reports the profile we asked for. */
private async waitObservedProfile(session: RegisteredSession, target: RuntimeProfile): Promise<boolean> {
- const confirmed = await this.waitPane(session.tmuxPane, (value) => {
+ const confirmed = await this.waitPane(session.agentId, (value) => {
this.deps.manager.ingestPane(session, value, true)
return this.deps.manager.selectedModel(session) === target.id
}, COMMAND_CONFIRM_MS)
@@ -576,22 +576,22 @@ export class RuntimeProfileController {
// "Is a picker open?" cannot be asked of a capture that carries scrollback — an EARLIER picker is
// still up there, so the check passes before this one opens and the filter would be typed into the
// composer and submitted as a message. Count the openings instead and wait for one more.
- const before = countOpencodePickers(stripAnsi(await this.deps.capture(session.tmuxPane, 100) ?? ''))
- if (!await this.deps.sendText(session.tmuxPane, '/models')) {
+ const before = countOpencodePickers(stripAnsi(await this.deps.capture(session.agentId, 100) ?? ''))
+ if (!await this.deps.sendText(session.agentId, '/models')) {
throw new RuntimeProfileControlError('TMUX_FAILED')
}
if (!await this.waitPane(
- session.tmuxPane,
+ session.agentId,
(v) => countOpencodePickers(stripAnsi(v)) > before,
PICKER_OPEN_MS,
)) {
throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
}
- if (!await this.deps.sendLiteral(session.tmuxPane, entry.filter)) {
+ if (!await this.deps.sendLiteral(session.agentId, entry.filter)) {
throw new RuntimeProfileControlError('TMUX_FAILED')
}
const narrowed = await this.waitPane(
- session.tmuxPane,
+ session.agentId,
(v) => (parseOpencodePickerRows(stripAnsi(v)) ?? []).length === 1,
PICKER_STEP_MS,
)
@@ -599,7 +599,7 @@ export class RuntimeProfileController {
if (rows.length !== 1 || !opencodeRowMatches(entry, rows[0])) {
throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
}
- if (!await this.deps.sendKey(session.tmuxPane, 'Enter')) {
+ if (!await this.deps.sendKey(session.agentId, 'Enter')) {
throw new RuntimeProfileControlError('TMUX_FAILED')
}
if (!await this.waitObservedProfile(session, target)) {
@@ -625,7 +625,7 @@ export class RuntimeProfileController {
if (!entry) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
if (current?.model !== target.model) {
- if (!await this.deps.sendText(session.tmuxPane, `/model ${entry.id}`)) {
+ if (!await this.deps.sendText(session.agentId, `/model ${entry.id}`)) {
throw new RuntimeProfileControlError('TMUX_FAILED')
}
if (!await this.waitObservedModel(session, target)) {
@@ -640,8 +640,8 @@ export class RuntimeProfileController {
// Success prints NOTHING and a refusal prints one line, so both have to be watched at once — and the
// refusal has to be a NEW one. Matching the text anywhere in the capture reported failure in 25ms off
// a refusal still sitting in the scrollback from an earlier model, while the level had in fact applied.
- const refusalsBefore = countCommandcodeRefusals(stripAnsi(await this.deps.capture(session.tmuxPane, 100) ?? ''))
- if (!await this.deps.sendText(session.tmuxPane, `/effort ${target.effort}`)) {
+ const refusalsBefore = countCommandcodeRefusals(stripAnsi(await this.deps.capture(session.agentId, 100) ?? ''))
+ if (!await this.deps.sendText(session.agentId, `/effort ${target.effort}`)) {
throw new RuntimeProfileControlError('TMUX_FAILED')
}
const deadline = Date.now() + COMMAND_CONFIRM_MS
@@ -649,7 +649,7 @@ export class RuntimeProfileController {
// The level is recorded only in the CLI's global config, so confirming it means re-reading that.
await this.deps.manager.ingestConfig(session, true).catch(() => false)
if (this.deps.manager.selectedModel(session) === target.id) return
- const capture = stripAnsi(await this.deps.capture(session.tmuxPane, 100) ?? '')
+ const capture = stripAnsi(await this.deps.capture(session.agentId, 100) ?? '')
if (countCommandcodeRefusals(capture) > refusalsBefore) {
throw new RuntimeProfileControlError('EFFORT_UNSUPPORTED')
}
@@ -670,11 +670,11 @@ export class RuntimeProfileController {
private async setHermes(session: RegisteredSession, target: RuntimeProfile): Promise<void> {
const entry = this.deps.manager.hermesTarget(session.sessionId, target.id)
if (!entry) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
- if (!await this.deps.sendText(session.tmuxPane, '/model')) {
+ if (!await this.deps.sendText(session.agentId, '/model')) {
throw new RuntimeProfileControlError('TMUX_FAILED')
}
const opened = await this.waitPane(
- session.tmuxPane,
+ session.agentId,
(v) => !!parseHermesPickerPage(stripAnsi(v)),
PICKER_OPEN_MS,
)
@@ -684,7 +684,7 @@ export class RuntimeProfileController {
if (entry.provider) {
await this.walkHermesPage(session, (row) => hermesProviderMatches(row, entry.provider))
if (!await this.waitPane(
- session.tmuxPane,
+ session.agentId,
(v) => (parseHermesPickerPage(stripAnsi(v))?.rows ?? []).some((row) => row === entry.id),
PICKER_OPEN_MS,
)) {
@@ -704,11 +704,11 @@ export class RuntimeProfileController {
wanted: (row: string) => boolean,
): Promise<void> {
for (let guard = 0; guard < HERMES_PAGE_MAX_STEPS; guard++) {
- const capture = await this.deps.capture(session.tmuxPane, 100)
+ const capture = await this.deps.capture(session.agentId, 100)
const page = capture ? parseHermesPickerPage(stripAnsi(capture)) : null
if (!page || !page.selected) throw new RuntimeProfileControlError('TMUX_FAILED')
if (wanted(page.selected)) {
- if (!await this.deps.sendKey(session.tmuxPane, 'Enter')) {
+ if (!await this.deps.sendKey(session.agentId, 'Enter')) {
throw new RuntimeProfileControlError('TMUX_FAILED')
}
return
@@ -716,10 +716,10 @@ export class RuntimeProfileController {
const at = page.rows.indexOf(page.selected)
const to = page.rows.findIndex(wanted)
if (to < 0) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
- if (!await this.deps.sendKey(session.tmuxPane, to > at ? 'Down' : 'Up')) {
+ if (!await this.deps.sendKey(session.agentId, to > at ? 'Down' : 'Up')) {
throw new RuntimeProfileControlError('TMUX_FAILED')
}
- const moved = await this.waitPane(session.tmuxPane, (v) => {
+ const moved = await this.waitPane(session.agentId, (v) => {
const next = parseHermesPickerPage(stripAnsi(v))
return !!next?.selected && next.selected !== page.selected
}, PICKER_STEP_MS)
@@ -730,7 +730,7 @@ export class RuntimeProfileController {
/** Like waitObservedProfile, but only the model half — used where effort is applied separately. */
private async waitObservedModel(session: RegisteredSession, target: RuntimeProfile): Promise<boolean> {
- const confirmed = await this.waitPane(session.tmuxPane, (value) => {
+ const confirmed = await this.waitPane(session.agentId, (value) => {
this.deps.manager.ingestPane(session, value, true)
return parseRuntimeProfile(this.deps.manager.selectedModel(session))?.model === target.model
}, COMMAND_CONFIRM_MS)
@@ -738,23 +738,23 @@ export class RuntimeProfileController {
}
private async setCodex(session: RegisteredSession, target: RuntimeProfile): Promise<void> {
- if (!await this.deps.sendText(session.tmuxPane, '/model')) throw new RuntimeProfileControlError('TMUX_FAILED')
+ if (!await this.deps.sendText(session.agentId, '/model')) throw new RuntimeProfileControlError('TMUX_FAILED')
const isPicker = (value: string): boolean =>
!!parseCodexModelMenuRows(value) || !!parseCodexEffortRows(value) || !!parseCodexModelRows(value)
- let capture = await this.waitPane(session.tmuxPane, isPicker, 900)
+ let capture = await this.waitPane(session.agentId, isPicker, 900)
if (!capture) {
- await this.deps.sendKey(session.tmuxPane, 'Enter')
- capture = await this.waitPane(session.tmuxPane, isPicker, PICKER_OPEN_MS)
+ await this.deps.sendKey(session.agentId, 'Enter')
+ capture = await this.waitPane(session.agentId, isPicker, PICKER_OPEN_MS)
}
if (!capture) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
let efforts = parseCodexEffortRows(capture)
if (efforts) {
- if (!await this.deps.sendKey(session.tmuxPane, 'Escape')) {
+ if (!await this.deps.sendKey(session.agentId, 'Escape')) {
throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
}
capture = await this.waitPane(
- session.tmuxPane,
+ session.agentId,
(value) => !!parseCodexModelMenuRows(value) || !!parseCodexModelRows(value),
PICKER_STEP_MS,
)
@@ -767,9 +767,9 @@ export class RuntimeProfileController {
const quickRow = menu.quickModels.get(target.model)
const row = quickRow ?? menu.allModelsRow
if (!row) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
- if (!await this.deps.sendKey(session.tmuxPane, row)) throw new RuntimeProfileControlError('TMUX_FAILED')
+ if (!await this.deps.sendKey(session.agentId, row)) throw new RuntimeProfileControlError('TMUX_FAILED')
capture = await this.waitPane(
- session.tmuxPane,
+ session.agentId,
quickRow
? (value) => !!parseCodexEffortRows(value)
: (value) => !!parseCodexModelRows(value),
@@ -783,20 +783,20 @@ export class RuntimeProfileController {
const models = parseCodexModelRows(capture)
const modelRow = models?.get(target.model)
if (!modelRow) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
- if (!await this.deps.sendKey(session.tmuxPane, modelRow)) throw new RuntimeProfileControlError('TMUX_FAILED')
- capture = await this.waitPane(session.tmuxPane, (value) => !!parseCodexEffortRows(value), PICKER_STEP_MS)
+ if (!await this.deps.sendKey(session.agentId, modelRow)) throw new RuntimeProfileControlError('TMUX_FAILED')
+ capture = await this.waitPane(session.agentId, (value) => !!parseCodexEffortRows(value), PICKER_STEP_MS)
efforts = capture ? parseCodexEffortRows(capture) : null
}
if (!efforts) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
let effortRow = target.effort === 'auto' ? efforts.defaultRow : efforts.efforts.get(target.effort) ?? null
if (!effortRow && (target.effort === 'max' || target.effort === 'ultra') && efforts.advancedRow) {
- if (!await this.deps.sendKey(session.tmuxPane, efforts.advancedRow)) throw new RuntimeProfileControlError('TMUX_FAILED')
- capture = await this.waitPane(session.tmuxPane, (value) => !!parseCodexAdvancedRows(value), PICKER_STEP_MS)
+ if (!await this.deps.sendKey(session.agentId, efforts.advancedRow)) throw new RuntimeProfileControlError('TMUX_FAILED')
+ capture = await this.waitPane(session.agentId, (value) => !!parseCodexAdvancedRows(value), PICKER_STEP_MS)
effortRow = capture ? parseCodexAdvancedRows(capture)?.get(target.effort) ?? null : null
}
if (!effortRow) throw new RuntimeProfileControlError('EFFORT_UNSUPPORTED')
- if (!await this.deps.sendKey(session.tmuxPane, effortRow)) throw new RuntimeProfileControlError('TMUX_FAILED')
+ if (!await this.deps.sendKey(session.agentId, effortRow)) throw new RuntimeProfileControlError('TMUX_FAILED')
if (!await this.deps.manager.waitForProfile(session.sessionId, COMMAND_CONFIRM_MS)) {
throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
}
@@ -805,13 +805,13 @@ export class RuntimeProfileController {
private async setCursor(session: RegisteredSession, target: RuntimeProfile): Promise<void> {
const cursorTarget = this.deps.manager.cursorTarget(session.sessionId, target.id)
if (!cursorTarget) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
- if (!await this.deps.sendText(session.tmuxPane, `/model ${cursorTarget.familyLabel}`)) {
+ if (!await this.deps.sendText(session.agentId, `/model ${cursorTarget.familyLabel}`)) {
throw new RuntimeProfileControlError('TMUX_FAILED')
}
- let capture = await this.waitPane(session.tmuxPane, (value) => !!parseCursorModelPicker(value), 900)
+ let capture = await this.waitPane(session.agentId, (value) => !!parseCursorModelPicker(value), 900)
if (!capture) {
- if (!await this.deps.sendKey(session.tmuxPane, 'Enter')) throw new RuntimeProfileControlError('TMUX_FAILED')
- capture = await this.waitPane(session.tmuxPane, (value) => !!parseCursorModelPicker(value), PICKER_OPEN_MS)
+ if (!await this.deps.sendKey(session.agentId, 'Enter')) throw new RuntimeProfileControlError('TMUX_FAILED')
+ capture = await this.waitPane(session.agentId, (value) => !!parseCursorModelPicker(value), PICKER_OPEN_MS)
}
const picker = capture ? parseCursorModelPicker(capture) : null
if (!picker || picker.selectedFamily?.toLowerCase() !== cursorTarget.familyLabel.toLowerCase()) {
@@ -819,8 +819,8 @@ export class RuntimeProfileController {
}
if (cursorTarget.rawId !== 'auto') {
- if (!await this.deps.sendKey(session.tmuxPane, 'Tab')) throw new RuntimeProfileControlError('TMUX_FAILED')
- capture = await this.waitPane(session.tmuxPane, (value) => !!parseCursorParameterRows(value), PICKER_STEP_MS)
+ if (!await this.deps.sendKey(session.agentId, 'Tab')) throw new RuntimeProfileControlError('TMUX_FAILED')
+ capture = await this.waitPane(session.agentId, (value) => !!parseCursorParameterRows(value), PICKER_STEP_MS)
if (!capture) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
if (cursorTarget.context) {
@@ -832,16 +832,16 @@ export class RuntimeProfileController {
await this.setCursorParameter(session, 'thinking', 'true', cursorTarget.thinking ?? false)
await this.setCursorParameter(session, 'fast', 'true', cursorTarget.fast ?? false)
- if (!await this.deps.sendKey(session.tmuxPane, 'Escape')) throw new RuntimeProfileControlError('TMUX_FAILED')
- if (!await this.waitPane(session.tmuxPane, (value) => !!parseCursorModelPicker(value), PICKER_STEP_MS)) {
+ if (!await this.deps.sendKey(session.agentId, 'Escape')) throw new RuntimeProfileControlError('TMUX_FAILED')
+ if (!await this.waitPane(session.agentId, (value) => !!parseCursorModelPicker(value), PICKER_STEP_MS)) {
throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
}
- if (!await this.deps.sendKey(session.tmuxPane, 'Enter')) throw new RuntimeProfileControlError('TMUX_FAILED')
+ if (!await this.deps.sendKey(session.agentId, 'Enter')) throw new RuntimeProfileControlError('TMUX_FAILED')
} else {
- if (!await this.deps.sendKey(session.tmuxPane, 'Enter')) throw new RuntimeProfileControlError('TMUX_FAILED')
+ if (!await this.deps.sendKey(session.agentId, 'Enter')) throw new RuntimeProfileControlError('TMUX_FAILED')
}
- const confirmed = await this.waitPane(session.tmuxPane, (value) => {
+ const confirmed = await this.waitPane(session.agentId, (value) => {
this.deps.manager.ingestPane(session, value, true)
return this.deps.manager.selectedModel(session) === target.id
|| this.cursorFooterMatches(value, cursorTarget, target.effort)
@@ -858,7 +858,7 @@ export class RuntimeProfileController {
value: string,
selected: boolean,
): Promise<void> {
- const capture = await this.deps.capture(session.tmuxPane, 100)
+ const capture = await this.deps.capture(session.agentId, 100)
const rows = capture ? parseCursorParameterRows(capture) : null
if (!rows) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
const target = rows.find((row) => row.kind === kind && row.value === value)
@@ -871,11 +871,11 @@ export class RuntimeProfileController {
if (!current) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
const direction = target.index > current.index ? 'Down' : 'Up'
for (let i = 0; i < Math.abs(target.index - current.index); i++) {
- if (!await this.deps.sendKey(session.tmuxPane, direction)) throw new RuntimeProfileControlError('TMUX_FAILED')
+ if (!await this.deps.sendKey(session.agentId, direction)) throw new RuntimeProfileControlError('TMUX_FAILED')
await sleep(120)
}
- if (!await this.deps.sendKey(session.tmuxPane, 'Enter')) throw new RuntimeProfileControlError('TMUX_FAILED')
- const updated = await this.waitPane(session.tmuxPane, (next) => {
+ if (!await this.deps.sendKey(session.agentId, 'Enter')) throw new RuntimeProfileControlError('TMUX_FAILED')
+ const updated = await this.waitPane(session.agentId, (next) => {
const nextRows = parseCursorParameterRows(next)
return nextRows?.some((row) => row.kind === kind && row.value === value && row.selected === selected) ?? false
}, PICKER_STEP_MS)
@@ -907,10 +907,10 @@ export class RuntimeProfileController {
})
}
- private async waitPane(pane: string, predicate: (capture: string) => boolean, timeoutMs: number): Promise<string | null> {
+ private async waitPane(terminalTarget: string, predicate: (capture: string) => boolean, timeoutMs: number): Promise<string | null> {
const deadline = Date.now() + timeoutMs
while (Date.now() < deadline) {
- const capture = await this.deps.capture(pane, 100)
+ const capture = await this.deps.capture(terminalTarget, 100)
if (capture && predicate(capture)) return capture
await sleep(100)
}
diff --git a/cli/src/lib/secureState.ts b/cli/src/lib/secureState.ts
new file mode 100644
index 000000000..7746de583
--- /dev/null
+++ b/cli/src/lib/secureState.ts
@@ -0,0 +1,91 @@
+import {
+ closeSync,
+ constants,
+ fchmodSync,
+ fstatSync,
+ mkdirSync,
+ openSync,
+ readFileSync,
+} from 'node:fs'
+
+const PRIVATE_DIRECTORY_MODE = 0o700
+const PRIVATE_FILE_MODE = 0o600
+
+function ownerUid(): number | null {
+ return typeof process.getuid === 'function' ? process.getuid() : null
+}
+
+function isMissing(error: unknown): boolean {
+ return (error as NodeJS.ErrnoException).code === 'ENOENT'
+}
+
+export function secureStateDirectory(directory: string, create = true): void {
+ if (create) mkdirSync(directory, { recursive: true, mode: PRIVATE_DIRECTORY_MODE })
+ const fd = openSync(
+ directory,
+ constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW,
+ )
+ try {
+ const stat = fstatSync(fd)
+ const uid = ownerUid()
+ if (!stat.isDirectory() || (uid !== null && stat.uid !== uid)) {
+ throw new Error('state directory has unsafe owner or type')
+ }
+ const mode = stat.mode & 0o777
+ if ((mode & 0o022) !== 0) throw new Error('state directory is group/world writable')
+ if (mode !== PRIVATE_DIRECTORY_MODE) {
+ fchmodSync(fd, PRIVATE_DIRECTORY_MODE)
+ if ((fstatSync(fd).mode & 0o777) !== PRIVATE_DIRECTORY_MODE) {
+ throw new Error('state directory permissions could not be tightened')
+ }
+ }
+ } finally {
+ closeSync(fd)
+ }
+}
+
+function inspectPrivateStateFile(fd: number, maxBytes: number): void {
+ const stat = fstatSync(fd)
+ const uid = ownerUid()
+ if (!stat.isFile() || (uid !== null && stat.uid !== uid)) {
+ throw new Error('state file has unsafe owner or type')
+ }
+ if (stat.size > maxBytes) throw new Error('state file exceeds its size limit')
+ const mode = stat.mode & 0o777
+ if ((mode & 0o022) !== 0) throw new Error('state file is group/world writable')
+ if (mode !== PRIVATE_FILE_MODE) {
+ fchmodSync(fd, PRIVATE_FILE_MODE)
+ if ((fstatSync(fd).mode & 0o777) !== PRIVATE_FILE_MODE) {
+ throw new Error('state file permissions could not be tightened')
+ }
+ }
+}
+
+export function readPrivateStateFile(file: string, maxBytes = Number.MAX_SAFE_INTEGER): string {
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
+ try {
+ inspectPrivateStateFile(fd, maxBytes)
+ return readFileSync(fd, 'utf8')
+ } finally {
+ closeSync(fd)
+ }
+}
+
+export function hardenPrivateStateFileIfPresent(
+ file: string,
+ maxBytes = Number.MAX_SAFE_INTEGER,
+): boolean {
+ let fd: number
+ try {
+ fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
+ } catch (error) {
+ if (isMissing(error)) return false
+ throw error
+ }
+ try {
+ inspectPrivateStateFile(fd, maxBytes)
+ return true
+ } finally {
+ closeSync(fd)
+ }
+}
diff --git a/cli/src/lib/sessionInput.spec.ts b/cli/src/lib/sessionInput.spec.ts
index c596827fa..a4c0d3195 100644
--- a/cli/src/lib/sessionInput.spec.ts
+++ b/cli/src/lib/sessionInput.spec.ts
@@ -1,11 +1,15 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { SessionInputController } from './sessionInput.js'
import type { RegisteredSession } from './registry.js'
+import type { TerminalActionResult } from './terminalTypes.js'
function session(engine: 'claude' | 'codex' | 'cursor' | 'commandcode' = 'codex'): RegisteredSession {
return {
+ schemaVersion: 2,
+ active: true,
sessionId: 's1', engine, launcherId: 'h1', agentId: 'h1', boundAt: 0, transcriptPath: '/tmp/s1.jsonl', projectDir: 'tmp', cwd: '/tmp',
tmuxPane: '%1', source: null, title: null, model: null, cliVersion: null, processIdentity: null,
+ runtimes: [{ backend: 'tmux', paneId: '%1' }], primaryRuntimeKey: 'tmux\u0000%1',
registeredAt: 1, updatedAt: 1, lastHookAt: 1, lastTranscriptAt: 1,
}
}
@@ -303,6 +307,147 @@ describe('SessionInputController', () => {
controller.forget('s1')
})
+ it('does not press Enter after an ambiguous submission when capture cannot prove the draft is pending', async () => {
+ vi.useFakeTimers()
+ const sendKey = vi.fn(async () => true)
+ const onError = vi.fn()
+ const ambiguous: TerminalActionResult = {
+ state: 'unknown', dispatch: 'possibly_executed', reason: 'response was lost',
+ }
+ const controller = new SessionInputController({
+ getSession: () => session('codex'),
+ validateRuntime: async () => true,
+ inject: async () => ambiguous,
+ sendKey,
+ onError,
+ })
+
+ controller.submit('s1', 'hello')
+ await vi.advanceTimersByTimeAsync(1_600)
+
+ expect(sendKey).not.toHaveBeenCalled()
+ expect(onError).toHaveBeenCalledWith('s1', expect.stringContaining('could not be confirmed'))
+ controller.forget('s1')
+ })
+
+ it('allows one evidence-backed Enter after an ambiguous submission leaves the exact draft in the composer', async () => {
+ vi.useFakeTimers()
+ const sendKey = vi.fn(async () => true)
+ const ambiguous: TerminalActionResult = {
+ state: 'unknown', dispatch: 'possibly_executed', reason: 'response was lost',
+ }
+ const controller = new SessionInputController({
+ getSession: () => session('codex'),
+ validateRuntime: async () => true,
+ inject: async () => ambiguous,
+ sendKey,
+ capture: async () => '› hello',
+ onError: vi.fn(),
+ })
+
+ controller.submit('s1', 'hello')
+ await vi.advanceTimersByTimeAsync(1_600)
+
+ expect(sendKey).toHaveBeenCalledTimes(1)
+ controller.forget('s1')
+ })
+
+ it('does not press Enter after ambiguous submission when repeated capture shows the draft absent', async () => {
+ vi.useFakeTimers()
+ const sendKey = vi.fn(async () => true)
+ const onError = vi.fn()
+ const ambiguous: TerminalActionResult = {
+ state: 'unknown', dispatch: 'possibly_executed', reason: 'response was lost',
+ }
+ const controller = new SessionInputController({
+ getSession: () => session('codex'),
+ validateRuntime: async () => true,
+ inject: async () => ambiguous,
+ sendKey,
+ capture: async () => '› \ngpt-5.6 medium ·',
+ onError,
+ })
+
+ controller.submit('s1', 'hello')
+ await vi.advanceTimersByTimeAsync(1_600 * 7)
+
+ expect(sendKey).not.toHaveBeenCalled()
+ expect(onError).toHaveBeenCalledWith('s1', expect.stringContaining('could not be confirmed'))
+ controller.forget('s1')
+ })
+
+ it('requires fresh draft evidence before retrying an ambiguously completed Enter', async () => {
+ vi.useFakeTimers()
+ const captures = ['› hello', null]
+ const sendKey = vi.fn(async (_target: string, _key: string): Promise<TerminalActionResult> => ({
+ state: 'unknown', dispatch: 'possibly_executed', reason: 'Enter response was lost',
+ }))
+ const onError = vi.fn()
+ const controller = new SessionInputController({
+ getSession: () => session('codex'),
+ validateRuntime: async () => true,
+ inject: async () => true,
+ sendKey,
+ capture: async () => captures.shift() ?? null,
+ onError,
+ })
+
+ controller.submit('s1', 'hello')
+ await vi.advanceTimersByTimeAsync(1_600 * 2)
+
+ expect(sendKey).toHaveBeenCalledTimes(1)
+ expect(onError).toHaveBeenCalledWith('s1', expect.stringContaining('could not be confirmed'))
+ controller.forget('s1')
+ })
+
+ it('does not re-arm Cursor after an ambiguous submission clears the exact draft', async () => {
+ vi.useFakeTimers()
+ const sendKey = vi.fn(async (_target: string, _key: string) => true)
+ const onError = vi.fn()
+ const ambiguous: TerminalActionResult = {
+ state: 'unknown', dispatch: 'possibly_executed', reason: 'response was lost',
+ }
+ const controller = new SessionInputController({
+ getSession: () => session('cursor'),
+ validateRuntime: async () => true,
+ inject: async () => ambiguous,
+ sendKey,
+ capture: async () => '→ \nAuto',
+ onError,
+ })
+
+ controller.submit('s1', 'hello')
+ await vi.advanceTimersByTimeAsync(1_600)
+
+ expect(sendKey.mock.calls.filter(([, key]) => key === 'Enter')).toHaveLength(0)
+ expect(onError).toHaveBeenCalledWith('s1', expect.stringContaining('could not be confirmed'))
+ controller.forget('s1')
+ })
+
+ it('requires fresh Cursor draft evidence after an ambiguously completed Enter', async () => {
+ vi.useFakeTimers()
+ const captures = ['→ hello\nAuto', null]
+ const sendKey = vi.fn(async (_target: string, _key: string): Promise<TerminalActionResult> => ({
+ state: 'unknown', dispatch: 'possibly_executed', reason: 'key response was lost',
+ }))
+ const onError = vi.fn()
+ const controller = new SessionInputController({
+ getSession: () => session('cursor'),
+ validateRuntime: async () => true,
+ inject: async () => true,
+ sendKey,
+ capture: async () => captures.shift() ?? null,
+ onError,
+ })
+
+ controller.submit('s1', 'hello')
+ await vi.advanceTimersByTimeAsync(1_600 * 2)
+
+ expect(sendKey.mock.calls.filter(([, key]) => key === 'Enter')).toHaveLength(1)
+ expect(onError).toHaveBeenCalledWith('s1', expect.stringContaining('could not be confirmed'))
+ controller.forget('s1')
+ })
+
it('serializes chat input behind a native runtime control lock', async () => {
const injected: string[] = []
const controller = new SessionInputController({
diff --git a/cli/src/lib/sessionInput.ts b/cli/src/lib/sessionInput.ts
index 00883dc47..a109e7436 100644
--- a/cli/src/lib/sessionInput.ts
+++ b/cli/src/lib/sessionInput.ts
@@ -1,6 +1,7 @@
import { createHash } from 'crypto'
import type { RegisteredSession } from './registry.js'
import { sid } from './log.js'
+import type { TerminalActionResult } from './terminalTypes.js'
const MAX_QUEUE_ITEMS = 8
const MAX_QUEUE_BYTES = 24 * 1024
@@ -63,14 +64,16 @@ interface InputState {
settleTimer: NodeJS.Timeout | null
retries: number
observes: number
+ ambiguousDispatch: boolean
}
export interface SessionInputDeps {
getSession: (sessionId: string) => RegisteredSession | undefined
validateRuntime: (session: RegisteredSession) => Promise<boolean>
- inject: (pane: string, content: string) => Promise<boolean>
- sendKey: (pane: string, key: string) => Promise<boolean>
- capture?: (pane: string) => Promise<string | null>
+ /** Boolean is retained for direct controller tests and legacy embedders. Production returns dispatch evidence. */
+ inject: (terminalTarget: string, content: string) => Promise<boolean | TerminalActionResult>
+ sendKey: (terminalTarget: string, key: string) => Promise<boolean | TerminalActionResult>
+ capture?: (terminalTarget: string) => Promise<string | null>
onError: (sessionId: string, message: string) => void
}
@@ -84,6 +87,11 @@ export class SessionInputController {
constructor(private readonly deps: SessionInputDeps) {}
+ /** Controller dependencies take the stable agent id, never a backend route. */
+ private controlSession(id: string): RegisteredSession | undefined {
+ return this.deps.getSession(id)
+ }
+
private state(sessionId: string): InputState {
let value = this.states.get(sessionId)
if (!value) {
@@ -98,6 +106,7 @@ export class SessionInputController {
settleTimer: null,
retries: 0,
observes: 0,
+ ambiguousDispatch: false,
}
this.states.set(sessionId, value)
}
@@ -109,7 +118,7 @@ export class SessionInputController {
}
submit(sessionId: string, content: string): void {
- const session = this.deps.getSession(sessionId)
+ const session = this.controlSession(sessionId)
if (!session) { this.deps.onError(sessionId, 'This agent is no longer available.'); return }
const state = this.state(sessionId)
this.dropExpired(sessionId, state)
@@ -124,7 +133,7 @@ export class SessionInputController {
/** Reserve this pane for a short native control interaction such as `/model`. */
acquireControl(sessionId: string): (() => void) | null {
- const session = this.deps.getSession(sessionId)
+ const session = this.controlSession(sessionId)
if (!session) return null
const state = this.state(sessionId)
this.dropExpired(sessionId, state)
@@ -160,6 +169,7 @@ export class SessionInputController {
state.awaitingContent = null
state.retries = 0
state.observes = 0
+ state.ambiguousDispatch = false
if (state.timer) clearTimeout(state.timer)
state.timer = null
}
@@ -173,12 +183,12 @@ export class SessionInputController {
* the terminal during the turn — a small window, but their keystrokes, not ours.
*/
private async clearCursorEcho(sessionId: string, userMessage: string): Promise<void> {
- const session = this.deps.getSession(sessionId)
+ const session = this.controlSession(sessionId)
if (session?.engine !== 'cursor' || !this.deps.capture) return
try {
- const capture = await this.deps.capture(session.tmuxPane)
+ const capture = await this.deps.capture(session.agentId)
if (!capture || !cursorComposerContains(capture, userMessage)) return
- await this.deps.sendKey(session.tmuxPane, 'C-u')
+ await this.deps.sendKey(session.agentId, 'C-u')
console.log(`[inject] ${sid(sessionId)} cleared the echoed prompt from the Cursor composer`)
} catch {
/* best-effort cosmetics — never let this break the turn */
@@ -192,9 +202,10 @@ export class SessionInputController {
state.awaitingContent = null
state.retries = 0
state.observes = 0
+ state.ambiguousDispatch = false
if (state.timer) clearTimeout(state.timer)
state.timer = null
- const session = this.deps.getSession(sessionId)
+ const session = this.controlSession(sessionId)
if (session?.engine === 'cursor') {
// Cursor's stop hook can arrive just before its TUI has returned to the idle composer. A prompt
// injected in that short window becomes a follow-up; Enter retries then enqueue it repeatedly.
@@ -211,15 +222,16 @@ export class SessionInputController {
}
cancel(sessionId: string): void {
- const session = this.deps.getSession(sessionId)
+ const session = this.controlSession(sessionId)
if (!session) return
void this.deps.validateRuntime(session).then(async (valid) => {
if (!valid) { this.deps.onError(sessionId, 'This agent process is no longer running.'); return }
- await this.deps.sendKey(session.tmuxPane, 'C-c')
+ await this.deps.sendKey(session.agentId, 'C-c')
const state = this.state(sessionId)
state.turnOpen = false
state.awaitingFingerprint = null
state.awaitingContent = null
+ state.ambiguousDispatch = false
if (state.timer) clearTimeout(state.timer)
state.timer = null
setTimeout(() => this.drainOne(sessionId, state), 250)
@@ -255,18 +267,23 @@ export class SessionInputController {
// C-u (kill-to-start-of-line) is a no-op on an empty composer, so this costs nothing in the normal
// case. It does discard a draft a human was typing in the terminal — but pasting into that draft
// would corrupt it into a run-on prompt anyway, which is worse and harder to notice.
- await this.deps.sendKey(session.tmuxPane, 'C-u')
+ await this.deps.sendKey(session.agentId, 'C-u')
}
- if (!(await this.deps.inject(session.tmuxPane, content))) {
- console.warn(`[inject] ${sid(sessionId)} paste failed · engine=${session.engine} · pane=${session.tmuxPane}`)
+ const delivery = await this.deps.inject(session.agentId, content)
+ const accepted = typeof delivery === 'boolean'
+ ? delivery
+ : delivery.state === 'succeeded' || delivery.dispatch === 'possibly_executed'
+ if (!accepted) {
+ console.warn(`[inject] ${sid(sessionId)} paste failed · engine=${session.engine} · target=${session.agentId}`)
this.deps.onError(sessionId, 'The message could not be delivered to the agent.')
return
}
- console.log(`[inject] ${sid(sessionId)} paste ok · engine=${session.engine} · pane=${session.tmuxPane} · len=${content.length}`)
+ console.log(`[inject] ${sid(sessionId)} paste ok · engine=${session.engine} · target=${session.agentId} · len=${content.length}`)
state.awaitingFingerprint = fingerprint(content)
state.awaitingContent = content
state.retries = 0
state.observes = 0
+ state.ambiguousDispatch = typeof delivery !== 'boolean' && delivery.dispatch === 'possibly_executed'
this.armSubmitCheck(sessionId, session, state)
}
@@ -301,15 +318,20 @@ export class SessionInputController {
private async retrySubmit(sessionId: string, session: RegisteredSession, state: InputState): Promise<void> {
if (session.engine === 'cursor') {
- const capture = await this.deps.capture?.(session.tmuxPane)
+ const capture = await this.deps.capture?.(session.agentId)
if (!state.awaitingFingerprint || state.turnOpen) return
+ const draftPending = !!capture && cursorComposerContains(capture, state.awaitingContent ?? '')
+ if (state.ambiguousDispatch && !draftPending) {
+ this.failAmbiguousSubmission(sessionId, state)
+ return
+ }
if (capture && cursorSubmissionAccepted(capture, state.awaitingContent ?? '')) {
// The transcript hook can trail the TUI by a moment. Observe again without pressing Enter:
// another Enter here would duplicate a running/queued follow-up.
this.armSubmitCheck(sessionId, session, state)
return
}
- if (!capture || !cursorComposerContains(capture, state.awaitingContent ?? '')) {
+ if (!draftPending) {
console.warn(`[inject] ${sid(sessionId)} not accepted · engine=cursor · composer clear of draft`)
state.awaitingFingerprint = null
state.awaitingContent = null
@@ -323,9 +345,13 @@ export class SessionInputController {
// derived turn_started (a new user row in opencode.db) to clear awaitingFingerprint; if it hasn't
// arrived yet, fall through to a bounded retry-Enter, then error.
if (!state.awaitingFingerprint || state.turnOpen) return
+ if (state.ambiguousDispatch) {
+ this.failAmbiguousSubmission(sessionId, state)
+ return
+ }
} else {
- // claude/codex/commandcode: verify against the pane before pressing Enter again or declaring failure.
- const capture = await this.deps.capture?.(session.tmuxPane)
+ // claude/codex/commandcode: verify against the terminal before pressing Enter again or declaring failure.
+ const capture = await this.deps.capture?.(session.agentId)
if (!state.awaitingFingerprint || state.turnOpen) return
// Command Code writes the user line to its transcript only once the model has finished THINKING, so
// the turn_started this used to wait for can be half a minute late on a real task — and the user
@@ -337,6 +363,7 @@ export class SessionInputController {
state.awaitingFingerprint = null
state.awaitingContent = null
state.observes = 0
+ state.ambiguousDispatch = false
return
}
if (capture && !terminalComposerContains(capture, state.awaitingContent ?? '')) {
@@ -349,15 +376,25 @@ export class SessionInputController {
this.armSubmitCheck(sessionId, session, state)
return
}
+ // An ambiguous dispatch with no visible draft still may have run. It can never justify Enter.
+ if (state.ambiguousDispatch) {
+ this.failAmbiguousSubmission(sessionId, state)
+ return
+ }
// Pathological: accepted-looking but no turn opened for a while → fall through to retry/error.
}
// capture === null (dep missing / unreadable) → fall through to today's blind retry/error so a
// real delivery failure is never hidden.
+ if (!capture && state.ambiguousDispatch) {
+ this.failAmbiguousSubmission(sessionId, state)
+ return
+ }
}
if (state.retries >= SUBMIT_MAX_RETRIES) {
console.warn(`[inject] ${sid(sessionId)} not accepted · engine=${session.engine} · gave up after ${state.retries} retries`)
state.awaitingFingerprint = null
state.awaitingContent = null
+ state.ambiguousDispatch = false
this.deps.onError(sessionId, 'The agent did not accept the message. Please try again.')
return
}
@@ -367,20 +404,31 @@ export class SessionInputController {
if (!valid) {
state.awaitingFingerprint = null
state.awaitingContent = null
+ state.ambiguousDispatch = false
this.deps.onError(sessionId, 'This agent process is no longer running.')
return
}
// Only the submit key is retried. The prompt body is never pasted twice.
- await this.deps.sendKey(session.tmuxPane, 'Enter')
+ const delivery = await this.deps.sendKey(session.agentId, 'Enter')
+ state.ambiguousDispatch = typeof delivery === 'boolean'
+ ? !delivery
+ : delivery.dispatch === 'possibly_executed'
this.armSubmitCheck(sessionId, session, state)
}
+ private failAmbiguousSubmission(sessionId: string, state: InputState): void {
+ state.awaitingFingerprint = null
+ state.awaitingContent = null
+ state.ambiguousDispatch = false
+ this.deps.onError(sessionId, 'The message delivery could not be confirmed. Check the agent before trying again.')
+ }
+
private drainOne(sessionId: string, state: InputState): void {
this.dropExpired(sessionId, state)
if (state.controlLocked || state.turnOpen || state.awaitingFingerprint || state.settling) return
const next = state.queue.shift()
if (!next) return
- const session = this.deps.getSession(sessionId)
+ const session = this.controlSession(sessionId)
if (!session) { this.deps.onError(sessionId, 'This agent is no longer available.'); return }
void this.inject(sessionId, session, next.content)
}
diff --git a/cli/src/lib/terminalAgentDiscovery.spec.ts b/cli/src/lib/terminalAgentDiscovery.spec.ts
new file mode 100644
index 000000000..af4ec2a19
--- /dev/null
+++ b/cli/src/lib/terminalAgentDiscovery.spec.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from 'vitest'
+import type { ProcessRow } from './tmux.js'
+import { discoverTerminalAgentsFromSnapshot } from './terminalAgentDiscovery.js'
+import { terminalRouteKey } from './terminalRuntime.js'
+import type { TerminalRootObservation } from './terminalTypes.js'
+
+const start = 'Sat Aug 15 10:00:00 2026'
+const shell = (pid: number, parentPid: number): ProcessRow => ({ pid, parentPid, executable: 'bash', startMarker: start, args: 'bash' })
+const claude = (pid: number, parentPid: number): ProcessRow => ({ pid, parentPid, executable: 'claude', startMarker: start, args: 'claude' })
+
+const tmux: TerminalRootObservation = {
+ runtime: { backend: 'tmux', paneId: '%1' }, rootPid: 10, cwd: '/work',
+}
+const herdr: TerminalRootObservation = {
+ runtime: {
+ backend: 'herdr', endpointId: 'endpoint-a', sessionName: 'default', terminalId: 'terminal-a', paneId: 'w1:p1',
+ },
+ rootPid: 20,
+ cwd: '/work',
+}
+
+describe('backend-neutral process discovery', () => {
+ it('deduplicates nested/coexisting roots by engine PID and start marker', () => {
+ const result = discoverTerminalAgentsFromSnapshot(
+ [tmux, herdr],
+ [shell(10, 1), shell(20, 10), claude(30, 20)],
+ 999,
+ ['tmux', 'herdr'],
+ ['default'],
+ )
+ expect(result.agents).toHaveLength(1)
+ expect(result.agents[0].runtimes).toHaveLength(2)
+ expect(result.agents[0].primaryRuntimeKey).toBe(terminalRouteKey(herdr.runtime))
+ })
+
+ it('keeps duplicate public Herdr routes distinct across endpoints', () => {
+ const second = {
+ ...herdr,
+ runtime: { ...herdr.runtime, endpointId: 'endpoint-b', sessionName: 'work', terminalId: 'terminal-b' },
+ rootPid: 40,
+ } as TerminalRootObservation
+ const result = discoverTerminalAgentsFromSnapshot(
+ [herdr, second],
+ [shell(20, 1), claude(30, 20), shell(40, 1), claude(50, 40)],
+ 999,
+ ['herdr'],
+ ['default', 'work'],
+ )
+ expect(result.agents).toHaveLength(2)
+ expect(result.agents.map((agent) => agent.primaryRuntimeKey)).toEqual([
+ terminalRouteKey(herdr.runtime),
+ terminalRouteKey(second.runtime),
+ ])
+ })
+
+ it('chooses the nearest root before configured backend order', () => {
+ const result = discoverTerminalAgentsFromSnapshot(
+ [tmux, herdr],
+ [shell(20, 1), shell(25, 20), shell(10, 25), claude(30, 10)],
+ 999,
+ ['tmux', 'herdr'],
+ ['default'],
+ )
+ expect(result.agents[0].primaryRuntimeKey).toBe(terminalRouteKey(tmux.runtime))
+ })
+})
diff --git a/cli/src/lib/terminalAgentDiscovery.ts b/cli/src/lib/terminalAgentDiscovery.ts
new file mode 100644
index 000000000..5123eabd4
--- /dev/null
+++ b/cli/src/lib/terminalAgentDiscovery.ts
@@ -0,0 +1,224 @@
+import type { AgentEngine } from '../engines/types.js'
+import {
+ agentAliasOwner,
+ agentCommandOwnershipSnapshot,
+ ENGINES,
+ type AgentCommandOwnershipSnapshot,
+} from './engineBin.js'
+import type { TerminalBackend } from './terminalBackend.js'
+import {
+ ambiguousAgentProcess,
+ engineProcessMatchScore,
+ processRows,
+ resumeSessionId,
+ type ProcessRow,
+} from './tmux.js'
+import { processIdentityKey, terminalInstanceId, terminalPlacementKey, terminalRouteKey } from './terminalRuntime.js'
+import type {
+ ProcessIdentity,
+ TerminalInventoryResult,
+ TerminalRootObservation,
+ TerminalRuntimeRef,
+} from './terminalTypes.js'
+
+export { processRows } from './tmux.js'
+
+export interface DiscoveredTerminalAgent {
+ engine: AgentEngine
+ cwd: string
+ processIdentity: ProcessIdentity
+ args: string
+ resumeSessionId: string | null
+ runtimes: TerminalRuntimeRef[]
+ primaryRuntimeKey: string
+}
+
+export interface TerminalTargetProbe {
+ instanceId: string
+ result: TerminalInventoryResult
+}
+
+export interface TerminalAgentProbe {
+ processTableAvailable: boolean
+ targets: TerminalTargetProbe[]
+ agents: DiscoveredTerminalAgent[]
+ ambiguousPlacements: Set<string>
+}
+
+interface RootOwner {
+ agent: Omit<DiscoveredTerminalAgent, 'runtimes' | 'primaryRuntimeKey'> | null
+ depth: number
+ ambiguous: boolean
+}
+
+function childrenByParent(rows: readonly ProcessRow[]): Map<number, ProcessRow[]> {
+ const children = new Map<number, ProcessRow[]>()
+ for (const row of rows) {
+ const list = children.get(row.parentPid) ?? []
+ list.push(row)
+ children.set(row.parentPid, list)
+ }
+ return children
+}
+
+function daemonDescendants(rows: readonly ProcessRow[], daemonPid: number): Set<number> {
+ const children = childrenByParent(rows)
+ const excluded = new Set<number>()
+ const queue = [daemonPid]
+ while (queue.length) {
+ const pid = queue.shift()!
+ if (excluded.has(pid)) continue
+ excluded.add(pid)
+ for (const child of children.get(pid) ?? []) queue.push(child.pid)
+ }
+ return excluded
+}
+
+function rootOwner(
+ root: TerminalRootObservation,
+ rows: readonly ProcessRow[],
+ excluded: ReadonlySet<number>,
+ ownership: AgentCommandOwnershipSnapshot,
+ hintedEngine?: AgentEngine,
+): RootOwner {
+ const byPid = new Map(rows.map((row) => [row.pid, row]))
+ const children = childrenByParent(rows)
+ const queue: Array<{ pid: number; depth: number }> = [{ pid: root.rootPid, depth: 0 }]
+ const matches: Array<{ row: ProcessRow; engine: AgentEngine; depth: number; score: number }> = []
+ let unresolvedAliasDepth = Number.POSITIVE_INFINITY
+
+ while (queue.length) {
+ const current = queue.shift()!
+ const row = byPid.get(current.pid)
+ if (row && !excluded.has(row.pid)) {
+ for (const engine of ENGINES) {
+ const score = engineProcessMatchScore(row, engine, ownership)
+ if (score > 0) matches.push({ row, engine, depth: current.depth, score })
+ }
+ if (ambiguousAgentProcess(row, ownership)) {
+ const aliasOwner = agentAliasOwner([row.imageFileKey, row.entrypointFileKey], ownership)
+ if (aliasOwner === 'unknown' && (hintedEngine === 'cursor' || hintedEngine === 'grok')) {
+ matches.push({ row, engine: hintedEngine, depth: current.depth, score: 1 })
+ } else {
+ unresolvedAliasDepth = Math.min(unresolvedAliasDepth, current.depth)
+ }
+ }
+ }
+ for (const child of children.get(current.pid) ?? []) queue.push({ pid: child.pid, depth: current.depth + 1 })
+ }
+
+ if (!matches.length) return { agent: null, depth: Number.POSITIVE_INFINITY, ambiguous: Number.isFinite(unresolvedAliasDepth) }
+ const shallowest = Math.min(...matches.map((match) => match.depth))
+ if (unresolvedAliasDepth <= shallowest) return { agent: null, depth: shallowest, ambiguous: true }
+ const atDepth = matches.filter((match) => match.depth === shallowest)
+ const strongest = Math.max(...atDepth.map((match) => match.score))
+ const finalists = atDepth.filter((match) => match.score === strongest)
+ const unique = new Map(finalists.map((match) => [`${match.row.pid}:${match.engine}`, match]))
+ if (unique.size !== 1) return { agent: null, depth: shallowest, ambiguous: true }
+
+ const [{ row, engine }] = [...unique.values()]
+ return {
+ depth: shallowest,
+ ambiguous: false,
+ agent: {
+ engine,
+ cwd: root.cwd,
+ processIdentity: { pid: row.pid, executable: row.executable, startMarker: row.startMarker },
+ args: row.args,
+ resumeSessionId: resumeSessionId(engine, row.args),
+ },
+ }
+}
+
+function runtimeRank(runtime: TerminalRuntimeRef, backendOrder: readonly string[], herdrSessionOrder: readonly string[]): number[] {
+ const backend = backendOrder.indexOf(runtime.backend)
+ const session = runtime.backend === 'herdr' ? herdrSessionOrder.indexOf(runtime.sessionName) : 0
+ return [backend < 0 ? Number.MAX_SAFE_INTEGER : backend, session < 0 ? Number.MAX_SAFE_INTEGER : session]
+}
+
+function rankBefore(a: number[], b: number[]): boolean {
+ return a[0] < b[0] || (a[0] === b[0] && a[1] < b[1])
+}
+
+/** Pure process-authoritative merge used by fixtures and the live coordinator. */
+export function discoverTerminalAgentsFromSnapshot(
+ roots: readonly TerminalRootObservation[],
+ rows: readonly ProcessRow[],
+ daemonPid: number,
+ backendOrder: readonly string[],
+ herdrSessionOrder: readonly string[],
+ hints: ReadonlyMap<string, AgentEngine> = new Map(),
+ ownership = agentCommandOwnershipSnapshot(),
+): { agents: DiscoveredTerminalAgent[]; ambiguousPlacements: Set<string> } {
+ const excluded = daemonDescendants(rows, daemonPid)
+ const grouped = new Map<string, {
+ agent: Omit<DiscoveredTerminalAgent, 'runtimes' | 'primaryRuntimeKey'>
+ observations: Array<{ runtime: TerminalRuntimeRef; depth: number; cwd: string }>
+ }>()
+ const ambiguousPlacements = new Set<string>()
+
+ for (const root of roots) {
+ const owner = rootOwner(root, rows, excluded, ownership, hints.get(terminalRouteKey(root.runtime)))
+ if (owner.ambiguous) {
+ ambiguousPlacements.add(terminalPlacementKey(root.runtime))
+ continue
+ }
+ if (!owner.agent) continue
+ const key = processIdentityKey(owner.agent.engine, owner.agent.processIdentity)
+ const group = grouped.get(key) ?? { agent: owner.agent, observations: [] }
+ group.observations.push({ runtime: root.runtime, depth: owner.depth, cwd: root.cwd })
+ grouped.set(key, group)
+ }
+
+ const agents = [...grouped.values()].map(({ agent, observations }): DiscoveredTerminalAgent => {
+ const byPlacement = new Map<string, { runtime: TerminalRuntimeRef; depth: number; cwd: string }>()
+ for (const observation of observations) byPlacement.set(terminalPlacementKey(observation.runtime), observation)
+ const ordered = [...byPlacement.values()].sort((a, b) => {
+ if (a.depth !== b.depth) return a.depth - b.depth
+ const ar = runtimeRank(a.runtime, backendOrder, herdrSessionOrder)
+ const br = runtimeRank(b.runtime, backendOrder, herdrSessionOrder)
+ if (rankBefore(ar, br)) return -1
+ if (rankBefore(br, ar)) return 1
+ return terminalPlacementKey(a.runtime).localeCompare(terminalPlacementKey(b.runtime))
+ })
+ return {
+ ...agent,
+ cwd: ordered[0].cwd,
+ runtimes: ordered.map((observation) => observation.runtime),
+ primaryRuntimeKey: terminalRouteKey(ordered[0].runtime),
+ }
+ })
+ return { agents, ambiguousPlacements }
+}
+
+/** Probe all targets independently while reading the OS process table exactly once. */
+export async function probeTerminalAgents(
+ backends: readonly TerminalBackend[],
+ backendOrder: readonly string[],
+ herdrSessionOrder: readonly string[],
+ daemonPid = process.pid,
+ hints: ReadonlyMap<string, AgentEngine> = new Map(),
+): Promise<TerminalAgentProbe> {
+ const [targets, rows] = await Promise.all([
+ Promise.all(backends.map(async (backend): Promise<TerminalTargetProbe> => ({
+ instanceId: backend.instanceId,
+ result: await backend.inventory().catch(() => ({ state: 'unavailable' as const, reason: 'terminal inventory failed' })),
+ }))),
+ processRows(),
+ ])
+ if (!rows) return { processTableAvailable: false, targets, agents: [], ambiguousPlacements: new Set() }
+ const roots = targets.flatMap((target) => target.result.state === 'available' ? target.result.roots : [])
+ const discovered = discoverTerminalAgentsFromSnapshot(
+ roots,
+ rows,
+ daemonPid,
+ backendOrder,
+ herdrSessionOrder,
+ hints,
+ )
+ return { processTableAvailable: true, targets, ...discovered }
+}
+
+export function targetForRuntime(probe: TerminalAgentProbe, runtime: TerminalRuntimeRef): TerminalTargetProbe | undefined {
+ return probe.targets.find((target) => target.instanceId === terminalInstanceId(runtime))
+}
diff --git a/cli/src/lib/terminalAgentReconciler.spec.ts b/cli/src/lib/terminalAgentReconciler.spec.ts
new file mode 100644
index 000000000..4d732f0a0
--- /dev/null
+++ b/cli/src/lib/terminalAgentReconciler.spec.ts
@@ -0,0 +1,123 @@
+import { describe, expect, it, vi } from 'vitest'
+import type { RegisteredSession } from './registry.js'
+import type { DiscoveredTerminalAgent, TerminalAgentProbe } from './terminalAgentDiscovery.js'
+import { TerminalAgentReconciler } from './terminalAgentReconciler.js'
+import { terminalRouteKey } from './terminalRuntime.js'
+import type { TerminalRuntimeRef } from './terminalTypes.js'
+
+const tmux: TerminalRuntimeRef = { backend: 'tmux', paneId: '%1' }
+const herdr: TerminalRuntimeRef = {
+ backend: 'herdr', endpointId: 'endpoint-a', sessionName: 'default', terminalId: 'terminal-a', paneId: 'w1:p1',
+}
+const identity = { pid: 42, executable: 'claude', startMarker: 'Sat Aug 15 10:00:00 2026' }
+
+function session(runtimes: TerminalRuntimeRef[] = [tmux]): RegisteredSession {
+ return {
+ schemaVersion: 2, active: true, agentId: 'agent-1', sessionId: '', boundAt: null, engine: 'claude',
+ transcriptPath: null, projectDir: 'work', cwd: '/work', runtimes,
+ primaryRuntimeKey: terminalRouteKey(runtimes[0]), tmuxPane: runtimes.find((runtime) => runtime.backend === 'tmux')?.paneId ?? '',
+ source: null, title: null, model: null, cliVersion: null, processIdentity: identity,
+ registeredAt: 1, updatedAt: 1, lastHookAt: 1, lastTranscriptAt: 1,
+ }
+}
+
+function observed(runtimes: TerminalRuntimeRef[]): DiscoveredTerminalAgent {
+ return {
+ engine: 'claude', cwd: '/work', processIdentity: identity, args: 'claude', resumeSessionId: null,
+ runtimes, primaryRuntimeKey: terminalRouteKey(runtimes[0]),
+ }
+}
+
+function probe(targets: TerminalAgentProbe['targets'], agents: DiscoveredTerminalAgent[] = []): TerminalAgentProbe {
+ return { processTableAvailable: true, targets, agents, ambiguousPlacements: new Set() }
+}
+
+describe('composite terminal reconciliation', () => {
+ it('does not count an unavailable endpoint as a confirmed miss', async () => {
+ const current = session([herdr])
+ const onDormant = vi.fn()
+ const onRemoved = vi.fn()
+ const reconciler = new TerminalAgentReconciler({
+ current: () => [current], backends: [], backendOrder: ['herdr'], herdrSessionOrder: ['default'],
+ onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant, onRemoved,
+ probe: async () => probe([{ instanceId: 'herdr:endpoint-a', result: { state: 'unavailable', reason: 'stopped' } }]),
+ })
+ await reconciler.trigger()
+ await reconciler.trigger()
+ expect(onDormant).toHaveBeenCalledTimes(2)
+ expect(onRemoved).not.toHaveBeenCalled()
+ })
+
+ it('refreshes configured targets before every cycle so an initially stopped Herdr session can recover', async () => {
+ const current = session([herdr])
+ const onObserved = vi.fn()
+ const onRemoved = vi.fn()
+ let available = false
+ const beforeProbe = vi.fn(async () => { available = beforeProbe.mock.calls.length > 1 })
+ const reconciler = new TerminalAgentReconciler({
+ current: () => [current], backends: [], backendOrder: ['herdr'], herdrSessionOrder: ['default'],
+ onDiscovered: vi.fn(), onObserved, onDormant: vi.fn(), onRemoved, beforeProbe,
+ probe: async () => available
+ ? probe(
+ [{ instanceId: 'herdr:endpoint-a', result: { state: 'available', roots: [{ runtime: herdr, rootPid: 1, cwd: '/work' }] } }],
+ [observed([herdr])],
+ )
+ : probe([{ instanceId: 'herdr:endpoint-a', result: { state: 'unavailable', reason: 'stopped' } }]),
+ })
+
+ await reconciler.trigger()
+ expect(onObserved).not.toHaveBeenCalled()
+ await reconciler.trigger()
+
+ expect(beforeProbe).toHaveBeenCalledTimes(2)
+ expect(onObserved).toHaveBeenCalledWith(expect.objectContaining({ runtimes: [herdr] }), current)
+ expect(onRemoved).not.toHaveBeenCalled()
+ })
+
+ it('removes only after two successful negative inventories', async () => {
+ const current = session([herdr])
+ const onRemoved = vi.fn()
+ const reconciler = new TerminalAgentReconciler({
+ current: () => [current], backends: [], backendOrder: ['herdr'], herdrSessionOrder: ['default'],
+ onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant: vi.fn(), onRemoved,
+ probe: async () => probe([{ instanceId: 'herdr:endpoint-a', result: { state: 'available', roots: [] } }]),
+ })
+ await reconciler.trigger()
+ expect(onRemoved).not.toHaveBeenCalled()
+ await reconciler.trigger()
+ expect(onRemoved).toHaveBeenCalledWith(current, 'terminal runtime absent after 2 confirmed scans')
+ })
+
+ it('refreshes a moved Herdr route on the same process without changing agent ownership', async () => {
+ const current = session([herdr])
+ const moved = { ...herdr, paneId: 'w2:p4' }
+ const onObserved = vi.fn()
+ const reconciler = new TerminalAgentReconciler({
+ current: () => [current], backends: [], backendOrder: ['herdr'], herdrSessionOrder: ['default'],
+ onDiscovered: vi.fn(), onObserved, onDormant: vi.fn(), onRemoved: vi.fn(),
+ probe: async () => probe(
+ [{ instanceId: 'herdr:endpoint-a', result: { state: 'available', roots: [{ runtime: moved, rootPid: 1, cwd: '/work' }] } }],
+ [observed([moved])],
+ ),
+ })
+ await reconciler.trigger()
+ expect(onObserved).toHaveBeenCalledWith(expect.objectContaining({ runtimes: [moved] }), current)
+ })
+
+ it('keeps a healthy locator active when another backend is unavailable', async () => {
+ const current = session([tmux, herdr])
+ const onObserved = vi.fn()
+ const onDormant = vi.fn()
+ const reconciler = new TerminalAgentReconciler({
+ current: () => [current], backends: [], backendOrder: ['tmux', 'herdr'], herdrSessionOrder: ['default'],
+ onDiscovered: vi.fn(), onObserved, onDormant, onRemoved: vi.fn(),
+ probe: async () => probe([
+ { instanceId: 'tmux:default', result: { state: 'available', roots: [{ runtime: tmux, rootPid: 1, cwd: '/work' }] } },
+ { instanceId: 'herdr:endpoint-a', result: { state: 'unavailable', reason: 'stopped' } },
+ ], [observed([tmux])]),
+ })
+ await reconciler.trigger()
+ expect(onObserved).toHaveBeenCalledWith(expect.objectContaining({ runtimes: [herdr, tmux] }), current)
+ expect(onDormant).not.toHaveBeenCalled()
+ })
+})
diff --git a/cli/src/lib/terminalAgentReconciler.ts b/cli/src/lib/terminalAgentReconciler.ts
new file mode 100644
index 000000000..368f70047
--- /dev/null
+++ b/cli/src/lib/terminalAgentReconciler.ts
@@ -0,0 +1,180 @@
+import type { AgentEngine } from '../engines/types.js'
+import type { RegisteredSession } from './registry.js'
+import {
+ probeTerminalAgents,
+ targetForRuntime,
+ type DiscoveredTerminalAgent,
+ type TerminalAgentProbe,
+} from './terminalAgentDiscovery.js'
+import type { TerminalBackend } from './terminalBackend.js'
+import { mergeTerminalRuntimes, processIdentityKey, terminalPlacementKey, terminalRouteKey } from './terminalRuntime.js'
+import type { TerminalRuntimeRef } from './terminalTypes.js'
+
+const MISS_LIMIT = 2
+
+export interface TerminalAgentReconcilerDeps {
+ current: () => RegisteredSession[]
+ backends: readonly TerminalBackend[]
+ backendOrder: readonly string[]
+ herdrSessionOrder: readonly string[]
+ onDiscovered: (agent: DiscoveredTerminalAgent) => void | Promise<void>
+ onObserved: (agent: DiscoveredTerminalAgent, current: RegisteredSession) => void | Promise<void>
+ onDormant: (current: RegisteredSession, reason: string) => void | Promise<void>
+ onRemoved: (current: RegisteredSession, reason: string) => void | Promise<void>
+ transaction?: <T>(apply: () => T | Promise<T>) => Promise<T>
+ /** Refresh configured backend instances before each immutable probe cycle. */
+ beforeProbe?: () => void | Promise<void>
+ probe?: (hints: ReadonlyMap<string, AgentEngine>) => Promise<TerminalAgentProbe>
+ daemonPid?: number
+}
+
+function currentProcessKey(session: RegisteredSession): string | null {
+ return session.processIdentity ? processIdentityKey(session.engine, session.processIdentity) : null
+}
+
+/** Serialized, failure-isolated reconciliation across every enabled backend instance. */
+export class TerminalAgentReconciler {
+ private readonly misses = new Map<string, number>()
+ private readonly suppressed = new Set<string>()
+ private readonly hints = new Map<string, AgentEngine>()
+ private pending = false
+ private inFlight: Promise<void> | null = null
+ private timer: NodeJS.Timeout | null = null
+
+ constructor(private readonly deps: TerminalAgentReconcilerDeps) {}
+
+ start(intervalMs: number): void {
+ void this.trigger()
+ this.timer = setInterval(() => { void this.trigger() }, intervalMs)
+ this.timer.unref?.()
+ }
+
+ stop(): void {
+ if (this.timer) clearInterval(this.timer)
+ this.timer = null
+ }
+
+ triggerHint(runtime: TerminalRuntimeRef, engine: AgentEngine): Promise<void> {
+ this.hints.set(terminalRouteKey(runtime), engine)
+ return this.trigger()
+ }
+
+ /** Hide an explicitly deleted process until an authoritative scan proves that process exited. */
+ suppress(session: Pick<RegisteredSession, 'engine' | 'processIdentity'>): void {
+ if (session.processIdentity) this.suppressed.add(processIdentityKey(session.engine, session.processIdentity))
+ }
+
+ trigger(): Promise<void> {
+ this.pending = true
+ if (!this.inFlight) this.inFlight = this.drain().finally(() => { this.inFlight = null })
+ return this.inFlight
+ }
+
+ private async drain(): Promise<void> {
+ while (this.pending) {
+ this.pending = false
+ await this.reconcileOnce()
+ }
+ }
+
+ private async reconcileOnce(): Promise<void> {
+ await this.deps.beforeProbe?.()
+ const hints = new Map(this.hints)
+ const probe = await (this.deps.probe
+ ? this.deps.probe(hints)
+ : probeTerminalAgents(
+ this.deps.backends,
+ this.deps.backendOrder,
+ this.deps.herdrSessionOrder,
+ this.deps.daemonPid ?? process.pid,
+ hints,
+ ))
+ if (!probe.processTableAvailable) {
+ console.warn('[discovery] process table unavailable; keeping existing terminal agents')
+ return
+ }
+ this.hints.clear()
+
+ const observedKeys = new Set(probe.agents.map((agent) => processIdentityKey(agent.engine, agent.processIdentity)))
+ for (const key of [...this.suppressed]) if (!observedKeys.has(key)) this.suppressed.delete(key)
+ probe.agents = probe.agents.filter((agent) => !this.suppressed.has(processIdentityKey(agent.engine, agent.processIdentity)))
+
+ const apply = async (): Promise<void> => {
+ const before = this.deps.current()
+ const observedByProcess = new Map(probe.agents.map((agent) => [
+ processIdentityKey(agent.engine, agent.processIdentity),
+ agent,
+ ]))
+ const matchedProcesses = new Set<string>()
+
+ // Refresh existing process identities first. New route owners are opened afterwards so split/merge
+ // conflict handling never depends on backend probe completion order.
+ for (const current of before) {
+ const processKey = currentProcessKey(current)
+ const observed = processKey ? observedByProcess.get(processKey) : undefined
+ if (observed) matchedProcesses.add(processKey!)
+
+ let nextRuntimes = current.runtimes
+ for (const runtime of current.runtimes) {
+ const target = targetForRuntime(probe, runtime)
+ if (!target || target.result.state !== 'available') continue
+ const placement = terminalPlacementKey(runtime)
+ if (probe.ambiguousPlacements.has(placement)) continue
+ const replacement = observed?.runtimes.find((candidate) => terminalPlacementKey(candidate) === placement)
+ const missKey = `${current.agentId}\u0000${placement}`
+ if (replacement) {
+ this.misses.delete(missKey)
+ nextRuntimes = mergeTerminalRuntimes(nextRuntimes, [replacement])
+ continue
+ }
+ const misses = (this.misses.get(missKey) ?? 0) + 1
+ if (misses < MISS_LIMIT) {
+ this.misses.set(missKey, misses)
+ continue
+ }
+ this.misses.delete(missKey)
+ nextRuntimes = nextRuntimes.filter((candidate) => terminalPlacementKey(candidate) !== placement)
+ }
+
+ if (observed) {
+ const availableInstances = new Set(probe.targets
+ .filter((target) => target.result.state === 'available')
+ .map((target) => target.instanceId))
+ const unknownRuntimes = current.runtimes.filter((runtime) => !availableInstances.has(
+ runtime.backend === 'tmux' ? 'tmux:default' : `herdr:${runtime.endpointId}`,
+ ))
+ const merged: DiscoveredTerminalAgent = {
+ ...observed,
+ runtimes: mergeTerminalRuntimes(unknownRuntimes, [...nextRuntimes, ...observed.runtimes]),
+ }
+ await this.deps.onObserved(merged, current)
+ } else if (nextRuntimes.length < current.runtimes.length && nextRuntimes.length > 0) {
+ await this.deps.onObserved({
+ engine: current.engine,
+ cwd: current.cwd ?? '',
+ processIdentity: current.processIdentity!,
+ args: current.processIdentity?.executable ?? '',
+ resumeSessionId: null,
+ runtimes: nextRuntimes,
+ primaryRuntimeKey: nextRuntimes.some((runtime) => terminalRouteKey(runtime) === current.primaryRuntimeKey)
+ ? current.primaryRuntimeKey
+ : terminalRouteKey(nextRuntimes[0]),
+ }, current)
+ await this.deps.onDormant(current, 'no terminal runtime currently verifies this process')
+ } else if (nextRuntimes.length === 0) {
+ await this.deps.onRemoved(current, `terminal runtime absent after ${MISS_LIMIT} confirmed scans`)
+ } else {
+ await this.deps.onDormant(current, 'no terminal runtime currently verifies this process')
+ }
+ }
+
+ for (const observed of probe.agents) {
+ const key = processIdentityKey(observed.engine, observed.processIdentity)
+ if (!matchedProcesses.has(key)) await this.deps.onDiscovered(observed)
+ }
+ }
+
+ if (this.deps.transaction) await this.deps.transaction(apply)
+ else await apply()
+ }
+}
diff --git a/cli/src/lib/terminalBackend.ts b/cli/src/lib/terminalBackend.ts
new file mode 100644
index 000000000..e8d2dc342
--- /dev/null
+++ b/cli/src/lib/terminalBackend.ts
@@ -0,0 +1,32 @@
+import type {
+ TerminalActionResult,
+ TerminalBackendName,
+ TerminalCaptureOptions,
+ TerminalCreateRequest,
+ TerminalCreateResult,
+ TerminalInventoryResult,
+ TerminalLogicalKey,
+ TerminalProcessExpectation,
+ TerminalReadResult,
+ TerminalRuntimeRef,
+ RuntimeValidation,
+} from './terminalTypes.js'
+
+/** Backend-specific terminal I/O. Process ownership and registry reconciliation deliberately live above it. */
+export interface TerminalBackend<Ref extends TerminalRuntimeRef = TerminalRuntimeRef> {
+ readonly name: TerminalBackendName
+ readonly instanceId: string
+
+ create(request: TerminalCreateRequest): Promise<TerminalCreateResult<Ref>>
+ kill(runtime: Ref): Promise<TerminalActionResult>
+ inventory(): Promise<TerminalInventoryResult>
+ /** Current user-visible titles keyed by backend-scoped terminal route key. */
+ titles(): Promise<TerminalReadResult<Map<string, string>>>
+ validate(runtime: Ref, expected: TerminalProcessExpectation): Promise<RuntimeValidation>
+ capture(runtime: Ref, options?: TerminalCaptureOptions): Promise<TerminalReadResult<string>>
+ typeLiteral(runtime: Ref, text: string): Promise<TerminalActionResult>
+ submitText(runtime: Ref, text: string): Promise<TerminalActionResult>
+ sendKey(runtime: Ref, key: TerminalLogicalKey): Promise<TerminalActionResult>
+ setTitle(runtime: Ref, title: string): Promise<TerminalActionResult>
+ notify(runtime: Ref, title: string, body: string): Promise<TerminalActionResult>
+}
diff --git a/cli/src/lib/terminalBackendCoordinator.spec.ts b/cli/src/lib/terminalBackendCoordinator.spec.ts
new file mode 100644
index 000000000..ef0180df2
--- /dev/null
+++ b/cli/src/lib/terminalBackendCoordinator.spec.ts
@@ -0,0 +1,143 @@
+import { describe, expect, it, vi } from 'vitest'
+import type { RegisteredSession } from './registry.js'
+import type { TerminalBackend } from './terminalBackend.js'
+import { TerminalBackendCoordinator } from './terminalBackendCoordinator.js'
+import { terminalRouteKey } from './terminalRuntime.js'
+import type { TerminalRuntimeRef } from './terminalTypes.js'
+
+const tmux: TerminalRuntimeRef = { backend: 'tmux', paneId: '%1' }
+const herdr: TerminalRuntimeRef = {
+ backend: 'herdr', endpointId: 'endpoint-a', sessionName: 'default', terminalId: 'terminal-a', paneId: 'w1:p1',
+}
+
+function session(): RegisteredSession {
+ return {
+ schemaVersion: 2, active: true, agentId: 'agent-1', sessionId: 's1', boundAt: 1, engine: 'claude', transcriptPath: null,
+ projectDir: 'work', cwd: '/work', runtimes: [tmux, herdr], primaryRuntimeKey: terminalRouteKey(tmux), tmuxPane: '%1',
+ source: null, title: null, model: null, cliVersion: null,
+ processIdentity: { pid: 42, executable: 'claude', startMarker: 'Sat Aug 15 10:00:00 2026' },
+ registeredAt: 1, updatedAt: 1, lastHookAt: 1, lastTranscriptAt: 1,
+ }
+}
+
+function backend(instanceId: string, submit: TerminalBackend['submitText']): TerminalBackend {
+ return {
+ name: instanceId.startsWith('tmux') ? 'tmux' : 'herdr', instanceId,
+ create: vi.fn(), kill: vi.fn(), inventory: vi.fn(),
+ titles: vi.fn(async () => ({ state: 'succeeded' as const, value: new Map() })),
+ validate: vi.fn(async () => ({ state: 'alive' as const })), capture: vi.fn(), typeLiteral: vi.fn(), submitText: submit,
+ sendKey: vi.fn(), setTitle: vi.fn(), notify: vi.fn(),
+ }
+}
+
+describe('TerminalBackendCoordinator', () => {
+ it('merges backend-scoped title snapshots and prefers the primary runtime title', async () => {
+ const first = backend('tmux:default', vi.fn())
+ first.titles = vi.fn(async () => ({ state: 'succeeded' as const, value: new Map([[terminalRouteKey(tmux), 'tmux title']]) }))
+ const second = backend('herdr:endpoint-a', vi.fn())
+ second.titles = vi.fn(async () => ({ state: 'succeeded' as const, value: new Map([[terminalRouteKey(herdr), 'Herdr title']]) }))
+ const coordinator = new TerminalBackendCoordinator([first, second], ['herdr', 'tmux'], ['default'])
+ const current = session()
+ current.primaryRuntimeKey = terminalRouteKey(herdr)
+ const titles = await coordinator.titles()
+ expect(titles.size).toBe(2)
+ expect(coordinator.titleFor(current, titles)).toBe('Herdr title')
+ })
+
+ it('fails over only when dispatch is proven not to have started', async () => {
+ const first = backend('tmux:default', vi.fn(async () => ({ state: 'failed' as const, dispatch: 'not_started' as const, reason: 'missing' })))
+ const second = backend('herdr:endpoint-a', vi.fn(async () => ({ state: 'succeeded' as const, dispatch: 'executed' as const })))
+ const result = await new TerminalBackendCoordinator([first, second], ['tmux', 'herdr'], ['default']).submitText(session(), 'hello')
+ expect(result).toEqual({ state: 'succeeded', dispatch: 'executed' })
+ expect(second.submitText).toHaveBeenCalledOnce()
+ })
+
+ it('never retries a possibly executed side effect', async () => {
+ const first = backend('tmux:default', vi.fn(async () => ({ state: 'unknown' as const, dispatch: 'possibly_executed' as const, reason: 'lost response' })))
+ const second = backend('herdr:endpoint-a', vi.fn(async () => ({ state: 'succeeded' as const, dispatch: 'executed' as const })))
+ const result = await new TerminalBackendCoordinator([first, second], ['tmux', 'herdr'], ['default']).submitText(session(), 'hello')
+ expect(result).toMatchObject({ state: 'unknown', dispatch: 'possibly_executed' })
+ expect(second.submitText).not.toHaveBeenCalled()
+ })
+
+ it('allows read-only capture failover and refreshes a Herdr lease after a route move', async () => {
+ const first = backend('tmux:default', vi.fn())
+ first.capture = vi.fn(async () => ({ state: 'failed' as const, reason: 'capture failed' }))
+ const second = backend('herdr:endpoint-a', vi.fn())
+ second.capture = vi.fn(async () => ({ state: 'succeeded' as const, value: 'screen' }))
+ const coordinator = new TerminalBackendCoordinator([first, second], ['tmux', 'herdr'], ['default'])
+ const current = session()
+ await expect(coordinator.capture(current)).resolves.toEqual({ state: 'succeeded', value: 'screen' })
+ const acquired = await coordinator.acquireLease(current)
+ expect(acquired.state).toBe('succeeded')
+ if (acquired.state !== 'succeeded') return
+ expect(coordinator.leaseIsCurrent(acquired.value, current)).toBe(true)
+ current.runtimes = [herdr]
+ current.primaryRuntimeKey = terminalRouteKey(herdr)
+ const herdrLease = await coordinator.acquireLease(current)
+ expect(herdrLease.state).toBe('succeeded')
+ if (herdrLease.state !== 'succeeded') return
+ current.runtimes[0] = { ...herdr, paneId: 'w2:p4' }
+ current.primaryRuntimeKey = terminalRouteKey(current.runtimes[0])
+ expect(coordinator.leaseIsCurrent(herdrLease.value, current)).toBe(true)
+ expect(herdrLease.value.runtime).toMatchObject({ paneId: 'w2:p4', terminalId: 'terminal-a' })
+ })
+
+ it('uses lease-aware pre-dispatch fallback but never retries ambiguous completion', async () => {
+ const first = backend('tmux:default', vi.fn(async () => ({ state: 'failed' as const, dispatch: 'rejected' as const, reason: 'rejected' })))
+ const secondSubmit = vi.fn(async () => ({ state: 'succeeded' as const, dispatch: 'executed' as const }))
+ const second = backend('herdr:endpoint-a', secondSubmit)
+ const coordinator = new TerminalBackendCoordinator([first, second], ['tmux', 'herdr'], ['default'])
+ const current = session()
+ const acquired = await coordinator.acquireLease(current)
+ expect(acquired.state).toBe('succeeded')
+ if (acquired.state !== 'succeeded') return
+ await expect(coordinator.submitTextForLease(current, acquired.value, 'hello')).resolves.toEqual({
+ state: 'succeeded', dispatch: 'executed',
+ })
+ expect(acquired.value.runtime).toEqual(herdr)
+
+ first.submitText = vi.fn(async () => ({ state: 'unknown' as const, dispatch: 'possibly_executed' as const, reason: 'lost response' }))
+ const another = await coordinator.acquireLease(current)
+ if (another.state !== 'succeeded') return
+ secondSubmit.mockClear()
+ await expect(coordinator.submitTextForLease(current, another.value, 'again')).resolves.toMatchObject({
+ state: 'unknown', dispatch: 'possibly_executed',
+ })
+ expect(secondSubmit).not.toHaveBeenCalled()
+ })
+
+ it('never changes placement for a side effect issued through an already pinned multi-step lease', async () => {
+ const firstSubmit = vi.fn(async () => ({ state: 'failed' as const, dispatch: 'rejected' as const, reason: 'rejected' }))
+ const secondSubmit = vi.fn(async () => ({ state: 'succeeded' as const, dispatch: 'executed' as const }))
+ const coordinator = new TerminalBackendCoordinator([
+ backend('tmux:default', firstSubmit),
+ backend('herdr:endpoint-a', secondSubmit),
+ ], ['tmux', 'herdr'], ['default'])
+ const acquired = await coordinator.acquireLease(session())
+ expect(acquired.state).toBe('succeeded')
+ if (acquired.state !== 'succeeded') return
+
+ await expect(coordinator.submitTextLease(acquired.value, 'hello')).resolves.toMatchObject({
+ state: 'failed', dispatch: 'rejected',
+ })
+ expect(firstSubmit).toHaveBeenCalledOnce()
+ expect(secondSubmit).not.toHaveBeenCalled()
+ })
+
+ it('keeps an active lease valid when refreshed endpoint discovery reuses the same backend instance', async () => {
+ const herdrBackend = backend('herdr:endpoint-a', vi.fn())
+ const coordinator = new TerminalBackendCoordinator([herdrBackend], ['herdr'], ['default'])
+ const current = session()
+ current.runtimes = [herdr]
+ current.primaryRuntimeKey = terminalRouteKey(herdr)
+ const acquired = await coordinator.acquireLease(current)
+ expect(acquired.state).toBe('succeeded')
+ if (acquired.state !== 'succeeded') return
+
+ coordinator.replaceBackends([herdrBackend])
+
+ expect(coordinator.leaseIsCurrent(acquired.value, current)).toBe(true)
+ await expect(coordinator.validateLease(acquired.value, current)).resolves.toBe(true)
+ })
+})
diff --git a/cli/src/lib/terminalBackendCoordinator.ts b/cli/src/lib/terminalBackendCoordinator.ts
new file mode 100644
index 000000000..8721c82ef
--- /dev/null
+++ b/cli/src/lib/terminalBackendCoordinator.ts
@@ -0,0 +1,280 @@
+import type { RegisteredSession } from './registry.js'
+import type { TerminalBackend } from './terminalBackend.js'
+import { processIdentityKey, terminalInstanceId, terminalPlacementKey, terminalRouteKey } from './terminalRuntime.js'
+import {
+ terminalActionNotStarted,
+ type RuntimeValidation,
+ type TerminalActionResult,
+ type TerminalCaptureOptions,
+ type TerminalLogicalKey,
+ type TerminalReadResult,
+ type TerminalRuntimeRef,
+} from './terminalTypes.js'
+
+export interface TerminalControlLease {
+ agentId: string
+ runtime: TerminalRuntimeRef
+ placementKey: string
+ generation: string
+}
+
+function primaryPlacement(session: Pick<RegisteredSession, 'runtimes' | 'primaryRuntimeKey'>): string {
+ const primary = session.runtimes.find((runtime) => terminalRouteKey(runtime) === session.primaryRuntimeKey)
+ return primary ? terminalPlacementKey(primary) : ''
+}
+
+function runtimeGeneration(session: Pick<RegisteredSession, 'engine' | 'processIdentity' | 'runtimes' | 'primaryRuntimeKey'>): string {
+ const process = session.processIdentity ? processIdentityKey(session.engine, session.processIdentity) : ''
+ return `${process}\u0000${primaryPlacement(session)}\u0000${session.runtimes.map(terminalPlacementKey).sort().join('\u0001')}`
+}
+
+const LEGACY_KEYS: Record<string, TerminalLogicalKey> = {
+ Enter: 'enter', Escape: 'escape', Tab: 'tab', BTab: 'backtab', Up: 'up', Down: 'down', Left: 'left', Right: 'right',
+ Home: 'home', End: 'end', BSpace: 'backspace', DC: 'delete', PPage: 'pageup', NPage: 'pagedown',
+ 'C-c': 'ctrl-c', 'C-d': 'ctrl-d', 'C-u': 'ctrl-u', 'C-w': 'ctrl-w', Space: 'space',
+ '0': '0', '1': '1', '2': '2', '3': '3', '4': '4', '5': '5', '6': '6', '7': '7', '8': '8', '9': '9',
+}
+
+export function terminalLogicalKey(key: string): TerminalLogicalKey | null {
+ return LEGACY_KEYS[key] ?? null
+}
+
+/** Resolves all terminal I/O through validated backend-scoped locators. */
+export class TerminalBackendCoordinator {
+ private readonly byInstance = new Map<string, TerminalBackend>()
+
+ constructor(
+ backends: readonly TerminalBackend[],
+ private readonly backendOrder: readonly string[],
+ private readonly herdrSessionOrder: readonly string[],
+ ) {
+ this.replaceBackends(backends)
+ }
+
+ replaceBackends(backends: readonly TerminalBackend[]): void {
+ this.byInstance.clear()
+ for (const backend of backends) this.byInstance.set(backend.instanceId, backend)
+ }
+
+ instances(): TerminalBackend[] {
+ return [...this.byInstance.values()]
+ }
+
+ async titles(): Promise<Map<string, string>> {
+ const snapshots = await Promise.all(this.instances().map((backend) =>
+ backend.titles().catch(() => ({ state: 'failed' as const, reason: 'terminal title snapshot failed' }))))
+ const titles = new Map<string, string>()
+ for (const snapshot of snapshots) {
+ if (snapshot.state !== 'succeeded') continue
+ for (const [route, title] of snapshot.value) titles.set(route, title)
+ }
+ return titles
+ }
+
+ titleFor(session: RegisteredSession, titles: ReadonlyMap<string, string>): string | undefined {
+ for (const runtime of this.orderedRuntimes(session)) {
+ const title = titles.get(terminalRouteKey(runtime))
+ if (title) return title
+ }
+ return undefined
+ }
+
+ backendFor(runtime: TerminalRuntimeRef): TerminalBackend | undefined {
+ return this.byInstance.get(terminalInstanceId(runtime))
+ }
+
+ private orderedRuntimes(session: RegisteredSession): TerminalRuntimeRef[] {
+ const configured = session.runtimes.filter((runtime) => this.backendFor(runtime))
+ return configured.toSorted((a, b) => {
+ const aPrimary = terminalRouteKey(a) === session.primaryRuntimeKey
+ const bPrimary = terminalRouteKey(b) === session.primaryRuntimeKey
+ if (aPrimary !== bPrimary) return aPrimary ? -1 : 1
+ const ab = this.backendOrder.indexOf(a.backend)
+ const bb = this.backendOrder.indexOf(b.backend)
+ if (ab !== bb) return (ab < 0 ? Number.MAX_SAFE_INTEGER : ab) - (bb < 0 ? Number.MAX_SAFE_INTEGER : bb)
+ if (a.backend === 'herdr' && b.backend === 'herdr') {
+ return this.herdrSessionOrder.indexOf(a.sessionName) - this.herdrSessionOrder.indexOf(b.sessionName)
+ }
+ return terminalRouteKey(a).localeCompare(terminalRouteKey(b))
+ })
+ }
+
+ async validate(session: RegisteredSession): Promise<RuntimeValidation> {
+ if (!session.active) return { state: 'gone', reason: 'terminal agent is dormant' }
+ let unknown: RuntimeValidation | null = null
+ for (const runtime of this.orderedRuntimes(session)) {
+ const backend = this.backendFor(runtime)!
+ const result = await backend.validate(runtime, {
+ engine: session.engine,
+ processIdentity: session.processIdentity ?? undefined,
+ })
+ if (result.state === 'alive') return result
+ if (result.state === 'unknown') unknown = result
+ }
+ return unknown ?? { state: 'gone', reason: 'no configured terminal runtime is alive' }
+ }
+
+ async acquireLease(session: RegisteredSession): Promise<TerminalReadResult<TerminalControlLease>> {
+ if (!session.active) return { state: 'failed', reason: 'terminal agent is dormant' }
+ for (const runtime of this.orderedRuntimes(session)) {
+ const backend = this.backendFor(runtime)!
+ const validation = await backend.validate(runtime, {
+ engine: session.engine,
+ processIdentity: session.processIdentity ?? undefined,
+ })
+ if (validation.state === 'alive') {
+ return {
+ state: 'succeeded',
+ value: {
+ agentId: session.agentId,
+ runtime,
+ placementKey: terminalPlacementKey(runtime),
+ generation: runtimeGeneration(session),
+ },
+ }
+ }
+ }
+ return { state: 'failed', reason: 'no terminal runtime could be leased' }
+ }
+
+ leaseIsCurrent(lease: TerminalControlLease, session: RegisteredSession): boolean {
+ if (lease.agentId !== session.agentId || lease.generation !== runtimeGeneration(session)) return false
+ const current = session.runtimes.find((runtime) => terminalPlacementKey(runtime) === lease.placementKey)
+ if (!current) return false
+ // Herdr's pane route is mutable. Refresh it under the stable endpoint + terminal placement rather
+ // than splitting a pinned interaction across a different placement.
+ lease.runtime = current
+ return true
+ }
+
+ async validateLease(lease: TerminalControlLease, session: RegisteredSession): Promise<boolean> {
+ if (!this.leaseIsCurrent(lease, session)) return false
+ const backend = this.backendFor(lease.runtime)
+ if (!backend) return false
+ return (await backend.validate(lease.runtime, {
+ engine: session.engine,
+ processIdentity: session.processIdentity ?? undefined,
+ })).state === 'alive'
+ }
+
+ async capture(session: RegisteredSession, options?: TerminalCaptureOptions): Promise<TerminalReadResult<string>> {
+ if (!session.active) return { state: 'failed', reason: 'terminal agent is dormant' }
+ let reason = 'no configured terminal runtime is available'
+ for (const runtime of this.orderedRuntimes(session)) {
+ const result = await this.backendFor(runtime)!.capture(runtime, options)
+ if (result.state === 'succeeded') return result
+ reason = result.reason
+ }
+ return { state: 'failed', reason }
+ }
+
+ async captureLease(lease: TerminalControlLease, options?: TerminalCaptureOptions): Promise<TerminalReadResult<string>> {
+ const backend = this.backendFor(lease.runtime)
+ return backend ? backend.capture(lease.runtime, options) : { state: 'failed', reason: 'leased terminal backend is disabled' }
+ }
+
+ typeLiteralLease(lease: TerminalControlLease, text: string): Promise<TerminalActionResult> {
+ const backend = this.backendFor(lease.runtime)
+ return backend
+ ? backend.typeLiteral(lease.runtime, text)
+ : Promise.resolve(terminalActionNotStarted('leased terminal backend is disabled'))
+ }
+
+ submitTextLease(lease: TerminalControlLease, text: string): Promise<TerminalActionResult> {
+ const backend = this.backendFor(lease.runtime)
+ return backend
+ ? backend.submitText(lease.runtime, text)
+ : Promise.resolve(terminalActionNotStarted('leased terminal backend is disabled'))
+ }
+
+ /** Single-operation lease dispatch with exact-once-safe fallback to another validated locator. */
+ async submitTextForLease(
+ session: RegisteredSession,
+ lease: TerminalControlLease,
+ text: string,
+ ): Promise<TerminalActionResult> {
+ if (!this.leaseIsCurrent(lease, session)) return terminalActionNotStarted('terminal control lease changed')
+ const ordered = this.orderedRuntimes(session)
+ const candidates = [
+ lease.runtime,
+ ...ordered.filter((runtime) => terminalPlacementKey(runtime) !== lease.placementKey),
+ ]
+ let last: TerminalActionResult = terminalActionNotStarted('no configured terminal runtime is available')
+ for (const runtime of candidates) {
+ const backend = this.backendFor(runtime)
+ if (!backend) continue
+ const validation = await backend.validate(runtime, {
+ engine: session.engine,
+ processIdentity: session.processIdentity ?? undefined,
+ })
+ if (validation.state !== 'alive') continue
+ const result = await backend.submitText(runtime, text)
+ if (result.state === 'succeeded') {
+ lease.runtime = runtime
+ lease.placementKey = terminalPlacementKey(runtime)
+ return result
+ }
+ if (result.dispatch === 'possibly_executed') return result
+ last = result
+ if (result.dispatch !== 'not_started' && result.dispatch !== 'rejected') return result
+ }
+ return last
+ }
+
+ sendLegacyKeyLease(lease: TerminalControlLease, key: string): Promise<TerminalActionResult> {
+ const backend = this.backendFor(lease.runtime)
+ const logical = terminalLogicalKey(key)
+ return backend && logical
+ ? backend.sendKey(lease.runtime, logical)
+ : Promise.resolve(terminalActionNotStarted(backend
+ ? 'unsupported logical terminal key'
+ : 'leased terminal backend is disabled'))
+ }
+
+ private async sideEffect(
+ session: RegisteredSession,
+ action: (backend: TerminalBackend, runtime: TerminalRuntimeRef) => Promise<TerminalActionResult>,
+ ): Promise<TerminalActionResult> {
+ if (!session.active) return terminalActionNotStarted('terminal agent is dormant')
+ let last: TerminalActionResult = terminalActionNotStarted('no configured terminal runtime is available')
+ for (const runtime of this.orderedRuntimes(session)) {
+ const backend = this.backendFor(runtime)!
+ const validation = await backend.validate(runtime, {
+ engine: session.engine,
+ processIdentity: session.processIdentity ?? undefined,
+ })
+ if (validation.state !== 'alive') continue
+ const result = await action(backend, runtime)
+ if (result.state === 'succeeded' || result.dispatch === 'possibly_executed') return result
+ last = result
+ // Only proven pre-dispatch or explicit server rejection may use another validated locator.
+ if (result.dispatch !== 'not_started' && result.dispatch !== 'rejected') return result
+ }
+ return last
+ }
+
+ submitText(session: RegisteredSession, text: string): Promise<TerminalActionResult> {
+ return this.sideEffect(session, (backend, runtime) => backend.submitText(runtime, text))
+ }
+
+ typeLiteral(session: RegisteredSession, text: string): Promise<TerminalActionResult> {
+ return this.sideEffect(session, (backend, runtime) => backend.typeLiteral(runtime, text))
+ }
+
+ sendKey(session: RegisteredSession, key: TerminalLogicalKey): Promise<TerminalActionResult> {
+ return this.sideEffect(session, (backend, runtime) => backend.sendKey(runtime, key))
+ }
+
+ sendLegacyKey(session: RegisteredSession, key: string): Promise<TerminalActionResult> {
+ const logical = terminalLogicalKey(key)
+ return logical ? this.sendKey(session, logical) : Promise.resolve(terminalActionNotStarted('unsupported logical terminal key'))
+ }
+
+ setTitle(session: RegisteredSession, title: string): Promise<TerminalActionResult> {
+ return this.sideEffect(session, (backend, runtime) => backend.setTitle(runtime, title))
+ }
+
+ notify(session: RegisteredSession, title: string, body: string): Promise<TerminalActionResult> {
+ return this.sideEffect(session, (backend, runtime) => backend.notify(runtime, title, body))
+ }
+}
diff --git a/cli/src/lib/terminalConfigSnapshot.spec.ts b/cli/src/lib/terminalConfigSnapshot.spec.ts
new file mode 100644
index 000000000..1507abc7e
--- /dev/null
+++ b/cli/src/lib/terminalConfigSnapshot.spec.ts
@@ -0,0 +1,61 @@
+import { chmodSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { readTerminalConfigSnapshot, terminalConfigSnapshotPath, writeTerminalConfigSnapshot } from './terminalConfigSnapshot.js'
+
+const cleanup: string[] = []
+
+afterEach(() => {
+ for (const path of cleanup.splice(0)) rmSync(path, { recursive: true, force: true })
+})
+
+describe('terminal config snapshot', () => {
+ it('atomically persists only configured endpoints in configured order', () => {
+ const dataDir = mkdtempSync(join(tmpdir(), 'terminal-config-'))
+ cleanup.push(dataDir)
+ writeTerminalConfigSnapshot(dataDir, { backends: ['herdr'], herdrSessions: ['work', 'default'] }, [
+ { sessionName: 'default', endpointId: 'default-id', socketPath: '/safe/default.sock', generation: { device: 1, inode: 2 } },
+ { sessionName: 'ignored', endpointId: 'ignored-id', socketPath: '/safe/ignored.sock', generation: { device: 3, inode: 4 } },
+ { sessionName: 'work', endpointId: 'work-id', socketPath: '/safe/work.sock', generation: { device: 5, inode: 6 } },
+ ])
+
+ const file = terminalConfigSnapshotPath(dataDir)
+ expect(statSync(file).mode & 0o777).toBe(0o600)
+ expect(readTerminalConfigSnapshot(dataDir)?.herdrEndpoints.map((endpoint) => endpoint.sessionName)).toEqual(['work', 'default'])
+ expect(readFileSync(file, 'utf8')).not.toContain('ignored-id')
+ })
+
+ it('tightens an owner-owned legacy snapshot before reading it', () => {
+ const dataDir = mkdtempSync(join(tmpdir(), 'terminal-config-'))
+ cleanup.push(dataDir)
+ writeTerminalConfigSnapshot(dataDir, { backends: ['tmux'], herdrSessions: [] }, [])
+ chmodSync(terminalConfigSnapshotPath(dataDir), 0o644)
+ expect(readTerminalConfigSnapshot(dataDir)?.backends).toEqual(['tmux'])
+ expect(statSync(terminalConfigSnapshotPath(dataDir)).mode & 0o777).toBe(0o600)
+ })
+
+ it('rejects a group-writable snapshot instead of tightening and trusting it', () => {
+ const dataDir = mkdtempSync(join(tmpdir(), 'terminal-config-'))
+ cleanup.push(dataDir)
+ writeTerminalConfigSnapshot(dataDir, { backends: ['tmux'], herdrSessions: [] }, [])
+ chmodSync(terminalConfigSnapshotPath(dataDir), 0o660)
+ expect(readTerminalConfigSnapshot(dataDir)).toBeNull()
+ expect(statSync(terminalConfigSnapshotPath(dataDir)).mode & 0o777).toBe(0o660)
+ })
+
+ it('neither reads nor replaces a symlinked snapshot', () => {
+ const root = mkdtempSync(join(tmpdir(), 'terminal-config-'))
+ cleanup.push(root)
+ const dataDir = join(root, 'data')
+ const target = join(root, 'target.json')
+ writeFileSync(target, '{}', { mode: 0o600 })
+ writeTerminalConfigSnapshot(dataDir, { backends: ['tmux'], herdrSessions: [] }, [])
+ rmSync(terminalConfigSnapshotPath(dataDir))
+ symlinkSync(target, terminalConfigSnapshotPath(dataDir))
+
+ expect(readTerminalConfigSnapshot(dataDir)).toBeNull()
+ expect(() => writeTerminalConfigSnapshot(dataDir, { backends: ['tmux'], herdrSessions: [] }, [])).toThrow()
+ expect(readFileSync(target, 'utf8')).toBe('{}')
+ })
+})
diff --git a/cli/src/lib/terminalConfigSnapshot.ts b/cli/src/lib/terminalConfigSnapshot.ts
new file mode 100644
index 000000000..cbf18a7b6
--- /dev/null
+++ b/cli/src/lib/terminalConfigSnapshot.ts
@@ -0,0 +1,102 @@
+import { randomUUID } from 'node:crypto'
+import { closeSync, constants, fchmodSync, fsyncSync, openSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { isAbsolute, join } from 'node:path'
+import type { TerminalConfig } from '../config/terminalConfig.js'
+import type { HerdrEndpoint } from './herdrApiClient.js'
+import { hardenPrivateStateFileIfPresent, readPrivateStateFile, secureStateDirectory } from './secureState.js'
+import type { TerminalBackendName } from './terminalTypes.js'
+
+const SNAPSHOT_FILE = 'terminal-config.json'
+const MAX_SNAPSHOT_BYTES = 64 * 1024
+
+export interface TerminalConfigEndpointSnapshot {
+ sessionName: string
+ endpointId: string
+ socketPath: string
+ generation: { device: number; inode: number }
+}
+
+export interface TerminalConfigSnapshot {
+ version: 1
+ updatedAt: number
+ backends: TerminalBackendName[]
+ herdrEndpoints: TerminalConfigEndpointSnapshot[]
+}
+
+export function terminalConfigSnapshotPath(dataDir: string): string {
+ return join(dataDir, SNAPSHOT_FILE)
+}
+
+export function writeTerminalConfigSnapshot(
+ dataDir: string,
+ config: TerminalConfig,
+ endpoints: readonly HerdrEndpoint[],
+): TerminalConfigSnapshot {
+ const allowed = new Set(config.herdrSessions)
+ const herdrEndpoints = endpoints
+ .filter((endpoint) => allowed.has(endpoint.sessionName))
+ .sort((a, b) => config.herdrSessions.indexOf(a.sessionName) - config.herdrSessions.indexOf(b.sessionName))
+ .map(({ sessionName, endpointId, socketPath, generation }) => ({
+ sessionName,
+ endpointId,
+ socketPath,
+ generation: { ...generation },
+ }))
+ const snapshot: TerminalConfigSnapshot = {
+ version: 1,
+ updatedAt: Date.now(),
+ backends: [...config.backends],
+ herdrEndpoints,
+ }
+ secureStateDirectory(dataDir)
+ const file = terminalConfigSnapshotPath(dataDir)
+ hardenPrivateStateFileIfPresent(file, MAX_SNAPSHOT_BYTES)
+ const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`
+ let renamed = false
+ try {
+ const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)
+ try {
+ writeFileSync(fd, `${JSON.stringify(snapshot, null, 2)}\n`)
+ fchmodSync(fd, 0o600)
+ fsyncSync(fd)
+ } finally {
+ closeSync(fd)
+ }
+ renameSync(temporary, file)
+ renamed = true
+ const directoryFd = openSync(dataDir, 'r')
+ try { fsyncSync(directoryFd) } finally { closeSync(directoryFd) }
+ } finally {
+ if (!renamed) rmSync(temporary, { force: true })
+ }
+ return snapshot
+}
+
+function validString(value: unknown, max = 200): value is string {
+ return typeof value === 'string' && value.length > 0 && value.length <= max && !/[\u0000-\u001f\u007f]/.test(value)
+}
+
+export function readTerminalConfigSnapshot(dataDir: string): TerminalConfigSnapshot | null {
+ const file = terminalConfigSnapshotPath(dataDir)
+ try {
+ secureStateDirectory(dataDir, false)
+ const parsed = JSON.parse(readPrivateStateFile(file, MAX_SNAPSHOT_BYTES)) as Partial<TerminalConfigSnapshot>
+ if (parsed.version !== 1 || !Number.isFinite(parsed.updatedAt)) return null
+ if (!Array.isArray(parsed.backends)
+ || parsed.backends.some((backend) => backend !== 'tmux' && backend !== 'herdr')
+ || new Set(parsed.backends).size !== parsed.backends.length) return null
+ if (!Array.isArray(parsed.herdrEndpoints)) return null
+ for (const endpoint of parsed.herdrEndpoints) {
+ if (!endpoint || typeof endpoint !== 'object') return null
+ if (!validString(endpoint.sessionName, 64)
+ || !validString(endpoint.endpointId)
+ || !validString(endpoint.socketPath, 4_096)
+ || !isAbsolute(endpoint.socketPath)
+ || !Number.isSafeInteger(endpoint.generation?.device)
+ || !Number.isSafeInteger(endpoint.generation?.inode)) return null
+ }
+ return parsed as TerminalConfigSnapshot
+ } catch {
+ return null
+ }
+}
diff --git a/cli/src/lib/terminalEnvironment.spec.ts b/cli/src/lib/terminalEnvironment.spec.ts
new file mode 100644
index 000000000..3a32e5ef0
--- /dev/null
+++ b/cli/src/lib/terminalEnvironment.spec.ts
@@ -0,0 +1,12 @@
+import { describe, expect, it } from 'vitest'
+import { scrubTerminalContext, TERMINAL_CONTEXT_VARIABLES } from './terminalEnvironment.js'
+
+describe('scrubTerminalContext', () => {
+ it('removes the complete tmux and Herdr routing context without touching unrelated values', () => {
+ const environment = Object.fromEntries([
+ ...TERMINAL_CONTEXT_VARIABLES.map((key) => [key, `value-${key}`]),
+ ['PATH', '/bin'],
+ ])
+ expect(scrubTerminalContext(environment)).toEqual({ PATH: '/bin' })
+ })
+})
diff --git a/cli/src/lib/terminalEnvironment.ts b/cli/src/lib/terminalEnvironment.ts
new file mode 100644
index 000000000..ff04a12d5
--- /dev/null
+++ b/cli/src/lib/terminalEnvironment.ts
@@ -0,0 +1,16 @@
+export const TERMINAL_CONTEXT_VARIABLES = [
+ 'TMUX',
+ 'TMUX_PANE',
+ 'HERDR_ENV',
+ 'HERDR_SESSION',
+ 'HERDR_SOCKET_PATH',
+ 'HERDR_WORKSPACE_ID',
+ 'HERDR_TAB_ID',
+ 'HERDR_PANE_ID',
+] as const
+
+/** Mutate a child-only environment copy so one-shots cannot register as top-level terminal agents. */
+export function scrubTerminalContext<T extends NodeJS.ProcessEnv>(environment: T): T {
+ for (const key of TERMINAL_CONTEXT_VARIABLES) delete environment[key]
+ return environment
+}
diff --git a/cli/src/lib/terminalRuntime.spec.ts b/cli/src/lib/terminalRuntime.spec.ts
new file mode 100644
index 000000000..a637f9cdf
--- /dev/null
+++ b/cli/src/lib/terminalRuntime.spec.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from 'vitest'
+import {
+ mergeTerminalRuntimes,
+ processIdentityKey,
+ sameProcessIdentity,
+ terminalPlacementKey,
+ terminalRouteKey,
+} from './terminalRuntime.js'
+import type { HerdrRuntimeRef, TmuxRuntimeRef } from './terminalTypes.js'
+
+const tmux: TmuxRuntimeRef = { backend: 'tmux', paneId: '%3' }
+const herdr: HerdrRuntimeRef = {
+ backend: 'herdr',
+ endpointId: 'herdr:default:abc',
+ sessionName: 'default',
+ terminalId: 'terminal-1',
+ paneId: 'w1:p1',
+}
+
+describe('terminal runtime identity', () => {
+ it('scopes duplicate Herdr pane routes to their configured endpoint', () => {
+ const other = { ...herdr, endpointId: 'herdr:work:def', sessionName: 'work' }
+ expect(terminalRouteKey(herdr)).not.toBe(terminalRouteKey(other))
+ expect(terminalPlacementKey(herdr)).not.toBe(terminalPlacementKey(other))
+ })
+
+ it('keeps Herdr placement stable while replacing a moved route', () => {
+ const moved = { ...herdr, paneId: 'w2:p4' }
+ expect(terminalPlacementKey(moved)).toBe(terminalPlacementKey(herdr))
+ expect(terminalRouteKey(moved)).not.toBe(terminalRouteKey(herdr))
+ expect(mergeTerminalRuntimes([tmux, herdr], [moved])).toEqual([moved, tmux])
+ })
+
+ it('keys process identity without treating argv-derived executable as authoritative', () => {
+ const before = { pid: 42, executable: 'node', startMarker: 'Sat Aug 15 10:00:00 2026' }
+ const renamed = { ...before, executable: 'agent title' }
+ expect(sameProcessIdentity(before, renamed)).toBe(true)
+ expect(processIdentityKey('claude', before)).toBe(processIdentityKey('claude', renamed))
+ })
+
+ it('rejects separator injection into stable keys', () => {
+ expect(() => terminalRouteKey({ backend: 'tmux', paneId: '%1\u0000other' })).toThrow('invalid tmux pane id')
+ })
+})
diff --git a/cli/src/lib/terminalRuntime.ts b/cli/src/lib/terminalRuntime.ts
new file mode 100644
index 000000000..c0d1a4421
--- /dev/null
+++ b/cli/src/lib/terminalRuntime.ts
@@ -0,0 +1,56 @@
+import type { ProcessIdentity, TerminalRuntimeRef } from './terminalTypes.js'
+
+const SEP = '\u0000'
+
+function assertKeyPart(value: string, field: string): string {
+ if (!value || value.includes(SEP)) throw new Error(`invalid ${field}`)
+ return value
+}
+
+/** Stable route key. It changes when a Herdr terminal moves to a different public pane route. */
+export function terminalRouteKey(runtime: TerminalRuntimeRef): string {
+ return runtime.backend === 'tmux'
+ ? `tmux${SEP}${assertKeyPart(runtime.paneId, 'tmux pane id')}`
+ : `herdr${SEP}${assertKeyPart(runtime.endpointId, 'Herdr endpoint id')}${SEP}${assertKeyPart(runtime.paneId, 'Herdr pane id')}`
+}
+
+export function terminalInstanceId(runtime: TerminalRuntimeRef): string {
+ return runtime.backend === 'tmux' ? 'tmux:default' : `herdr:${assertKeyPart(runtime.endpointId, 'Herdr endpoint id')}`
+}
+
+/** Human-readable locator label for status and logs. It never contains a Herdr socket path. */
+export function terminalRuntimeLabel(runtime: TerminalRuntimeRef): string {
+ return runtime.backend === 'tmux'
+ ? `tmux:${runtime.paneId}`
+ : `herdr:${runtime.sessionName}:${runtime.paneId}`
+}
+
+/** Stable placement key. A Herdr pane move keeps this key because terminal_id is the placement identity. */
+export function terminalPlacementKey(runtime: TerminalRuntimeRef): string {
+ return runtime.backend === 'tmux'
+ ? terminalRouteKey(runtime)
+ : `herdr${SEP}${assertKeyPart(runtime.endpointId, 'Herdr endpoint id')}${SEP}${assertKeyPart(runtime.terminalId, 'Herdr terminal id')}`
+}
+
+export function processIdentityKey(engine: string, identity: ProcessIdentity): string {
+ return `${assertKeyPart(engine, 'engine')}${SEP}${identity.pid}${SEP}${assertKeyPart(identity.startMarker, 'process start marker')}`
+}
+
+export function sameProcessIdentity(a: ProcessIdentity | undefined, b: ProcessIdentity | undefined): boolean {
+ return !!a && !!b && a.pid === b.pid && a.startMarker === b.startMarker
+}
+
+export function sameTerminalPlacement(a: TerminalRuntimeRef, b: TerminalRuntimeRef): boolean {
+ return terminalPlacementKey(a) === terminalPlacementKey(b)
+}
+
+/** Replace a moved Herdr route without duplicating its stable placement. */
+export function mergeTerminalRuntimes(
+ current: readonly TerminalRuntimeRef[],
+ observed: readonly TerminalRuntimeRef[],
+): TerminalRuntimeRef[] {
+ const merged = new Map<string, TerminalRuntimeRef>()
+ for (const runtime of current) merged.set(terminalPlacementKey(runtime), runtime)
+ for (const runtime of observed) merged.set(terminalPlacementKey(runtime), runtime)
+ return [...merged.values()].sort((a, b) => terminalPlacementKey(a).localeCompare(terminalPlacementKey(b)))
+}
diff --git a/cli/src/lib/terminalTypes.ts b/cli/src/lib/terminalTypes.ts
new file mode 100644
index 000000000..dc7fc9d63
--- /dev/null
+++ b/cli/src/lib/terminalTypes.ts
@@ -0,0 +1,141 @@
+import type { AgentEngine } from '../engines/types.js'
+
+export type TerminalBackendName = 'tmux' | 'herdr'
+
+/** PID reuse-safe identity for the process that owns a Harness agent. */
+export interface ProcessIdentity {
+ pid: number
+ executable: string
+ startMarker: string
+}
+
+export interface TmuxRuntimeRef {
+ backend: 'tmux'
+ paneId: string
+}
+
+export interface HerdrRuntimeRef {
+ backend: 'herdr'
+ /** Stable configured-target identifier. Never contains the socket path. */
+ endpointId: string
+ sessionName: string
+ /** Stable within one Herdr endpoint, including across pane moves. */
+ terminalId: string
+ /** Mutable public route, scoped to endpointId. */
+ paneId: string
+}
+
+export type TerminalRuntimeRef = TmuxRuntimeRef | HerdrRuntimeRef
+
+/** Untrusted route hints from hooks. Herdr socket paths are lookup hints, never connection authority. */
+export type HookTerminalHint =
+ | { backend: 'tmux'; paneId: string }
+ | { backend: 'herdr'; paneId: string; sessionName?: string; socketPath?: string }
+
+export interface TerminalRootObservation {
+ runtime: TerminalRuntimeRef
+ rootPid: number
+ cwd: string
+ /** Route aliases reported by the backend; never treated as process identity. */
+ aliases?: readonly string[]
+}
+
+export type TerminalInventoryResult =
+ | { state: 'available'; roots: readonly TerminalRootObservation[] }
+ | { state: 'unavailable'; reason: string }
+ | { state: 'incompatible'; reason: string }
+
+export type RuntimeValidation =
+ | { state: 'alive' }
+ | { state: 'gone'; reason: string }
+ | { state: 'unknown'; reason: string }
+
+/**
+ * Result of a PTY side effect. Only `not_started` and a server-confirmed `rejected` result may be
+ * retried on another runtime. `possibly_executed` must be observed before any further side effect.
+ */
+export type TerminalActionResult =
+ | { state: 'succeeded'; dispatch: 'executed' }
+ | { state: 'failed'; dispatch: 'not_started' | 'rejected'; reason: string }
+ | { state: 'unknown'; dispatch: 'possibly_executed'; reason: string }
+
+export interface TerminalCreateRequest {
+ cwd?: string
+ label?: string
+}
+
+export type TerminalCreateResult<Ref extends TerminalRuntimeRef = TerminalRuntimeRef> =
+ | { state: 'succeeded'; dispatch: 'executed'; runtime: Ref }
+ | { state: 'failed'; dispatch: 'not_started' | 'rejected'; reason: string }
+ | { state: 'unknown'; dispatch: 'possibly_executed'; reason: string }
+
+export type TerminalReadResult<T> =
+ | { state: 'succeeded'; value: T }
+ | { state: 'failed'; reason: string }
+
+export type TerminalLogicalKey =
+ | 'enter'
+ | 'escape'
+ | 'tab'
+ | 'backtab'
+ | 'up'
+ | 'down'
+ | 'left'
+ | 'right'
+ | 'home'
+ | 'end'
+ | 'backspace'
+ | 'delete'
+ | 'pageup'
+ | 'pagedown'
+ | 'ctrl-c'
+ | 'ctrl-d'
+ | 'ctrl-u'
+ | 'ctrl-w'
+ | 'space'
+ | '0'
+ | '1'
+ | '2'
+ | '3'
+ | '4'
+ | '5'
+ | '6'
+ | '7'
+ | '8'
+ | '9'
+
+export type TerminalCaptureMode = 'recent_unwrapped' | 'visible' | 'detection'
+
+export interface TerminalCaptureOptions {
+ mode?: TerminalCaptureMode
+ historyLines?: number
+ ansi?: boolean
+}
+
+export interface TerminalProcessExpectation {
+ engine: AgentEngine
+ processIdentity?: ProcessIdentity
+}
+
+export const TERMINAL_ACTION_SUCCEEDED: TerminalActionResult = {
+ state: 'succeeded',
+ dispatch: 'executed',
+}
+
+export function terminalActionNotStarted(reason: string): {
+ state: 'failed'; dispatch: 'not_started'; reason: string
+} {
+ return { state: 'failed', dispatch: 'not_started', reason }
+}
+
+export function terminalActionRejected(reason: string): {
+ state: 'failed'; dispatch: 'rejected'; reason: string
+} {
+ return { state: 'failed', dispatch: 'rejected', reason }
+}
+
+export function terminalActionPossiblyExecuted(reason: string): {
+ state: 'unknown'; dispatch: 'possibly_executed'; reason: string
+} {
+ return { state: 'unknown', dispatch: 'possibly_executed', reason }
+}
diff --git a/cli/src/lib/tmux.spec.ts b/cli/src/lib/tmux.spec.ts
index be7767ec0..169e02134 100644
--- a/cli/src/lib/tmux.spec.ts
+++ b/cli/src/lib/tmux.spec.ts
@@ -1,6 +1,17 @@
-import { describe, expect, it } from 'vitest'
+import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { describe, expect, it, vi } from 'vitest'
import type { AgentCommandOwnershipSnapshot } from './engineBin.js'
-import { ambiguousAgentProcess, engineProcessMatchScore, parseProcessRow, resumeSessionId } from './tmux.js'
+import {
+ ambiguousAgentProcess,
+ engineProcessMatchScore,
+ parseProcessRow,
+ resumeSessionId,
+ sendLiteralToTmux,
+ sendToTmux,
+ tmuxCaptureArgs,
+} from './tmux.js'
const ownership = (cursor: string[] = [], grok: string[] = []): AgentCommandOwnershipSnapshot => ({
cursorFileKeys: new Set(cursor),
@@ -79,4 +90,68 @@ describe('tmux process primitives', () => {
expect(resumeSessionId('codex', 'codex resume 53d3843c-724e-47ff-ae3a-9fedfa328bba')).toBeNull()
expect(resumeSessionId('devin', 'devin --resume 53d3843c-724e-47ff-ae3a-9fedfa328bba')).toBeNull()
})
+
+ it('maps neutral visible/history and ANSI capture options to tmux flags', () => {
+ expect(tmuxCaptureArgs('%7', 60)).toEqual([
+ 'capture-pane', '-p', '-e', '-J', '-t', '%7', '-S', '-60',
+ ])
+ expect(tmuxCaptureArgs('%7', 60, { visible: true, ansi: false })).toEqual([
+ 'capture-pane', '-p', '-J', '-t', '%7',
+ ])
+ })
+
+ it('carries prompt and literal bytes only over stdin, never child argv or diagnostics', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'harness-tmux-input-'))
+ const argsFile = join(dir, 'args')
+ const stdinFile = join(dir, 'stdin')
+ const fakeTmux = join(dir, 'tmux')
+ const sentinel = `prompt sentinel $' ${process.pid}`
+ writeFileSync(fakeTmux, `#!/bin/sh
+printf '%s\\n' "$*" >> "$TMUX_INPUT_ARGS"
+if [ "$1" = "load-buffer" ]; then
+ cat >> "$TMUX_INPUT_STDIN"
+ printf '\\n' >> "$TMUX_INPUT_STDIN"
+fi
+if [ "$1" = "paste-buffer" ] && [ "$TMUX_INPUT_FAIL_PASTE" = "1" ]; then
+ printf 'synthetic paste failure\\n' >&2
+ exit 2
+fi
+`)
+ chmodSync(fakeTmux, 0o700)
+ const previous = {
+ path: process.env.PATH,
+ args: process.env.TMUX_INPUT_ARGS,
+ stdin: process.env.TMUX_INPUT_STDIN,
+ fail: process.env.TMUX_INPUT_FAIL_PASTE,
+ }
+ const errors: string[] = []
+ const error = vi.spyOn(console, 'error').mockImplementation((...values) => {
+ errors.push(values.map(String).join(' '))
+ })
+ try {
+ process.env.PATH = `${dir}:${previous.path ?? ''}`
+ process.env.TMUX_INPUT_ARGS = argsFile
+ process.env.TMUX_INPUT_STDIN = stdinFile
+ expect(await sendLiteralToTmux('%7', sentinel)).toBe(true)
+ expect(await sendToTmux('%7', sentinel)).toBe(true)
+ process.env.TMUX_INPUT_FAIL_PASTE = '1'
+ expect(await sendLiteralToTmux('%7', sentinel)).toBe(false)
+
+ const argv = readFileSync(argsFile, 'utf8')
+ expect(argv).not.toContain(sentinel)
+ expect(readFileSync(stdinFile, 'utf8').split(sentinel)).toHaveLength(4)
+ expect(errors.join('\n')).not.toContain(sentinel)
+ } finally {
+ error.mockRestore()
+ if (previous.path === undefined) delete process.env.PATH
+ else process.env.PATH = previous.path
+ if (previous.args === undefined) delete process.env.TMUX_INPUT_ARGS
+ else process.env.TMUX_INPUT_ARGS = previous.args
+ if (previous.stdin === undefined) delete process.env.TMUX_INPUT_STDIN
+ else process.env.TMUX_INPUT_STDIN = previous.stdin
+ if (previous.fail === undefined) delete process.env.TMUX_INPUT_FAIL_PASTE
+ else process.env.TMUX_INPUT_FAIL_PASTE = previous.fail
+ rmSync(dir, { recursive: true, force: true })
+ }
+ })
})
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index dff2f52a9..53613c6a2 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -131,7 +131,7 @@ export function parseProcessRow(line: string): ProcessRow | null {
}
/** The process table, or null when `ps` itself failed — "we could not look" is not "nothing is there". */
-async function processRows(): Promise<ProcessRow[] | null> {
+export async function processRows(): Promise<ProcessRow[] | null> {
const rows = await new Promise<ProcessRow[] | null>((resolve) => {
execFile('ps', ['-axo', 'pid=,ppid=,comm=,lstart=,args='], { timeout: 3000 }, (err, stdout) => {
if (err) { resolve(null); return }
@@ -489,8 +489,8 @@ export async function checkSessionRuntime(session: RegisteredSession): Promise<R
return { state: 'alive' }
}
-// A short single-line message fits in ONE pty write, so `send-keys -l` + an immediate Enter submits
-// instantly. Anything longer or multi-line takes the bracketed-paste path below (see sendToTmux).
+// A short single-line message can be pasted without bracketed-paste settling. Anything longer or
+// multi-line uses bracketed paste and waits before Enter (see sendToTmux).
const INJECT_FASTPATH_MAXLEN = 500
// Base settle time before the submit Enter; grows with length (Claude needs time to ingest a big paste
// and collapse it to `[Pasted text]` before a clean Enter counts as submit rather than paste content).
@@ -522,42 +522,49 @@ function tmuxLoadBuffer(name: string, content: string): Promise<boolean> {
})
}
+function tmuxDeleteBuffer(name: string): Promise<void> {
+ return new Promise((resolve) => {
+ execFile('tmux', ['delete-buffer', '-b', name], { timeout: 2_000 }, () => resolve())
+ })
+}
+
+/** Paste text from a uniquely named stdin-loaded buffer so its bytes never enter argv or errors. */
+async function tmuxPasteText(pane: string, content: string, bracketed: boolean): Promise<boolean> {
+ const bufferName = `machinemsg-${process.pid}-${++injectBufferSequence}`
+ if (!(await tmuxLoadBuffer(bufferName, content))) {
+ await tmuxDeleteBuffer(bufferName)
+ console.error(`[tmux] load-buffer for ${pane} failed`)
+ return false
+ }
+ const args = ['paste-buffer', '-t', pane, '-b', bufferName]
+ if (bracketed) args.push('-p')
+ args.push('-d')
+ const pasted = await new Promise<boolean>((resolve) => {
+ execFile('tmux', args, { timeout: 2_000 }, (err) => {
+ if (err) console.error(`[tmux] paste-buffer to ${pane} failed:`, err.message)
+ resolve(!err)
+ })
+ })
+ if (!pasted) await tmuxDeleteBuffer(bufferName)
+ return pasted
+}
+
/**
* Type a message into a tmux pane and submit it — the web-chat/device → terminal injection point.
*
- * SHORT single-line: `send-keys -l` (literal, so "Enter"/"C-m" in the body aren't read as key names) +
- * an immediate Enter. Fast, no added latency.
+ * All text is loaded into a uniquely named tmux buffer over stdin so prompt bytes never enter argv,
+ * environment, logs, or child-process error strings. Short single-line input is pasted literally and
+ * submitted immediately.
*
- * LONG / multi-line: a big `send-keys -l` is split by tmux into several pty writes, so Claude Code's
- * paste heuristic collapses each chunk into its own `[Pasted text]` block and the immediate Enter lands
- * mid-burst and is SWALLOWED (never submits). Instead we stage the text in a named buffer and
- * bracketed-paste it as ONE unit (`paste-buffer -p`), let Claude settle, then send a clean separate
- * Enter. (Verified: reliably submits up to ~28 KB.)
+ * Long/multiline input is bracketed-pasted as one unit (`paste-buffer -p`), allowed to settle, then
+ * submitted with a separate Enter. (Verified: reliably submits up to ~28 KB.)
*/
export function sendToTmux(pane: string, text: string): Promise<boolean> {
const content = text.replace(/[\r\n]+$/, '') // strip trailing newlines so the submit Enter isn't doubled
- if (content.length <= INJECT_FASTPATH_MAXLEN && !content.includes('\n')) {
- return new Promise((resolve) => {
- execFile('tmux', ['send-keys', '-t', pane, '-l', content], { timeout: 2000 }, (err) => {
- if (err) { console.error(`[tmux] send-keys to ${pane} failed:`, err.message); resolve(false); return }
- void tmuxEnter(pane).then(resolve)
- })
- })
- }
return (async () => {
- const bufferName = `machinemsg-${process.pid}-${++injectBufferSequence}`
- if (!(await tmuxLoadBuffer(bufferName, content))) {
- console.error(`[tmux] load-buffer for ${pane} failed`)
- return false
- }
- const pasted = await new Promise<boolean>((resolve) => {
- execFile('tmux', ['paste-buffer', '-t', pane, '-b', bufferName, '-p', '-d'], { timeout: 2000 }, (err) => {
- if (err) console.error(`[tmux] paste-buffer to ${pane} failed:`, err.message)
- resolve(!err)
- })
- })
- if (!pasted) return false
- await sleep(Math.min(1500, INJECT_PASTE_DELAY_BASE_MS + Math.floor(content.length / 60)))
+ const bracketed = content.length > INJECT_FASTPATH_MAXLEN || content.includes('\n')
+ if (!(await tmuxPasteText(pane, content, bracketed))) return false
+ if (bracketed) await sleep(Math.min(1500, INJECT_PASTE_DELAY_BASE_MS + Math.floor(content.length / 60)))
return tmuxEnter(pane)
})()
}
@@ -569,12 +576,7 @@ export function sendToTmux(pane: string, text: string): Promise<boolean> {
* land on the row that just opened and pick whatever was already highlighted.
*/
export function sendLiteralToTmux(pane: string, text: string): Promise<boolean> {
- return new Promise((resolve) => {
- execFile('tmux', ['send-keys', '-t', pane, '-l', text], { timeout: 2000 }, (err) => {
- if (err) console.error(`[tmux] literal send to ${pane} failed:`, err.message)
- resolve(!err)
- })
- })
+ return tmuxPasteText(pane, text, false)
}
export function sendKeyToTmux(pane: string, key: string): Promise<boolean> {
@@ -583,11 +585,27 @@ export function sendKeyToTmux(pane: string, key: string): Promise<boolean> {
})
}
-/** Capture terminal text plus SGR style codes. Styles distinguish a dim CLI placeholder from a real draft. */
-export function captureTmuxPane(pane: string, historyLines = 100): Promise<string | null> {
+export function tmuxCaptureArgs(
+ pane: string,
+ historyLines = 100,
+ options: { visible?: boolean; ansi?: boolean } = {},
+): string[] {
const bounded = Math.max(20, Math.min(300, Math.floor(historyLines)))
+ const args = ['capture-pane', '-p']
+ if (options.ansi !== false) args.push('-e')
+ args.push('-J', '-t', pane)
+ if (!options.visible) args.push('-S', `-${bounded}`)
+ return args
+}
+
+/** Capture terminal text; SGR and bounded history are independently selectable by backend consumers. */
+export function captureTmuxPane(
+ pane: string,
+ historyLines = 100,
+ options: { visible?: boolean; ansi?: boolean } = {},
+): Promise<string | null> {
return new Promise((resolve) => {
- execFile('tmux', ['capture-pane', '-p', '-e', '-J', '-t', pane, '-S', `-${bounded}`], { timeout: 2000 }, (err, stdout) => {
+ execFile('tmux', tmuxCaptureArgs(pane, historyLines, options), { timeout: 2000 }, (err, stdout) => {
if (err) { resolve(null); return }
resolve(stdout)
})
diff --git a/cli/src/lib/tmuxAgentDiscovery.real.spec.ts b/cli/src/lib/tmuxAgentDiscovery.real.spec.ts
index 8d100a315..63a8cbac1 100644
--- a/cli/src/lib/tmuxAgentDiscovery.real.spec.ts
+++ b/cli/src/lib/tmuxAgentDiscovery.real.spec.ts
@@ -1,5 +1,5 @@
import { execFile } from 'node:child_process'
-import { mkdtemp, rm } from 'node:fs/promises'
+import { access, mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { promisify } from 'node:util'
@@ -11,15 +11,21 @@ import {
ENGINE_CLI_COMMANDS,
ENGINES,
executableFileIdentity,
+ installedEngineBin,
} from './engineBin.js'
+import { TmuxBackend } from './tmuxBackend.js'
import { probeTmuxAgents } from './tmuxAgentDiscovery.js'
const exec = promisify(execFile)
const realDescribe = process.env.RUN_REAL_TMUX_DISCOVERY === '1' ? describe : describe.skip
const createdSessions = new Set<string>()
-const engines: Array<[AgentEngine, string]> = ENGINES.map((engine) => [engine, ENGINE_CLI_COMMANDS[engine]])
const ownership = agentCommandOwnershipSnapshot()
+const engines: Array<[AgentEngine, string, string | null]> = ENGINES.map((engine) => [
+ engine,
+ ENGINE_CLI_COMMANDS[engine],
+ installedEngineBin(engine, ownership),
+])
const installedAgentAliases: Array<[AgentEngine, string]> = []
const seenAgentAliases = new Set<string>()
for (const [engine, candidates] of [
@@ -48,13 +54,6 @@ async function eventually<T>(read: () => Promise<T | null>, timeoutMs = 20_000):
return null
}
-async function executable(name: string): Promise<string> {
- const result = await exec('/bin/zsh', ['-lc', `command -v ${name}`], { timeout: 5_000 })
- const path = result.stdout.trim()
- if (!path) throw new Error(`${name} is not installed`)
- return path
-}
-
realDescribe.sequential('real installed CLI process discovery', () => {
afterAll(async () => {
for (const session of createdSessions) {
@@ -62,52 +61,110 @@ realDescribe.sequential('real installed CLI process discovery', () => {
}
})
- it.each(engines)('discovers %s once and process-only deletion preserves its pane', async (engine, bin) => {
- const dir = await mkdtemp(join(tmpdir(), `harness-real-${engine}-`))
- const session = `harness-real-${process.pid}-${engine}`
+ it('creates, notifies, and kills a test-owned session through the shared backend contract', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'harness-real-tmux-lifecycle-'))
+ const session = `harness-real-${process.pid}-lifecycle`
+ const backend = new TmuxBackend()
createdSessions.add(session)
+ try {
+ const created = await backend.create({ cwd: dir, label: session })
+ expect(created.state).toBe('succeeded')
+ if (created.state !== 'succeeded') return
+ await expect(tmux(['display-message', '-p', '-t', created.runtime.paneId, '#{session_name}']))
+ .resolves.toBe(session)
+ await expect(backend.notify(created.runtime, 'Harness test', 'Lifecycle message'))
+ .resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })
+ await expect(backend.kill(created.runtime))
+ .resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })
+ await expect(tmux(['has-session', '-t', session])).rejects.toBeTruthy()
+ createdSessions.delete(session)
+ } finally {
+ await exec('tmux', ['kill-session', '-t', session], { timeout: 5_000 }).catch(() => {})
+ createdSessions.delete(session)
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+
+ for (const [engine, bin, path] of engines) {
+ if (!path) console.warn(`[tmux-real] unavailable matrix row: ${engine} (${bin} has no verified installed executable)`)
+ const matrixIt = path ? it : it.skip
+ matrixIt(`discovers ${engine} once and process-only deletion preserves its pane`, async () => {
+ const dir = await mkdtemp(join(tmpdir(), `harness-real-${engine}-`))
+ const session = `harness-real-${process.pid}-${engine}`
+ createdSessions.add(session)
+
+ try {
+ await tmux(['new-session', '-d', '-s', session, '-c', dir])
+ const pane = await tmux(['list-panes', '-t', session, '-F', '#{pane_id}'])
+ await tmux(['send-keys', '-t', pane, '-l', '--', path!])
+ await tmux(['send-keys', '-t', pane, 'C-m'])
+
+ const discovered = await eventually(async () => {
+ const result = await probeTmuxAgents()
+ if (!result.ok) throw new Error(result.error)
+ const inPane = result.agents.filter((candidate) => candidate.tmuxPane === pane)
+ return inPane.length === 1 && inPane[0].engine === engine ? inPane[0] : null
+ })
+ const capture = await tmux(['capture-pane', '-p', '-t', pane]).catch(() => '')
+ expect(discovered, `${bin} was not discovered in ${pane}\n${capture}`).not.toBeNull()
+
+ const pid = discovered!.processIdentity.pid
+ process.kill(pid, 'SIGTERM')
+ const gone = await eventually(async () => {
+ try { process.kill(pid, 0) } catch { return true }
+ return null
+ }, 2_000)
+ if (!gone) {
+ try { process.kill(pid, 'SIGKILL') } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error
+ }
+ }
+
+ const absent = await eventually(async () => {
+ const result = await probeTmuxAgents()
+ if (!result.ok) throw new Error(result.error)
+ return result.agents.some((candidate) => candidate.tmuxPane === pane) ? null : true
+ }, 5_000)
+ expect(absent, `${bin} remained discoverable after its exact saved PID was terminated`).toBe(true)
+ await expect(tmux(['display-message', '-p', '-t', pane, '#{pane_id}'])).resolves.toBe(pane)
+ } finally {
+ await exec('tmux', ['kill-session', '-t', session], { timeout: 5_000 }).catch(() => {})
+ createdSessions.delete(session)
+ await rm(dir, { recursive: true, force: true })
+ }
+ }, 35_000)
+ }
+ it('types literally and submits short text through stdin-loaded buffers', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'harness-real-tmux-input-'))
+ const session = `harness-real-${process.pid}-input`
+ createdSessions.add(session)
try {
- const path = await executable(bin)
await tmux(['new-session', '-d', '-s', session, '-c', dir])
const pane = await tmux(['list-panes', '-t', session, '-F', '#{pane_id}'])
- await tmux(['send-keys', '-t', pane, '-l', '--', path])
- await tmux(['send-keys', '-t', pane, 'C-m'])
+ const runtime = { backend: 'tmux' as const, paneId: pane }
+ const backend = new TmuxBackend()
+ const literalMarker = join(dir, 'literal-marker')
+ const submitMarker = join(dir, 'submit-marker')
- const discovered = await eventually(async () => {
- const result = await probeTmuxAgents()
- if (!result.ok) throw new Error(result.error)
- const inPane = result.agents.filter((candidate) => candidate.tmuxPane === pane)
- return inPane.length === 1 && inPane[0].engine === engine ? inPane[0] : null
+ await expect(backend.typeLiteral(runtime, `touch ${literalMarker}`)).resolves.toEqual({
+ state: 'succeeded', dispatch: 'executed',
})
- const capture = await tmux(['capture-pane', '-p', '-t', pane]).catch(() => '')
- expect(discovered, `${bin} was not discovered in ${pane}\n${capture}`).not.toBeNull()
-
- const pid = discovered!.processIdentity.pid
- process.kill(pid, 'SIGTERM')
- const gone = await eventually(async () => {
- try { process.kill(pid, 0) } catch { return true }
- return null
- }, 2_000)
- if (!gone) {
- try { process.kill(pid, 'SIGKILL') } catch (error) {
- if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error
- }
- }
+ await new Promise((resolve) => setTimeout(resolve, 100))
+ await expect(access(literalMarker)).rejects.toBeTruthy()
+ await expect(backend.sendKey(runtime, 'enter')).resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })
+ expect(await eventually(() => access(literalMarker).then(() => true).catch(() => null), 5_000)).toBe(true)
- const absent = await eventually(async () => {
- const result = await probeTmuxAgents()
- if (!result.ok) throw new Error(result.error)
- return result.agents.some((candidate) => candidate.tmuxPane === pane) ? null : true
- }, 5_000)
- expect(absent, `${bin} remained discoverable after its exact saved PID was terminated`).toBe(true)
- await expect(tmux(['display-message', '-p', '-t', pane, '#{pane_id}'])).resolves.toBe(pane)
+ await expect(backend.submitText(runtime, `touch ${submitMarker}`)).resolves.toEqual({
+ state: 'succeeded', dispatch: 'executed',
+ })
+ expect(await eventually(() => access(submitMarker).then(() => true).catch(() => null), 5_000)).toBe(true)
} finally {
await exec('tmux', ['kill-session', '-t', session], { timeout: 5_000 }).catch(() => {})
createdSessions.delete(session)
await rm(dir, { recursive: true, force: true })
}
- }, 35_000)
+ }, 15_000)
it.each(installedAgentAliases)('classifies installed %s alias named agent from its executable identity', async (engine, path) => {
const dir = await mkdtemp(join(tmpdir(), `harness-real-agent-alias-${engine}-`))
diff --git a/cli/src/lib/tmuxAgentDiscovery.spec.ts b/cli/src/lib/tmuxAgentDiscovery.spec.ts
index 40caf288f..cf040d9ae 100644
--- a/cli/src/lib/tmuxAgentDiscovery.spec.ts
+++ b/cli/src/lib/tmuxAgentDiscovery.spec.ts
@@ -299,6 +299,8 @@ function observed(pid: number, engine: AgentEngine = 'claude'): DiscoveredTmuxAg
function registered(agent: DiscoveredTmuxAgent, agentId = 'agent-1'): RegisteredSession {
return {
+ schemaVersion: 2,
+ active: true,
agentId,
sessionId: '',
boundAt: null,
@@ -307,6 +309,8 @@ function registered(agent: DiscoveredTmuxAgent, agentId = 'agent-1'): Registered
projectDir: 'demo',
cwd: agent.cwd,
tmuxPane: agent.tmuxPane,
+ runtimes: [{ backend: 'tmux', paneId: agent.tmuxPane }],
+ primaryRuntimeKey: `tmux\u0000${agent.tmuxPane}`,
source: null,
title: null,
model: null,
diff --git a/cli/src/lib/tmuxAgentDiscovery.ts b/cli/src/lib/tmuxAgentDiscovery.ts
index 6aa89efcd..644a0fde2 100644
--- a/cli/src/lib/tmuxAgentDiscovery.ts
+++ b/cli/src/lib/tmuxAgentDiscovery.ts
@@ -64,7 +64,7 @@ function execText(command: string, args: string[], timeout: number): Promise<{ o
})
}
-function parsePanes(stdout: string): TmuxPaneSnapshot[] {
+export function parsePanes(stdout: string): TmuxPaneSnapshot[] {
const panes: TmuxPaneSnapshot[] = []
for (const line of stdout.split('\n')) {
const [tmuxPane, pidText, ...cwdParts] = line.split('\t')
@@ -75,6 +75,16 @@ function parsePanes(stdout: string): TmuxPaneSnapshot[] {
return panes
}
+export type TmuxPaneInventory =
+ | { ok: true; panes: TmuxPaneSnapshot[] }
+ | { ok: false; error: string }
+
+/** One bounded tmux inventory read, shared by discovery and the neutral backend adapter. */
+export async function listTmuxPanes(): Promise<TmuxPaneInventory> {
+ const result = await execText('tmux', ['list-panes', '-a', '-F', '#{pane_id}\t#{pane_pid}\t#{pane_current_path}'], 2_000)
+ return result.ok ? { ok: true, panes: parsePanes(result.stdout) } : result
+}
+
function childrenByParent(rows: readonly ProcessRow[]): Map<number, ProcessRow[]> {
const children = new Map<number, ProcessRow[]>()
for (const row of rows) {
@@ -188,7 +198,7 @@ export async function probeTmuxAgents(
hints: ReadonlyMap<string, AgentEngine> = new Map(),
): Promise<TmuxAgentProbe> {
const [tmux, ps] = await Promise.all([
- execText('tmux', ['list-panes', '-a', '-F', '#{pane_id}\t#{pane_pid}\t#{pane_current_path}'], 2_000),
+ listTmuxPanes(),
execText('ps', ['-axo', 'pid=,ppid=,comm=,lstart=,args='], 3_000),
])
if (!tmux.ok) return { ok: false, error: `tmux list-panes failed: ${tmux.error}` }
@@ -196,7 +206,7 @@ export async function probeTmuxAgents(
const parsed = ps.stdout.split('\n').map(parseProcessRow).filter((row): row is ProcessRow => row !== null)
const rows = await enrichProcessRows(parsed)
return discoverTmuxAgentsFromSnapshot(
- parsePanes(tmux.stdout),
+ tmux.panes,
rows,
daemonPid,
agentCommandOwnershipSnapshot(),
diff --git a/cli/src/lib/tmuxBackend.spec.ts b/cli/src/lib/tmuxBackend.spec.ts
new file mode 100644
index 000000000..a2dfe44fb
--- /dev/null
+++ b/cli/src/lib/tmuxBackend.spec.ts
@@ -0,0 +1,68 @@
+import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { delimiter, join } from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { TmuxBackend } from './tmuxBackend.js'
+
+const originalPath = process.env.PATH
+const dirs: string[] = []
+
+afterEach(() => {
+ process.env.PATH = originalPath
+ delete process.env.TMUX_BACKEND_CALLS
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
+})
+
+describe('TmuxBackend lifecycle', () => {
+ it('creates a detached session and kills the session resolved from its root pane', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-lifecycle-'))
+ dirs.push(dir)
+ const calls = join(dir, 'calls')
+ const tmux = join(dir, 'tmux')
+ writeFileSync(tmux, `#!/bin/sh
+printf '%s\\n' "$*" >> "$TMUX_BACKEND_CALLS"
+case "$1" in
+ new-session) printf '%%42\\n' ;;
+ display-message) printf '$7\\n' ;;
+esac
+`)
+ chmodSync(tmux, 0o700)
+ process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`
+ process.env.TMUX_BACKEND_CALLS = calls
+ const backend = new TmuxBackend()
+
+ const created = await backend.create({ cwd: '/tmp/work', label: 'harness-test' })
+ expect(created).toEqual({
+ state: 'succeeded', dispatch: 'executed', runtime: { backend: 'tmux', paneId: '%42' },
+ })
+ if (created.state !== 'succeeded') return
+ await expect(backend.kill(created.runtime)).resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })
+ expect(readFileSync(calls, 'utf8').trim().split('\n')).toEqual([
+ 'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-test',
+ 'display-message -p -t %42 #{session_id}',
+ 'kill-session -t $7',
+ ])
+ })
+
+ it('displays a bounded message in the addressed pane without a shell', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-notify-'))
+ dirs.push(dir)
+ const calls = join(dir, 'calls')
+ const tmux = join(dir, 'tmux')
+ writeFileSync(tmux, `#!/bin/sh
+printf '%s\\n' "$*" >> "$TMUX_BACKEND_CALLS"
+`)
+ chmodSync(tmux, 0o700)
+ process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`
+ process.env.TMUX_BACKEND_CALLS = calls
+
+ await expect(new TmuxBackend().notify(
+ { backend: 'tmux', paneId: '%7' },
+ 'Build status',
+ 'Ready; touch /tmp/must-not-run',
+ )).resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })
+ expect(readFileSync(calls, 'utf8').trim()).toBe(
+ 'display-message -t %7 -- Build status: Ready; touch /tmp/must-not-run',
+ )
+ })
+})
diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.ts
new file mode 100644
index 000000000..6a89ee7e6
--- /dev/null
+++ b/cli/src/lib/tmuxBackend.ts
@@ -0,0 +1,181 @@
+import { execFile } from 'node:child_process'
+import type { TerminalBackend } from './terminalBackend.js'
+import {
+ TERMINAL_ACTION_SUCCEEDED,
+ terminalActionNotStarted,
+ terminalActionPossiblyExecuted,
+ type TerminalActionResult,
+ type TerminalCaptureOptions,
+ type TerminalCreateRequest,
+ type TerminalCreateResult,
+ type TerminalInventoryResult,
+ type TerminalLogicalKey,
+ type TerminalProcessExpectation,
+ type TerminalReadResult,
+ type TmuxRuntimeRef,
+ type RuntimeValidation,
+} from './terminalTypes.js'
+import {
+ captureTmuxPane,
+ listPaneTitles,
+ resolvePaneEngineProcess,
+ sendKeyToTmux,
+ sendLiteralToTmux,
+ sendToTmux,
+} from './tmux.js'
+import { listTmuxPanes } from './tmuxAgentDiscovery.js'
+import { terminalRouteKey } from './terminalRuntime.js'
+
+const TMUX_KEYS: Record<TerminalLogicalKey, string> = {
+ enter: 'Enter',
+ escape: 'Escape',
+ tab: 'Tab',
+ backtab: 'BTab',
+ up: 'Up',
+ down: 'Down',
+ left: 'Left',
+ right: 'Right',
+ home: 'Home',
+ end: 'End',
+ backspace: 'BSpace',
+ delete: 'DC',
+ pageup: 'PPage',
+ pagedown: 'NPage',
+ 'ctrl-c': 'C-c',
+ 'ctrl-d': 'C-d',
+ 'ctrl-u': 'C-u',
+ 'ctrl-w': 'C-w',
+ space: 'Space',
+ '0': '0',
+ '1': '1',
+ '2': '2',
+ '3': '3',
+ '4': '4',
+ '5': '5',
+ '6': '6',
+ '7': '7',
+ '8': '8',
+ '9': '9',
+}
+
+function legacyActionResult(ok: boolean, operation: string): TerminalActionResult {
+ // The legacy helper has spawned tmux before it reports false, so execution cannot safely be ruled out.
+ return ok ? TERMINAL_ACTION_SUCCEEDED : terminalActionPossiblyExecuted(`${operation} did not complete`)
+}
+
+export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
+ readonly name = 'tmux' as const
+ readonly instanceId = 'tmux:default'
+
+ async create(request: TerminalCreateRequest): Promise<TerminalCreateResult<TmuxRuntimeRef>> {
+ const args = ['new-session', '-d', '-P', '-F', '#{pane_id}']
+ if (request.cwd) args.push('-c', request.cwd)
+ if (request.label) args.push('-s', request.label)
+ const result = await new Promise<{ error: NodeJS.ErrnoException | null; stdout: string }>((resolve) => {
+ execFile('tmux', args, { timeout: 5_000 }, (error, stdout) => resolve({
+ error: error as NodeJS.ErrnoException | null,
+ stdout,
+ }))
+ })
+ if (result.error) {
+ return result.error.code === 'ENOENT'
+ ? terminalActionNotStarted('tmux is unavailable')
+ : terminalActionPossiblyExecuted('tmux session creation did not complete')
+ }
+ const paneId = result.stdout.trim()
+ if (!/^%\d+$/.test(paneId)) {
+ return terminalActionPossiblyExecuted('tmux created a session without returning its root pane')
+ }
+ return { state: 'succeeded', dispatch: 'executed', runtime: { backend: 'tmux', paneId } }
+ }
+
+ async kill(runtime: TmuxRuntimeRef): Promise<TerminalActionResult> {
+ const sessionId = await new Promise<string | null>((resolve) => {
+ execFile('tmux', ['display-message', '-p', '-t', runtime.paneId, '#{session_id}'], { timeout: 2_000 }, (error, stdout) => {
+ const value = stdout.trim()
+ resolve(!error && /^\$\d+$/.test(value) ? value : null)
+ })
+ })
+ if (!sessionId) return terminalActionNotStarted('tmux session could not be resolved from pane')
+ const ok = await new Promise<boolean>((resolve) => {
+ execFile('tmux', ['kill-session', '-t', sessionId], { timeout: 5_000 }, (error) => resolve(!error))
+ })
+ return legacyActionResult(ok, 'tmux session close')
+ }
+
+ async titles(): Promise<TerminalReadResult<Map<string, string>>> {
+ const titles = await listPaneTitles()
+ return {
+ state: 'succeeded',
+ value: new Map([...titles].map(([paneId, title]) => [terminalRouteKey({ backend: 'tmux', paneId }), title])),
+ }
+ }
+
+ async inventory(): Promise<TerminalInventoryResult> {
+ const result = await listTmuxPanes()
+ if (!result.ok) return { state: 'unavailable', reason: result.error }
+ return {
+ state: 'available',
+ roots: result.panes.map((pane) => ({
+ runtime: { backend: 'tmux' as const, paneId: pane.tmuxPane },
+ rootPid: pane.rootPid,
+ cwd: pane.cwd,
+ })),
+ }
+ }
+
+ async validate(runtime: TmuxRuntimeRef, expected: TerminalProcessExpectation): Promise<RuntimeValidation> {
+ try {
+ const live = await resolvePaneEngineProcess(runtime.paneId, expected.engine)
+ if (!live) return { state: 'gone', reason: `no ${expected.engine} process under tmux pane` }
+ if (expected.processIdentity
+ && (expected.processIdentity.pid !== live.pid || expected.processIdentity.startMarker !== live.startMarker)) {
+ return { state: 'gone', reason: 'process changed under tmux pane' }
+ }
+ return { state: 'alive' }
+ } catch {
+ return { state: 'unknown', reason: 'tmux runtime probe failed' }
+ }
+ }
+
+ async capture(runtime: TmuxRuntimeRef, options: TerminalCaptureOptions = {}): Promise<TerminalReadResult<string>> {
+ const captured = await captureTmuxPane(runtime.paneId, options.historyLines, {
+ visible: options.mode === 'visible',
+ ansi: options.ansi,
+ })
+ return captured === null
+ ? { state: 'failed', reason: 'tmux capture failed' }
+ : { state: 'succeeded', value: captured }
+ }
+
+ async typeLiteral(runtime: TmuxRuntimeRef, text: string): Promise<TerminalActionResult> {
+ return legacyActionResult(await sendLiteralToTmux(runtime.paneId, text), 'tmux literal input')
+ }
+
+ async submitText(runtime: TmuxRuntimeRef, text: string): Promise<TerminalActionResult> {
+ return legacyActionResult(await sendToTmux(runtime.paneId, text), 'tmux submission')
+ }
+
+ async sendKey(runtime: TmuxRuntimeRef, key: TerminalLogicalKey): Promise<TerminalActionResult> {
+ return legacyActionResult(await sendKeyToTmux(runtime.paneId, TMUX_KEYS[key]), 'tmux key input')
+ }
+
+ async setTitle(runtime: TmuxRuntimeRef, title: string): Promise<TerminalActionResult> {
+ const ok = await new Promise<boolean>((resolve) => {
+ execFile('tmux', ['select-pane', '-t', runtime.paneId, '-T', title.slice(0, 200)], { timeout: 2_000 }, (error) => {
+ resolve(!error)
+ })
+ })
+ return legacyActionResult(ok, 'tmux title update')
+ }
+
+ async notify(runtime: TmuxRuntimeRef, title: string, body: string): Promise<TerminalActionResult> {
+ const message = `${title.slice(0, 200)}: ${body.slice(0, 1_000)}`
+ const ok = await new Promise<boolean>((resolve) => {
+ execFile('tmux', ['display-message', '-t', runtime.paneId, '--', message], { timeout: 2_000 }, (error) => {
+ resolve(!error)
+ })
+ })
+ return legacyActionResult(ok, 'tmux notification')
+ }
+}
diff --git a/cli/src/webui.ts b/cli/src/webui.ts
index 9ddc90eef..063a1b4d7 100644
--- a/cli/src/webui.ts
+++ b/cli/src/webui.ts
@@ -267,8 +267,8 @@ function render(s){
// sessions
const se = document.getElementById('sessions');
se.innerHTML = (s.sessions&&s.sessions.length) ? s.sessions.map(x =>
- '<div class="row"><div class="main"><div class="name">'+esc(x.name)+'</div><div class="sub">'+esc(x.cwd||'')+' · '+esc(x.tmuxPane||'')+'</div></div><div class="mut" style="font-size:12px">'+fmtWhen(x.updatedAt)+'</div></div>'
- ).join('') : '<div class="empty">No tmux claude sessions. Run <span class="mono">claude</span> in a tmux pane.</div>';
+ '<div class="row"><div class="main"><div class="name">'+esc(x.name)+'</div><div class="sub">'+esc(x.cwd||'')+' · '+esc((x.terminal&&x.terminal.primary)||x.tmuxPane||'')+'</div></div><div class="mut" style="font-size:12px">'+fmtWhen(x.updatedAt)+'</div></div>'
+ ).join('') : '<div class="empty">No active terminal agents.</div>';
// pairs
const pe = document.getElementById('pairs');
diff --git a/docs/plans/2026-08-15-001-feat-selectable-tmux-herdr-backends-plan.md b/docs/plans/2026-08-15-001-feat-selectable-tmux-herdr-backends-plan.md
new file mode 100644
index 000000000..279dd39d1
--- /dev/null
+++ b/docs/plans/2026-08-15-001-feat-selectable-tmux-herdr-backends-plan.md
@@ -0,0 +1,839 @@
+---
+title: "feat: selectable tmux and Herdr terminal backends"
+date: 2026-08-15
+type: feat
+artifact_contract: ce-unified-plan/v1
+artifact_readiness: implementation-ready
+product_contract_source: user-approved-scope
+execution: code
+deepened: 2026-08-15
+---
+
+# feat: selectable tmux and Herdr terminal backends
+
+Add Herdr 0.8.x as a fully supported terminal backend beside tmux. tmux remains the default; operators can enable tmux, Herdr, or both. The implementation introduces backend-neutral runtime identity, discovery, input, capture, validation, and hook handling without changing the transcript/event pipeline or requiring a private Herdr-only fork.
+
+This plan supersedes the architecture—but not the research—in [`2026-08-11-herdr-runtime-fork.md`](./2026-08-11-herdr-runtime-fork.md). That document is preserved as historical context. Its verified Herdr findings remain useful; its “replace tmux” product decision does not.
+
+---
+
+## Goal Capsule
+
+- **Objective:** Make the terminal multiplexer an additive, configured capability. Existing tmux users upgrade without behavior or identity loss; Herdr users receive equivalent discovery, remote input, terminal inspection, lifecycle validation, and supported-engine behavior.
+- **Authority:** This plan; current upstream [`CONTRIBUTING.md`](../../CONTRIBUTING.md) and [`cli/src/engines/README.md`](../../cli/src/engines/README.md); recorded behavior from real tmux and Herdr 0.8.x binaries; then implementer judgment for non-contractual details.
+- **Execution profile:** Obtain owner approval before publishing the required upstream design issue or any PR. Run U1’s isolated API spike first, then complete U2–U9 locally while keeping every automated gate green; attach U1/U9 evidence and obtain maintainer direction before any implementation lands upstream. Do not merge Herdr behavior based only on mocks; U1 requires real transport/identity/input evidence and U9 requires the full real-multiplexer matrix.
+- **Stop conditions:** Stop before broad implementation only if Herdr’s versioned socket API cannot expose endpoint-scoped pane identity, cannot carry long/multiline text without argv/log exposure, cannot preserve exact-once-aware dispatch semantics, or cannot distinguish unavailable from a successful empty inventory. Missing third-party engine credentials or individual parser captures do not stop U2–U8; they remain explicit U9 release-evidence blockers. Stop an individual reconciliation cycle—not the daemon—when a configured backend or process-table probe is unavailable.
+- **Tail ownership:** The implementation owner records any divergence from a KTD in the upstream issue/PR. Deferred wire renames and future multiplexer backends remain separate follow-up work.
+- **Definition of done:** See `## Definition of Done`.
+
+---
+
+## Product Contract
+
+### Summary
+
+Harness currently treats tmux as both a command runner and part of persisted agent identity. The direct tmux command surface is small, but `tmuxPane` and `TMUX_PANE` flow through the registry, process discovery, online and offline hooks, one-shot isolation, input controllers, status payloads, and UI-driving code. Herdr 0.8.x exposes the required pane, process, input, capture, lifecycle, and local-socket APIs, but its identity model differs: a `terminal_id` survives pane moves while a public pane ID is only a mutable route, and pane IDs are unique only inside one Herdr session/endpoint.
+
+The feature therefore adds a shared terminal-backend boundary and migrates identity rather than transliterating tmux commands into Herdr commands.
+
+### Problem Frame
+
+- Replacing tmux outright violates current upstream contribution guidance and would orphan existing users’ persisted agents.
+- Reusing a string called `tmuxPane` for Herdr would hide endpoint collisions and pane-move semantics.
+- Treating Herdr `terminal_id` as the whole agent identity would incorrectly reuse an `agentId` when an engine process exits and a new process starts in the same terminal.
+- Treating transport errors as proof of death would evict live agents during load spikes, server restarts, or CLI/API timeouts.
+- Treating text insertion as submission can swallow Enter, split multiline payloads, or duplicate a prompt after an ambiguous transport response.
+- Hooks and recap workers must identify or deliberately erase terminal context for both backends, including the dependency-free daemon-down fallback.
+
+### Actors
+
+- **Operator:** Configures enabled terminal backends and optional Herdr named sessions, then starts supported agent CLIs in tmux and/or Herdr.
+- **Harness daemon:** Discovers processes, binds engine sessions, drives terminal UI, and persists backend-neutral runtime state.
+- **Engine process:** The authoritative lifetime of one visible agent. Its session/transcript may rotate underneath it.
+- **Engine hook/plugin:** Supplies session metadata and a terminal-location hint; it never owns process identity.
+- **tmux server / Herdr server:** Own terminal routes and I/O. Each server can be unavailable independently.
+- **Web/device client:** Addresses stable Harness `agentId` values and must not need to understand terminal backend details.
+
+### Requirements
+
+- **R1 — Additive configuration.** `TERMINAL_BACKENDS` is a strict comma-separated list supporting `tmux`, `herdr`, and `tmux,herdr`; the default is `tmux`. Unknown or empty values fail startup with an actionable error.
+- **R2 — Named Herdr targets.** When Herdr is enabled, Harness connects only to configured named Herdr sessions. `HERDR_SESSIONS` defaults to `default`; an explicit ordered list enables additional sessions and supplies deterministic tie-breaking. Two Herdr sessions may expose the same public pane ID without collision.
+- **R3 — Backend-neutral locator model.** Persist one or more discriminated terminal runtime locators on each process-owned agent. tmux retains its pane route; Herdr persists a canonical endpoint/session identity, stable `terminal_id`, and current pane route. No backend-neutral API or registry index is named `tmuxPane`.
+- **R4 — Process-authoritative identity and cross-backend deduplication.** The process identity `(engine, pid, start marker)` remains authoritative. One process visible through nested/coexisting multiplexers produces one `agentId` with multiple validated locators and one deterministic primary control route. A Herdr pane move preserves the `agentId`; a different engine process in the same `terminal_id` creates a replacement agent.
+- **R5 — Upgrade- and rollback-safe persistence.** Existing `registry.json` records containing `tmuxPane` load as tmux runtime locators without changing `agentId`, engine-session bindings, names, or timestamps. The new runtime model is authoritative, but tmux rows retain an additive legacy `tmuxPane` projection for a compatibility release so rollback does not orphan tmux agents. Records with no currently enabled/healthy locator are preserved but not advertised as active.
+- **R6 — Discovery parity.** All engines currently supported by `cli/src/lib/tmuxAgentDiscovery.ts` remain discoverable under tmux and Herdr. One reconciliation cycle reads the OS process table once, treats backend pane inventories as roots/hints, merges observations by process identity, and preserves shallowest-process ownership, ambiguity handling, resume-ID recovery, daemon-descendant exclusion, deletion suppression, and two-confirmed-miss removal.
+- **R7 — Independent failure domains.** One backend or Herdr endpoint failing does not block successful discovery from another. Failed or timed-out probes produce `unknown` and cannot increment miss counts or evict agents.
+- **R8 — Hook parity and trust boundary.** New hooks/plugins derive zero or more typed terminal hints plus a non-authoritative caller-PID hint from tmux and Herdr context. Every mutating loopback hook request also authenticates with a rotatable per-install high-entropy credential that is stored mode `0600`, never exposed through argv/logs, and verified in constant time; authenticated events are bound to the registered session/process identity. The daemon accepts legacy tmux payload shapes only over this authenticated channel, resolves hints only against configured backend inventory, and verifies the caller PID as the expected engine process or descendant in the authoritative process snapshot. Nested contexts are deduplicated rather than resolved by environment-variable priority. A stale route with no verified caller correlation fails closed, and a hook cannot make Harness connect to an arbitrary socket path.
+- **R9 — Offline fallback parity.** `cli/hook/notify.mjs` can register a top-level engine safely while the daemon is down for both backends, using the same registry schema, process validation, and an atomically persisted non-secret snapshot of resolved backend configuration. Before the first valid snapshot—or when the relevant endpoint/caller cannot be verified—Herdr fallback skips registration rather than guessing; legacy tmux fallback remains compatible.
+- **R10 — One-shot isolation.** Every recap/voice/summary child strips tmux and Herdr location variables before spawning so the child cannot become a phantom top-level agent or pollute multiplexer-native agent detection.
+- **R11 — Exact-once-aware input.** The backend contract distinguishes literal typing, text submission, and logical key presses. Submission strips trailing newlines, preserves multiline content, and returns both outcome and dispatch evidence. Side-effecting failover is allowed only when execution is known not to have started; ambiguous completion is never blindly retried.
+- **R12 — Capture and control parity.** Herdr capture preserves ANSI style, joins soft wraps, bounds history, and supplies enough current UI for question dialogs, idle/draft detection, model/effort/profile pickers, Cursor composer clearing, and title sync. Parser behavior remains engine-specific rather than backend-specific.
+- **R13 — Safe lifecycle.** Validation is three-valued (`alive`, `gone`, `unknown`). Deleting an agent continues to signal only the validated engine process; neither backend closes a user-owned pane as part of agent deletion.
+- **R14 — Compatibility.** Web/device agent identity and transcript/provider protocols do not change. During a compatibility window, outbound project/status payloads retain `tmuxPane` for tmux records and add optional backend-neutral terminal metadata; new Herdr records never masquerade as tmux panes.
+- **R15 — Observability.** Logs and local status identify the backend and configured Herdr session without printing arbitrary socket paths or treating notification/event loss as liveness proof. Startup reports disabled, unavailable, and protocol-incompatible targets distinctly.
+- **R16 — Verified operation.** The default suite runs without tmux or Herdr installed. Opt-in real suites cover both backends. Herdr support is pinned initially to the verified 0.8.x schema/protocol and degrades safely on mismatch.
+
+### User and System Flows
+
+#### F1 — Startup and discovery
+
+1. Parse enabled backends and configured Herdr sessions.
+2. Build one backend instance for the single supported default tmux server and one per configured Herdr session endpoint.
+3. Load and migrate registry records without dropping disabled-backend state.
+4. Probe enabled backends independently and read one shared process snapshot.
+5. Match supported engine processes beneath each terminal root and merge duplicate observations by `(engine, pid, start marker)`.
+6. Adopt, refresh, replace, or suppress process agents while attaching all validated locators and selecting one primary control route.
+7. Publish only verified active agents to web/device clients.
+
+#### F2 — Hook registration
+
+1. An engine hook reads tmux and/or Herdr context from its environment and posts typed terminal hints, session metadata, and a caller PID hint (`process.pid`, `process.ppid`, or shell `PPID` according to the hook shape) over the authenticated per-install hook channel.
+2. The daemon applies strict request-size/schema bounds, verifies the hook credential in constant time, normalizes legacy and new payloads, and treats caller PID as untrusted input.
+3. Configured backends resolve live or aliased routes; for Herdr this adds `terminal_id` and the current route.
+4. Process discovery verifies the caller PID as the supported engine process or its expected descendant/ancestor chain, verifies the event session is already bound or eligible to bind to that process, and binds it to exactly one scanner-owned process identity.
+5. The registry binds the engine session to that one process agent, attaching any additional validated locators instead of minting duplicates. A stale/ambiguous route without caller correlation is rejected.
+6. If the daemon is down, `notify.mjs` reads the last atomically persisted backend snapshot and performs the same verification under the existing registry lock, or skips safely.
+
+#### F3 — Remote message and terminal control
+
+1. A web/device message resolves to a Harness `agentId`, then its deterministic primary validated terminal locator.
+2. Locator validation returns `alive`, `gone`, or `unknown`; another healthy locator may become primary before dispatch, and a multi-step control acquires a locator-generation lease.
+3. The selected backend submits the text with one submission action and reports whether PTY execution was impossible, rejected, executed, or ambiguous.
+4. `SessionInputController` observes transcript/pane evidence before any follow-up key action; ambiguous dispatch never fails over blindly.
+5. Question and profile controllers use backend-neutral capture, literal typing, and logical keys against the leased locator without learning how it was ranked. A mid-control primary change ends/restarts the interaction rather than splitting it across terminals.
+
+#### F4 — Herdr pane move
+
+1. A terminal moves between Herdr workspaces and receives a new pane route.
+2. Polling or a movement event observes the same endpoint-scoped `terminal_id` and process identity at the new route.
+3. The registry atomically updates the route and route index.
+4. The existing `agentId`, name, session binding, input queue, and transcript watcher remain attached.
+5. A later hook carrying an old inherited pane ID is correlated by verified caller PID and, when supported, the backend’s route alias; two same-engine processes cannot be confused and an ambiguous legacy hint fails closed.
+
+#### F5 — Backend outage, disable, and recovery
+
+1. A backend probe times out, its server stops, or the backend is removed from `TERMINAL_BACKENDS`.
+2. The daemon keeps other backends operational and does not count the failed backend as a negative observation. An agent with another healthy locator remains active.
+3. On losing its last healthy locator, an active agent becomes dormant: queued input fails visibly, control leases release, outbound turn/control events pause, and clients converge through the existing offline/deletion event while registry/name/session/transcript cursor state remains.
+4. Re-enabling or recovering a target triggers a fresh authoritative snapshot. After process + locator validation, the same `agentId` is republished with current normalized state; replaced processes are recreated and confirmed absences are removed through normal miss rules.
+
+### Acceptance Examples
+
+- **AE1:** With no new environment variables, a current tmux installation upgrades and preserves every live agent’s `agentId` and session binding.
+- **AE2:** With `TERMINAL_BACKENDS=herdr`, no tmux binary is required for discovery, input, capture, validation, or hooks.
+- **AE3:** With `TERMINAL_BACKENDS=tmux,herdr`, distinct agents in both backends remain independently controllable, while one process visible through nested tmux and Herdr appears once and receives one submitted message.
+- **AE4:** Herdr sessions `default` and `work` can both contain pane `w1:p1`; their agents do not collide because endpoint identity is part of every key.
+- **AE5:** With two same-engine Herdr processes running, moving one terminal between workspaces changes its pane route but preserves the correct Harness agent and public name; its stale-route hook rebinds only through verified caller correlation.
+- **AE6:** Restarting an engine in the same Herdr terminal replaces the old agent because process identity changed, despite stable `terminal_id`.
+- **AE7:** A multiline payload of approximately 28 KB reaches a deterministic terminal fixture byte-for-byte and is submitted once. A lost/ambiguous response does not cause duplicate submission.
+- **AE8:** Stopping or timing out one Herdr session yields `unknown`; no agent from that session is removed until a later successful snapshot confirms absence twice.
+- **AE9:** A recap worker started from inside either multiplexer emits no registration hook and is absent from both Harness and Herdr agent lists.
+- **AE10:** Old hook/plugin payloads containing only `tmuxPane` continue to bind a verified tmux process during the compatibility window.
+
+### Success Criteria
+
+- All existing tmux tests and the real-tmux discovery suite remain green.
+- The real-Herdr suite passes identity, discovery, capture, literal input, submission, key, move, outage, and same-pane-cross-session cases.
+- Every supported engine completes a recorded or manual Herdr smoke covering discovery, one prompt, one capture-driven control where supported, session rotation/resume, and deletion.
+- No daemon-side production call site outside a tmux adapter invokes tmux or assumes `%N` syntax. The sole exception is dependency-free `notify.mjs` daemon-down verification, whose bounded tmux/Herdr probes mirror the backend contract and are fixture-locked against the adapters.
+- No generic type, index, or dependency argument uses `tmuxPane` as a backend-neutral identity.
+- Default configuration behavior and web/device protocol behavior remain backward compatible.
+
+### Scope Boundaries
+
+**In scope**
+
+- `cli/` terminal operations, runtime identity, registry, discovery/reconciliation, hooks, one-shot environment handling, input/capture consumers, status, tests, packaging, and documentation.
+- tmux as the default first backend and Herdr 0.8.x as the second backend.
+- A configured set of local named Herdr sessions.
+- A focused Herdr socket-API adapter using Node built-ins, the generated v0.8 schema, bounded newline-delimited JSON framing, and no new runtime dependency. The Herdr CLI is limited to non-sensitive bootstrap/version/session discovery and acts as a diagnostic/test oracle rather than the production pane-control path.
+
+**Out of scope**
+
+- Removing tmux or maintaining a Herdr-only product fork.
+- Changing Herdr source, its native agent manifests, or its update channel.
+- Making Herdr’s native `agent_status` authoritative for Harness turns or lifecycle.
+- Replacing transcript readers, normalizers, provider protocol, or hosted backend behavior.
+- Harness-owned workspace layout, pane movement, or general-purpose terminal management UI.
+- Remote Herdr-over-SSH support and Windows support in the first release.
+- Immediate removal/rename of legacy outbound `tmuxPane` or `TMUX_FAILED` compatibility fields.
+
+### Dependencies and Sources
+
+- Upstream multiplexer contract: [`CONTRIBUTING.md`](../../CONTRIBUTING.md), especially “Adding a multiplexer.”
+- Engine contribution and replay requirements: [`cli/src/engines/README.md`](../../cli/src/engines/README.md).
+- Current tmux operations: [`cli/src/lib/tmux.ts`](../../cli/src/lib/tmux.ts).
+- Current process discovery: [`cli/src/lib/tmuxAgentDiscovery.ts`](../../cli/src/lib/tmuxAgentDiscovery.ts).
+- Current identity/persistence: [`cli/src/lib/registry.ts`](../../cli/src/lib/registry.ts).
+- Current hook paths: [`cli/src/hookServer.ts`](../../cli/src/hookServer.ts), [`cli/hook/notify.mjs`](../../cli/hook/notify.mjs), and [`cli/src/lib/hooks.ts`](../../cli/src/lib/hooks.ts).
+- Current input/control seams: [`cli/src/lib/sessionInput.ts`](../../cli/src/lib/sessionInput.ts), [`cli/src/lib/askQuestion.ts`](../../cli/src/lib/askQuestion.ts), and [`cli/src/lib/runtimeProfileController.ts`](../../cli/src/lib/runtimeProfileController.ts).
+- Herdr v0.8.0 API/source evidence: `HERDR_PANE_ID`, `HERDR_SOCKET_PATH`, and `HERDR_SESSION`; endpoint-scoped pane inventory; stable `terminal_id`; `pane.process_info`; `pane.send_text`, `pane.send_keys`, `pane.send_input`; `pane.read`; `session.snapshot`; and `events.subscribe` in [herdrdev/herdr v0.8.0](https://github.com/herdrdev/herdr/tree/v0.8.0).
+- Research baseline: Autonomous Harness upstream commit `a8d4a1a` and Herdr `v0.8.0`, reviewed 2026-08-15.
+
+---
+
+## Planning Contract
+
+### Settled Decisions
+
+- **User-approved — additive backends:** Keep tmux and add Herdr; chosen over a Herdr-only replacement because the user asked for a swappable setting and upstream requires coexistence.
+- **User-approved — new artifact:** Preserve the Aug 11 Herdr-only plan and create this dual-backend plan; chosen over rewriting historical context.
+- **User-approved — simultaneous operation:** Support tmux, Herdr, or both; chosen over an exactly-one-backend selector so users can migrate without stopping existing agents.
+- **User-approved — named-session coverage:** Support an explicit list of Herdr sessions; chosen over assuming only the default Herdr server.
+- **User-approved — staged full parity:** Use a focused feasibility gate first, then target all supported engines; chosen over stopping at a demo/MVP.
+- **User-approved — API-first Herdr transport:** Use Herdr’s versioned local socket API as the production control path while tmux remains CLI-backed; chosen over transport symmetry because functional parity matters and direct API requests avoid argv exposure.
+
+### Current Architecture and Change Surface
+
+- `cli/src/lib/tmux.ts` combines process-table helpers with tmux-specific pane PID lookup, runtime validation, input, keys, capture, and titles.
+- `cli/src/lib/tmuxAgentDiscovery.ts` already has the right core rule—“the process is the agent”—but its pane snapshot, keys, hints, and reconciler are tmux-shaped.
+- `cli/src/lib/registry.ts` persists and validates `tmuxPane`, indexes hooks by pane+engine, and deduplicates one agent per pane.
+- `cli/src/cli.ts` wires tmux functions directly into discovery, input, questions, profile control, title sync, status, and deletion.
+- `cli/src/backendSocket.ts` contains a direct tmux fallback and exposes `tmuxPane` on the outbound project shape.
+- `cli/src/hookServer.ts`, `cli/hook/notify.mjs`, and generated sources in `cli/src/lib/hooks.ts` use pane-scoped hook hints and process-authoritative binding; that trust model should remain.
+- `cli/src/lib/oneshot.ts` contains repeated tmux environment scrubbing that must be centralized and extended.
+- The transcript watcher and engine normalizers are terminal-backend neutral and should not move.
+
+### Key Technical Decisions
+
+- **KTD1 — One backend contract with acyclic ownership.** Put runtime refs, snapshots, action results, and key/capture vocabulary in a registry-independent `terminalTypes` module. `TerminalBackend` depends only on those types; tmux/Herdr adapters never import registry state. The coordinator owns backend instances and passes neutral observations to shared discovery; the registry owns persistence/indexes; input/control consumers resolve only through the coordinator. Shared process ownership, cross-backend deduplication, primary-route selection, and reconciliation remain outside adapters.
+- **KTD2 — Discriminated locators on a process-owned agent.** Use a runtime locator equivalent to:
+
+ ```ts
+ type TerminalRuntimeRef =
+ | { backend: 'tmux'; paneId: string }
+ | { backend: 'herdr'; endpointId: string; sessionName: string; terminalId: string; paneId: string }
+ ```
+
+ `endpointId + terminalId` identifies a Herdr terminal placement; `paneId` is the current route. V1 supports exactly the local default tmux server, so a tmux locator remains `%N`-scoped to that one instance. `engine + pid + startMarker` identifies the agent process across every backend. A registered agent stores `runtimes: TerminalRuntimeRef[]` plus a derived `primaryRuntimeKey`; central helpers produce stable placement and route keys so no caller concatenates fields ad hoc.
+- **KTD3 — Backward-read/additive-write registry migration.** Keep compatibility-release `registry.json` as a top-level array because the preceding loader treats any other root as empty. Put schema/version markers only in backward-tolerated row fields, and keep every legacy-required field on tmux rows. Load legacy `tmuxPane` records into `runtimes: [{backend:'tmux', paneId}]`; the new locator array is authoritative, while valid tmux rows continue to serialize a legacy `tmuxPane` projection for one compatibility release. Preserve public `agentId`, names, engine session bindings, and timestamps only for same-boot process identities. A machine boot-ID change invalidates every process-owned agent regardless of backend; Herdr placement may be rediscovered, but never carries the old `agentId` by itself. Keep same-boot agents with no enabled/healthy locator dormant instead of deleting them. Before code rollback, stop the new daemon, archive the current mixed array for forward recovery, and start the preceding binary only against a copied legacy-readable tmux projection; never let it destructively normalize the sole mixed-state copy.
+- **KTD4 — tmux is the first adapter and behavior oracle.** Extract today’s behavior behind `TmuxBackend` before adding Herdr. Characterization tests pin pane listing, process lookup, input fast/long paths, logical key names, ANSI capture, timeouts, and `alive|gone|unknown` behavior. tmux remains default and `npm run test:tmux-real` remains required.
+- **KTD5 — Herdr socket API is the primary control plane.** Implement a small typed `HerdrApiClient` over Node’s local-socket transport and Herdr’s versioned newline-delimited JSON protocol. Resolve configured named sessions with the non-sensitive `herdr session list --json` bootstrap, then use direct API requests for handshake/capabilities, `session.snapshot`, pane inventory/process info, capture, literal text, logical keys, title, and notifications. Pin protocol/schema compatibility from `ping` plus the generated v0.8 schema; bound request/response bytes and operation deadlines; generate unique request IDs; never use implicit focused-pane state. Prompt bytes remain in memory and the socket payload, never argv, environment, or logs. The CLI remains a diagnostic/test oracle and bootstrap fallback only for operations that carry no user content.
+- **KTD6 — Configured endpoints and the account-owner trust boundary.** Initial support trusts processes running as the owning local OS account; hostile same-UID isolation would require Herdr authentication or an OS sandbox and is not fabricated in Harness. Canonicalize configured session/socket paths once. Require each socket and parent directory to pass no-follow type, owner-UID, and mode checks; reject symlinks, non-sockets, unsafe parent permissions, unconfigured paths, and ownership/path replacement. Revalidate immediately before every connection. Use peer PID/UID checks where the platform exposes them as defense-in-depth, not as a cross-platform hard gate. Hook-supplied `HERDR_SOCKET_PATH` is a lookup hint only and must match a configured endpoint; Harness never connects to an arbitrary hook-provided socket. Endpoint logs use configured session names or short stable IDs, not raw paths.
+- **KTD7 — Shared process snapshot and batch graph remain authoritative.** Each backend lists terminal roots; one OS `ps` snapshot feeds the existing depth/score/ambiguity algorithm across all roots. A cycle first collects every successful/unknown target result into an immutable observation graph, resolves process ownership and locator conflicts, then commits one registry delta atomically. Probe completion order can never affect identity. Herdr-native agent kind/session/status can supply hints but cannot create, remove, or close a Harness agent by itself. `pane.process_info.shell_pid` supplies the Herdr root; PID start time still comes from `ps`.
+- **KTD8 — Composite reconciliation isolates failures and performs split/merge atomically.** Probe enabled backend instances independently and merge only successful observations. One process may accumulate several validated locators. Its primary control locator is the terminal root nearest that process in the ancestor tree; ties use `TERMINAL_BACKENDS` order, then `HERDR_SESSIONS` order for Herdr locators, then a verified hook-context match. If a locator now owns process B while process A remains alive through another locator, detach that locator from A and create/adopt B without mutating A’s public identity. Miss counters are locator-scoped; a failed endpoint leaves its locator/counters untouched, and a successful empty snapshot may advance only that locator’s misses.
+- **KTD9 — Terminal actions expose outcome and dispatch evidence.** Replace booleans with `succeeded/executed`, `failed/not_started|rejected`, or `unknown/possibly_executed`. Only `not_started` or explicit server rejection permits side-effecting failover to another locator. A timeout or child-process failure after possible dispatch is `unknown`; `SessionInputController` and profile/question controls must inspect transcript/capture state before any retry. Read-only capture may fail over freely after locator validation.
+- **KTD10 — Herdr submission is chosen by the spike, not assumed.** Prefer one Herdr API request that encodes bracketed-paste text plus Enter (`pane.send_input`/the v0.8 submission primitive). The U1 fixture must prove exact byte delivery and one submit for short, multiline, and ~28 KB payloads. If the primitive fails, use text plus a separately verified Enter with the existing settle/observation discipline; do not proceed without a passing exact-once test.
+- **KTD11 — Capture is semantic compatibility.** Request bounded `recent_unwrapped` ANSI capture for the tmux `-e -J -S` analogue, while allowing `visible` or `detection` for a specific parser only when a real fixture proves it. Re-record interaction fixtures in real Herdr panes; do not assume whitespace, wrapping, or alternate-screen history matches tmux.
+- **KTD12 — Hooks are authenticated, bounded, normalized, then process-verified.** New payloads carry backend-specific runtime hints plus a caller-PID hint; legacy `tmuxPane` remains accepted over the authenticated compatibility channel. Every mutating hook route verifies the per-install credential in constant time, applies byte/count/string/schema bounds before expensive work, and binds session-scoped events to the registered process. Caller PID is then verified against the shared process snapshot and expected engine ancestry before any binding. Herdr hints resolve only through the atomically persisted configured-endpoint snapshot and live backend inventory; a stale route may use a proven Herdr alias, but caller correlation is the required deterministic fallback. Nested hints attach to one process agent; ambiguous legacy hints fail closed.
+- **KTD13 — Environment isolation is centralized.** Add one `scrubTerminalContext(env)` helper for `TMUX`, `TMUX_PANE`, `HERDR_ENV`, `HERDR_SESSION`, `HERDR_SOCKET_PATH`, `HERDR_WORKSPACE_ID`, `HERDR_TAB_ID`, and `HERDR_PANE_ID`; apply it at every one-shot spawn and test the complete set. The daemon never uses inherited “current pane” state for routing.
+- **KTD14 — Compatibility is additive.** Keep current web/device IDs and provider payloads. Add optional neutral terminal metadata to local/outbound status while retaining `tmuxPane` only for actual tmux agents. Keep `TMUX_FAILED` as a compatibility alias while internal code moves to `TERMINAL_FAILED`.
+- **KTD15 — Upstream first, fork-safe meanwhile.** Obtain owner approval before publishing the required upstream issue or any PR. Local exploratory and implementation work may complete U1–U9 without external publication, but nothing lands upstream until the issue carries the proposed schema/evidence gates, U1 evidence is attached, and maintainer direction is obtained. Structure units as reviewable commits only when commit authorization exists. Until merged upstream, a distributed fork must disable upstream self-update or point `ADAPTER_UPDATE_URL` at a fork-owned signed manifest; a custom binary must never silently replace itself with upstream’s tmux-only build.
+
+### High-Level Design
+
+```mermaid
+flowchart LR
+ CFG[TERMINAL_BACKENDS + HERDR_SESSIONS] --> COORD[TerminalBackendCoordinator]
+ CFG --> SNAP[versioned terminal-config snapshot]
+ TMUX[TmuxBackend] --> COORD
+ H1[HerdrBackend: default] --> COORD
+ H2[HerdrBackend: work] --> COORD
+ COORD --> INV[neutral pane inventories]
+ PS[one ps snapshot] --> DISC[shared process discovery]
+ INV --> DISC
+ DISC --> REC[composite reconciler]
+ REC --> REG[registry: one process agent + validated locators]
+ SNAP --> HOOK[online/offline hooks]
+ HOOK -->|runtime hints + caller PID| REC
+ REG --> INPUT[SessionInputController]
+ REG --> CTRL[questions + runtime profiles]
+ INPUT --> COORD
+ CTRL --> COORD
+ COORD --> TMUX
+ COORD --> H1
+ COORD --> H2
+```
+
+#### Discovery, registration, and control sequence
+
+```mermaid
+sequenceDiagram
+ participant H as Hook or periodic scan
+ participant C as Backend coordinator
+ participant P as Shared process snapshot
+ participant R as Registry
+ participant I as Input/control caller
+ participant B as Selected backend
+
+ H->>C: runtime hint candidates or scan request
+ C->>C: probe each enabled target independently
+ C->>P: classify candidate process trees once
+ P-->>C: engine, PID, start marker, ancestor distance
+ C->>R: merge observations by process identity
+ R->>R: retain locators and select one primary route
+ I->>R: resolve agent to primary validated locator
+ R-->>I: leased typed locator + generation
+ I->>C: leased locator + capture/type/submit/key action
+ C->>B: validate route and dispatch action
+ B-->>C: outcome + dispatch evidence
+ C-->>I: normalized action result
+```
+
+Hooks accelerate the scanner-confirmed path used by polling. They do not create a second identity path, and callers never dispatch to every locator.
+
+#### Agent and locator lifecycle
+
+```mermaid
+stateDiagram-v2
+ [*] --> Probing: load, hook, or scan
+ Probing --> Active: at least one locator verifies the process
+ Active --> Active: route move, locator merge, or split with another locator alive
+ Active --> Dormant: no alive locator and any target is disabled or unknown; drain control
+ Dormant --> Active: target recovers and process verifies
+ Active --> Missing: every enabled locator reports gone
+ Dormant --> Missing: every enabled locator reports gone
+ Missing --> Active: process re-observed before miss threshold
+ Missing --> Removed: successful second miss
+ Active --> Replaced: no surviving observation; route now owns a new process
+ Replaced --> Probing: register replacement process
+ Removed --> [*]
+```
+
+`unknown` never advances a miss counter. A process-owned agent remains active while any locator validates; one locator failure cannot demote another backend’s healthy view.
+
+#### Configuration modes
+
+| `TERMINAL_BACKENDS` | Targets instantiated | Expected behavior |
+|---|---|---|
+| unset or `tmux` | local default tmux server | Current behavior and rollback path |
+| `herdr` | ordered `HERDR_SESSIONS`, defaulting to `default` | Only validated Herdr agents are published |
+| `tmux,herdr` | tmux plus every configured Herdr session | Observations merge by process; one primary locator controls each agent |
+| any mode with one unavailable target | remaining healthy targets | Daemon continues; failed-target locators are preserved as unknown/dormant |
+
+#### Target startup and recovery states
+
+| Target state | Meaning | Startup/retry/publication behavior |
+|---|---|---|
+| `disabled` | Backend omitted from configuration | No instance or probe; persisted locators remain dormant unless another locator is healthy |
+| `available` | Binary/protocol and target probe succeed | Participate in reconciliation and control |
+| `unavailable` | Valid configured target is absent, stopped, or times out | Daemon starts degraded, retries on the normal interval, preserves locators as `unknown`, and never auto-starts the target |
+| `incompatible` | Required backend binary is absent or its version/schema/protocol is unsupported | Do not publish/control through that target; show actionable status and retry only after binary/config change |
+| `misconfigured` | Backend list/session grammar is invalid or two configured names resolve to one endpoint | Fail startup before migration publication or hook-snapshot replacement |
+
+If no structurally usable backend remains because every enabled binary is missing/incompatible, startup fails non-zero. A structurally compatible Herdr-only configuration with all sessions temporarily stopped starts degraded and waits for recovery. In mixed mode, any healthy backend keeps the daemon operational.
+
+`HERDR_SESSIONS` is an ordered comma-separated list of validated Herdr names. Whitespace is trimmed; empty tokens and duplicate names are errors; unset means `default`. A valid but not-yet-created/stopped name is `unavailable`, not fatal. Resolution uses authenticated canonical socket endpoints to reject two names that alias one live endpoint while stable persisted identity remains scoped to the configured session name. `TERMINAL_RECONCILE_INTERVAL_MS` preserves the current 5,000 ms default. U1 benchmarks against that fixed value and records a measured safe minimum; U3 rejects configured intervals below the U1 bound rather than allowing overlapping probes.
+
+### Registry and Reconciliation Rules
+
+1. `runtimeIdentityKey` is `tmux:<paneId>` for legacy tmux placement and `herdr:<endpointId>:<terminalId>` for Herdr placement.
+2. `runtimeRouteKey` includes backend and endpoint plus current pane ID. Route keys are indexes/hints, never durable agent identity.
+3. `agentProcessKey` is `(engine, pid, startMarker)` and is the cross-backend registry identity. It drives deduplication, suppression, and replacement detection.
+4. A cycle resolves the complete observation graph before mutating the registry. All observations with the same process key merge into one agent with one or more locators. The closest terminal root is primary; ties use `TERMINAL_BACKENDS` order, then `HERDR_SESSIONS` order for Herdr locators, then verified hook context.
+5. A matching locator + process refreshes the agent and may update Herdr’s current route. If the locator now maps to process B while process A remains live elsewhere, the atomic delta detaches it from A, preserves A, and creates/adopts B; replacement of A occurs only when A has no surviving process observation.
+6. A matching process at a moved Herdr route updates only that locator without changing `agentId` or primary-route state unless the route ranking changes.
+7. A successful observation of no supported process advances the two-miss rule for that locator. The agent remains active while another locator is healthy; failed/ambiguous observations do not advance misses.
+8. Agents with no currently alive locator are dormant and excluded from active selectors/outbound turn flow. Re-enabling or target recovery runs normal process + locator validation before publication; one alive locator keeps a multi-locator agent active.
+
+### System-Wide Impact
+
+| Surface | Change | Primary risk | Guardrail |
+|---|---|---|---|
+| Registry | Locator array, process index, and route indexes | Agent orphaning or collision | Backward-read/additive-write migration fixtures; endpoint collision tests |
+| Discovery | Neutral panes + composite reconciliation | Cross-backend eviction, duplicate tiles, or double control | One shared `ps`; process-key merge; deterministic primary route; per-endpoint accounting |
+| Input | Outcome + dispatch-evidence actions | Duplicate or swallowed prompts | Real byte fixture; failover only before proven dispatch |
+| Capture/control | Backend-neutral capture | Picker/parser drift | Re-recorded ANSI fixtures per engine |
+| Hooks | Dual terminal hints | Spoofed endpoint or phantom agent | Configured-endpoint allowlist + process verification |
+| Offline hook | New registry, Herdr probe, and persisted resolved-config snapshot | Divergence from daemon allowlist | Versioned atomic snapshot; shared fixture/lock/migration tests |
+| One-shots | Central env scrub | Recap becomes top-level agent | Spawn-env assertions for every engine worker |
+| Wire/status | Optional terminal metadata | Client compatibility | Additive fields; legacy tmux field only for tmux |
+| Updates | Fork binary vs upstream updater | Feature silently disappears | Disable or fork-own manifest until upstream merge |
+
+### Risks and Mitigations
+
+- **High — Input ambiguity after transport timeout.** The server may execute an input request before the CLI response is lost. Mitigate with outcome + dispatch evidence, transcript/capture observation, no automatic full-message replay, and the U1 exact-once fault test.
+- **High — Registry collision or lost update during migration.** Herdr routes repeat across sessions, tmux pane IDs recycle, and daemon/offline-hook processes can write concurrently. Use one shared lock and operation-based read–validate–merge–fsync–rename transaction, schema/invariant validation, boot-ID invalidation, and crash/concurrency fixtures; never overwrite malformed input with an empty registry.
+- **High — One nested process observed through both backends.** Independent per-backend registration can create two tiles and submit twice. Merge observations by process identity before registry mutation, retain all validated locators, and select one primary route by ancestor distance with deterministic tie-breaks.
+- **High — Hook spoofing or duplication after pane move.** Loopback reachability and a claimed PID are not authentication, and child environment is fixed at process launch. Authenticate every mutating hook request, bind events to registered process/session identity, resolve stale Herdr routes through the configured backend and process tree, and never key registration solely on hook pane ID.
+- **High — False death from partial outage.** Preserve current agents and miss counters whenever inventory, process table, or protocol probing fails.
+- **Medium — Alternate-screen capture gaps.** Exercise each supported engine in a real Herdr pane; allow a parser-specific capture source only with a fixture and retain conservative “busy/unavailable” behavior on incomplete capture.
+- **Medium — Offline hook drift.** `notify.mjs` cannot import the TypeScript backend. Keep its surface minimal, run the same legacy/new registry and secure-state fixtures through both implementations, and fail closed when Herdr or state-file ownership cannot be verified.
+- **Medium — Upstream churn.** Refresh `origin/main` before U1 and before each PR slice. Avoid long-lived rename-only diffs; land neutral interfaces with tmux behavior first.
+- **Medium — Herdr protocol drift.** Pin the supported protocol range, negotiate on every connect, and distinguish incompatible from temporarily unavailable.
+
+### Assumptions
+
+- Herdr 0.8.x continues to expose `terminal_id`, endpoint socket paths, pane process info, ANSI reads, text/key input, named sessions, and protocol metadata as verified on 2026-08-15.
+- tmux remains installed only when the tmux backend is enabled.
+- Engine transcript storage and normalizers remain independent of the terminal backend.
+- Initial Herdr support targets local Linux/macOS named sessions. Remote and Windows transports require separate evidence and plans.
+- The upstream issue accepts additive registry evolution and a neutral adapter boundary before full implementation begins.
+
+### Open Questions
+
+No launch-blocking product or architecture question remains. The following are implementation-gated and have explicit defaults:
+
+- **Deferred OQ1 — Herdr submission primitive:** U1 chooses `pane.send_input` or the equivalent verified submission method. Default: one request containing bracketed-paste text and one Enter; stop if exact-once cannot be proven.
+- **Deferred OQ2 — Event subscription timing:** Polling/fresh snapshots are required for correctness. Default: add move/output events only after polling parity is green; events remain hints.
+- **Deferred OQ3 — Legacy wire removal:** Default: retain `tmuxPane`/`TMUX_FAILED` compatibility for this release and propose removal separately with coordinated client changes.
+
+---
+
+## Implementation Units
+
+### U1. Upstream issue and vertical Herdr feasibility gate
+
+**Outcome:** Herdr’s direct socket API is proven against real isolated named sessions, the upstream issue draft contains the architecture and evidence, and every low-level behavior that can invalidate the design is resolved before broad refactoring.
+
+**Files:**
+
+- `docs/plans/2026-08-15-001-feat-selectable-tmux-herdr-backends-plan.md`
+- `cli/src/lib/herdrBackend.real.spec.ts` (new spike/real test; finalized in U5/U9)
+- `cli/package.json`
+- recorded deterministic fixtures under `cli/src/lib/__fixtures__/herdr/` (new)
+
+**Work:**
+
+1. Refresh `origin/main`; update path references if upstream moved the touched modules.
+2. Draft the issue from R1–R16 and KTD1–KTD15, but do not publish it without owner approval. Keep implementation local; before any upstream landing, attach U1/U9 evidence and obtain maintainer direction.
+3. Pin Herdr binary version, schema version, and protocol from the same installed binary used by the test.
+4. In two uniquely named Herdr sessions, prove session resolution, canonical endpoint separation, endpoint + pane → `terminal_id`, shell PID, cwd, title, current pane route, and route change after a cross-workspace move. Record whether old pane IDs remain aliases and for how long; caller-PID verification, not alias permanence, is the production fallback.
+5. Prototype the typed direct socket API client and prove literal typing, logical keys, ANSI `recent_unwrapped` capture, and exact-once-aware short/multiline/~28 KB submission with a deterministic PTY fixture. Confirm prompt bytes travel only in memory and the local API payload, never argv, environment, or logs. Create the stable opt-in `npm run test:herdr-real` command here so every later unit reruns the same gate.
+6. Capture representative real Herdr output available in the isolated environment and run applicable existing idle/question/profile parsers against it. Build the durable fixture-ingestion path now. Missing proprietary engine credentials or binaries do not block U2–U8; the complete supported-engine capture/control matrix remains a U9 release gate and must be reported honestly.
+7. Launch a representative supported engine in tmux-inside-Herdr and Herdr-inside-tmux. Record both backend inventories plus the shared `ps` snapshot and prove whether one process yields two validated locators and deterministic one-route control; if real topology falsifies multi-locator ancestry assumptions, revise KTD7/KTD8 before U2.
+8. Benchmark direct-API target inventory/process resolution at 1, 10, and 50 panes against the fixed 5,000 ms v1 interval. The p95 probe must finish within 2,500 ms with no overlapping cycles; record the measured safe minimum interval for U3.
+9. Fault or time out the Herdr API transport before connect, before write, after write, and while awaiting the response; record whether execution is knowable and map each phase to `not_started`, `rejected`, or `possibly_executed` for U7.
+10. Stop/timeout the Herdr server and prove the probe can distinguish unavailable from a successful empty inventory.
+11. Prototype the daemon-down offline verification path under the shortest installed five-second command-hook timeout. Use one monotonic 4,500 ms internal deadline: at most 500 ms for loopback POST failure detection, 2,000 ms combined for endpoint/process verification, 1,500 ms for lock + durable commit, and 500 ms exit reserve. If the remaining budget cannot safely finish the next phase, skip registration before mutation.
+
+**Tests:**
+
+- `npm run test:herdr-real` exists, is opt-in, uses uniquely named sessions, and cleans up on success/failure.
+- Fixtures contain observed output from the real binary, not hand-invented schema examples.
+
+**Acceptance:** The low-level prerequisites behind AE3–AE8 are proven against the direct API: endpoint namespacing, protocol/schema negotiation, stable terminal identity across moves, real nested-topology behavior, exact-once-aware input without argv exposure, representative ANSI capture, and unavailable-vs-empty classification. `npm run test:herdr-real` is the durable executable gate. A failure of those transport/identity/input conditions pauses U2–U9; unavailable third-party engine credentials defer only the corresponding U9 release evidence.
+
+**Dependencies:** None. The direct-API transport, identity, input, and availability gates must pass before U2–U9 proceed locally. Owner-approved issue publication and maintainer direction are required before U2–U9 land upstream, not before local implementation.
+
+### U2. Define terminal contracts and wrap tmux without behavior change
+
+**Outcome:** Every terminal operation has a backend-neutral type and tmux is the first conforming adapter with unchanged real behavior.
+
+**Files:**
+
+- `cli/src/lib/terminalTypes.ts` (new; no registry/backend imports)
+- `cli/src/lib/terminalBackend.ts` (new; imports only terminal types)
+- `cli/src/lib/terminalRuntime.ts` (new keying/ranking helpers)
+- `cli/src/lib/tmux.ts`
+- `cli/src/lib/tmux.spec.ts`
+- `cli/src/lib/terminalBackend.spec.ts` (new shared contract tests)
+
+**Work:**
+
+1. Define `TerminalRuntimeRef`, `TerminalPaneSnapshot`, canonical key helpers, logical key vocabulary, capture options/results, `RuntimeCheck`, and outcome + dispatch-evidence `TerminalActionResult` in the acyclic type/port boundary.
+2. Implement `TmuxBackend` as a thin wrapper over current list/PID/title/input/key/capture operations. Keep create/kill helpers test-only rather than widening the production backend port.
+3. Preserve the short-input fast path, named-buffer long-input path, settle delay, ANSI capture flags, process timeout semantics, and key names.
+4. Move generic process parsing/scoring helpers out of tmux naming only when required by U3; avoid a drive-by rewrite.
+5. Add a fake backend implementing the contract for consumer tests.
+
+**Tests:**
+
+- Characterize success, definitive failure, and ambiguous timeout for every operation.
+- Run existing `tmux.spec.ts` and `npm run test:tmux-real` unchanged or with only adapter-aware assertions.
+
+**Acceptance:** AE1 passes at the adapter level; no consumer outside the adapter needs to know the tmux executable or `%N` validation syntax.
+
+**Dependencies:** U1 complete.
+
+### U3. Migrate configuration and registry identity safely
+
+**Outcome:** Configuration selects one or more backends, and persisted agents use the runtime union without losing current tmux identities.
+
+**Files:**
+
+- `cli/src/config/env.ts`
+- `cli/src/config/env.spec.ts` (new parser-focused tests)
+- `cli/src/lib/registry.ts`
+- `cli/src/lib/registry.spec.ts`
+- `cli/src/lib/terminalConfigSnapshot.ts` (new; shared format/writer)
+- `cli/src/lib/terminalConfigSnapshot.spec.ts` (new)
+- `cli/.env.example`
+
+**Work:**
+
+1. Add strict `TERMINAL_BACKENDS` parsing with default `tmux`, stable order, and useful validation errors. Support exactly the default tmux server in v1.
+2. Add `HERDR_SESSIONS` (unset → `default`; trimmed strict comma list; reject empty/duplicate/invalid names), `HERDR_BIN`, and neutral `TERMINAL_RECONCILE_INTERVAL_MS` with the existing 5,000 ms default and the measured U1 safe minimum; reject lower values. Accept `TMUX_REAP_INTERVAL_MS` as a documented one-release fallback with explicit precedence. U3 validates grammar only; U5 owns live target resolution and endpoint-alias rejection.
+3. Add authoritative `runtimes[]`, a process-identity index, route/placement indexes, and backend-aware lookup methods. Retain `tmuxPane` only as a serialized compatibility projection for tmux rows.
+4. Keep `registry.json` as a top-level array with row-scoped schema markers, then replace whole-memory-map saves with a cross-process transaction contract used by every writer: acquire the same lock path, re-read the latest bytes, reject unknown row variants/root corruption without writing, normalize/validate records, apply an idempotent operation, validate global invariants, write a same-directory temp with `0600` mode, fsync file, rename, fsync directory, then refresh the daemon’s in-memory view/revision. Require `ADAPTER_DATA_DIR` to be owned by the daemon UID and mode `0700` (or otherwise reject group/world-writable state); open and validate registry, lock, temp, backup, boot, credential, and config-snapshot artifacts with no-follow owner/type/mode checks. Hook mutation IDs derive from engine + event + session + verified process identity; scan batches are set-based deltas. The daemon implementation lives in TypeScript; dependency-free `notify.mjs` mirrors the protocol and must pass the same fixtures.
+5. Define invariants: unique `agentId` and process key; one owner per non-empty engine session; no duplicate placement per agent; unique validated route/placement ownership where the backend guarantees it; dormant agents have no primary; active `primaryRuntimeKey` references one retained locator; legacy `tmuxPane` is the deterministic projection. Only identical process records auto-merge; conflicts are quarantined/revalidated, never timestamp-won.
+6. Normalize valid legacy tmux records without discarding unrelated valid records. Preserve same-boot agents with no enabled/healthy locator while excluding them from active/public listings. A boot-ID change invalidates all process-owned agent records regardless of backend; retain independent name overrides but rediscover every process/locator. Test same-boot default-tmux restart/recycled `%N` and same-boot daemon restart.
+7. Before first schema rewrite, create one versioned rollback backup. Test the actual preceding loader/writer against a disposable mixed-array copy: tmux IDs/bindings must survive and Herdr-row loss must be detected as expected. Document code rollback as stop → archive current mixed state → install a legacy-readable tmux-only projection → start the old binary; the archived mixed state restores Herdr rows on forward recovery. Never replace a root-corrupt/unknown-version registry or save an empty map after load failure; diagnose and leave original bytes untouched. Clean/recover abandoned temp files deterministically.
+8. Define the versioned `terminal-config.json` schema plus an atomic writer/reader (mode `0600`, no credentials) under `ADAPTER_DATA_DIR`. Test it with supplied resolved-target fixtures, but do not publish live Herdr endpoints in U3; U5 owns resolution and publication. Missing/stale/unknown versions make Herdr offline registration fail closed.
+
+**Tests:**
+
+- Golden fixtures for legacy tmux, mixed top-level-array new-schema records, malformed individual records, corrupt/truncated/non-array root JSON, unknown row schema version, multiple locators, duplicate process/session/route owners, same Herdr pane across endpoints, same-boot and reboot behavior, disabled-backend preservation, actual preceding-loader/writer tmux survival plus expected Herdr-row discard on a disposable copy, mixed-state archive/forward restoration, terminal-config snapshot replacement/version/mode, and round-trip serialization. Assert failed load/migration leaves original bytes unchanged. Add permissive-directory, symlink, wrong-owner, lock/temp/backup mode, and no-follow artifact cases for both writers.
+- Cross-process tests interleave daemon/offline create/update/remove/migration operations, duplicate delivery after a lost response, crash points before/after fsync/rename, stale lock/temp recovery, and verify no committed registration is lost.
+- Config tests cover default, every supported mode, whitespace/empty/duplicate/invalid session names, unknown values, and old/new interval precedence. Live alias and absent-session cases belong to U5.
+- Assert same-boot `agentId`, session binding, name keys, timestamps, and process identity survive migration; reboot fixtures retain names but never reuse a process-owned `agentId` from terminal placement.
+
+**Acceptance:** AE1, AE4, and the persistence portion of AE5 pass.
+
+**Dependencies:** U2.
+
+### U4. Extract shared process discovery and composite reconciliation
+
+**Outcome:** One process-authoritative reconciler handles neutral pane snapshots from any number of backend instances without cross-backend failure or collision.
+
+**Files:**
+
+- `cli/src/lib/agentDiscovery.ts` (new shared process ownership and reconciler)
+- `cli/src/lib/agentDiscovery.spec.ts` (new)
+- `cli/src/lib/tmuxAgentDiscovery.ts`
+- `cli/src/lib/tmuxAgentDiscovery.spec.ts`
+- `cli/src/lib/tmuxAgentDiscovery.real.spec.ts`
+- `cli/src/lib/registry.ts`
+
+**Work:**
+
+1. Extract the pure process-tree ownership algorithm and shared `ps` snapshot from `tmuxAgentDiscovery.ts` without changing engine scoring.
+2. Adapt tmux pane inventory into neutral snapshots.
+3. Implement a coordinator that probes backend instances independently, captures one process snapshot, builds an immutable observation graph, and ranks locators by ancestor distance/configuration order/verified hook tie-break. Commit the resulting operation batch through the registry transaction against the latest on-disk revision so a daemon-down hook write that races the scan is merged, not overwritten.
+4. Make hints, ambiguity sets, miss counters, suppression keys, observed keys, and removal reasons backend/runtime-aware.
+5. Handle route moves as locator refreshes. When a locator changes from process A to B, detach/split it to B while preserving A through any other healthy locator; only replace A when A itself is no longer observed. Merge nested observations of the same process.
+6. Coalesce overlapping scans and preserve the two-confirmed-successful-miss rule without making outcomes dependent on backend completion order.
+
+**Tests:**
+
+- Re-run all process ownership fixtures.
+- Add mixed-backend, nested same-process deduplication in every probe order, deterministic primary-route selection, two-Herdr-endpoint collision, route-move, locator split where A remains live and B adopts one locator, process replacement, default-tmux restart/recycled-pane, one-endpoint-failure, process-table-failure, suppression, and ambiguity cases.
+
+**Acceptance:** AE3, AE4, AE5, AE6, and AE8 pass with fake inventories; real tmux behavior remains green.
+
+**Dependencies:** U2–U3.
+
+### U5. Implement the Herdr socket-API backend
+
+**Outcome:** A configured Herdr 0.8.x session conforms to `TerminalBackend` through typed, bounded direct socket-API calls without subprocess transport for pane control or implicit focused-pane state.
+
+**Files:**
+
+- `cli/src/lib/herdrBackend.ts` (new)
+- `cli/src/lib/herdrApiClient.ts` (new)
+- `cli/src/lib/herdrApiClient.spec.ts` (new)
+- `cli/src/lib/herdrBackend.spec.ts` (new)
+- `cli/src/lib/herdrBackend.real.spec.ts` (from U1)
+- `cli/src/lib/terminalConfigSnapshot.ts` and `.spec.ts` (schema/writer from U3; live publication here)
+- `cli/package.json`
+
+**Work:**
+
+1. Resolve the strict ordered `HERDR_SESSIONS` list with the non-sensitive `herdr session list --json` bootstrap; use the configured session name as stable endpoint namespace and reject two names resolving to one canonical socket. Validate socket/parent type, owner UID, permissions, no-follow behavior, and replacement before use. A valid absent/stopped name remains `unavailable` and is retried without auto-start. After successful initial resolution or recovery, atomically publish the complete resolved `terminal-config.json`; never replace the last valid snapshot with partial/invalid target data.
+2. Implement `HerdrApiClient` with Node built-ins over the named session’s local socket. Send one bounded newline-delimited JSON request with a unique request ID, parse one bounded structured response, enforce connect/write/read deadlines and aborts, and classify failure by dispatch phase. Keep request payloads, prompt text, credentials, and raw socket paths out of argv, environment, logs, and error strings.
+3. Perform `ping` capability/protocol negotiation on startup and after target recovery; validate responses against the pinned v0.8 protocol/schema contract, tolerate documented unknown fields, classify each target according to the startup-state table, and fail startup only for malformed config or when no structurally usable enabled backend remains.
+4. Map `session.snapshot`, `pane.list`/`pane.get`, and `pane.process_info` responses into neutral snapshots with `terminalId`, current `paneId`, shell PID, cwd, and title.
+5. Implement literal input with `pane.send_text`, logical keys/Enter with `pane.send_keys`, the U1-verified submission sequence, ANSI capture with `pane.read`, runtime validation inputs, and title/notification through explicit IDs. Never infer submission from text insertion alone.
+6. Fetch one fresh API snapshot per session for correctness and route moves. Keep persistent event subscriptions deferred until measured need; if later added, put them behind the same typed client and availability semantics rather than a second transport.
+7. Keep the Herdr CLI wrapper limited to session discovery, installed-version/schema diagnostics, and test-only isolated session creation/cleanup. Never use it for prompt-bearing pane control, expose general session lifecycle on the production backend, or auto-start/stop/move/close user-owned Herdr panes.
+
+**Tests:**
+
+- API-client contract: request IDs and framing, named-session targeting, absent/stopped/duplicate/aliased sessions, socket pre-creation/symlink swap/path replacement/wrong owner, optional peer mismatch where observable, resolved-snapshot publication/replacement, request/response size bounds, malformed/oversized JSON, structured server errors, timeout-before-connect/write, ambiguous timeout-after-write, abort, version/protocol mismatch, aggregate startup states, recovery, and unknown fields. Bootstrap CLI tests cover only session resolution/version discovery, a minimal secret-free environment, bounded output, and malformed discovery JSON.
+- Backend mapping: duplicate pane routes across endpoints, moved route, missing process info, alternate capture sources, logical-key validation, and notification failure.
+- Run the U1 real-Herdr evidence suite.
+
+**Acceptance:** AE2, AE4, AE5, AE7, and AE8 pass at backend level.
+
+**Dependencies:** U1–U4.
+
+### U6. Make online/offline hooks and one-shot isolation backend-neutral
+
+**Outcome:** Every supported engine can register from tmux or a configured Herdr session, and no ephemeral worker self-registers.
+
+**Files:**
+
+- `cli/src/lib/terminalContext.ts` (new env parsing/scrubbing helper)
+- `cli/src/lib/terminalContext.spec.ts` (new)
+- `cli/src/lib/terminalConfigSnapshot.ts` (from U3)
+- `cli/src/hookServer.ts`
+- `cli/src/hookServer.spec.ts`
+- `cli/hook/notify.mjs`
+- `cli/src/hookNotify.spec.ts`
+- `cli/src/lib/hooks.ts`
+- `cli/src/lib/hooks.spec.ts`
+- `cli/src/lib/oneshot.ts`
+- `cli/src/lib/grokOneShot.spec.ts`
+- `cli/src/lib/kiloOneShot.spec.ts`
+- `cli/src/lib/discoveryScripts.spec.ts`
+
+**Work:**
+
+1. Generate or load a rotatable per-install high-entropy hook credential in the secure state directory. Make it available to generated hooks/plugins through a mode-`0600` file or equivalent non-argv/non-log channel, and require constant-time verification on every mutating hook route before parsing expensive payload content.
+2. Parse tmux and Herdr environment into a typed list of runtime hints plus a caller-PID hint appropriate to the hook shape. When both contexts are inherited, emit both and let scanner-confirmed ownership plus primary-route ranking resolve them; never guess by environment-variable order.
+3. Update generated OpenCode/Kilo/Pi/Amp and other embedded plugin sources to authenticate and post the hints/caller PID while preserving plugin-version drift warnings and foreign hook blocks. Define one strict ingress schema for every hook endpoint: bounded body bytes, hint count and string lengths, known backends/fields only, and early termination on overflow.
+4. Normalize legacy `tmuxPane` and new runtime-hint arrays in `hookServer`; verify caller PID/ancestry through the shared process snapshot, bind every session/turn/tool/end mutation to the registered process identity, resolve Herdr hints only through configured authenticated instances, and reject stale/ambiguous hints without deterministic process correlation.
+5. Port offline `fallbackRegister` to the new registry schema. Read the atomically replaced versioned `terminal-config.json`, match authenticated canonical configured endpoints, verify `PPID`/caller ancestry, then commit through the offline implementation of the same idempotent registry transaction contract. Fail closed for missing/stale snapshots or unconfigured/unsafe Herdr sockets; preserve legacy tmux fallback.
+6. Enforce one monotonic 4,500 ms end-to-end offline deadline beneath the installed five-second hook timeout: 500 ms maximum loopback POST, 2,000 ms combined endpoint/process verification, 1,500 ms lock + durable commit, and 500 ms exit reserve. Every phase consumes the shared remaining budget; if verification or lock/commit cannot finish safely, abort before mutation rather than timing out mid-write.
+7. Keep engine-specific subagent filters, transcript validation, delayed transcript handling, session stealing/rotation, and daemon-down fail-closed behavior intact.
+8. Centralize terminal-context scrubbing and apply it to every one-shot spawn without removing unrelated engine-specific safety variables.
+
+**Tests:**
+
+- Online and offline registration matrices for tmux, Herdr, authenticated legacy payload, nested dual context, stale moved pane with two same-engine processes, absent/old config snapshot, configured/unconfigured/unsafe sockets, spoofed/wrong caller PID, child/subagent, daemon unavailable, config-change atomicity, and concurrent registry writers.
+- Hook-ingress tests cover missing/wrong/rotated/replayed credentials, a local client claiming another live engine PID, forged session-end/turn/tool events, oversized and chunked-overflow bodies, excessive hints, overlong fields, malformed types, and unknown fields.
+- Real five-second command-hook tests for tmux and Herdr daemon-down fallback cover fast success, endpoint timeout, process timeout, lock contention, commit latency, and safe pre-mutation budget exhaustion; the hook always exits before its host timeout.
+- Spawn-env assertions verify every tmux/Herdr context variable is absent for every one-shot engine.
+
+**Acceptance:** AE2, AE5, AE9, and AE10 pass; a hook can never create an agent without scanner-confirmed process ownership.
+
+**Dependencies:** U3–U5.
+
+### U7. Route input, questions, profile control, capture, and deletion through runtime locators
+
+**Outcome:** All interactive behavior dispatches through the selected backend and preserves engine-specific safety state machines.
+
+**Files:**
+
+- `cli/src/lib/sessionInput.ts`
+- `cli/src/lib/sessionInput.spec.ts`
+- `cli/src/lib/askQuestion.ts`
+- `cli/src/lib/askQuestion.spec.ts`
+- `cli/src/lib/runtimeProfileController.ts`
+- `cli/src/lib/runtimeProfileController.spec.ts`
+- `cli/src/lib/deleteAgentFallback.ts`
+- `cli/src/lib/deleteAgentFallback.spec.ts`
+- relevant recorded interaction fixtures under `cli/src/engines/**/__fixtures__/` or a new shared fixture directory
+
+**Work:**
+
+1. Change dependency seams from pane strings/booleans to a registry-owned primary `TerminalRuntimeRef` plus action results carrying outcome and dispatch evidence; consumers never choose locators themselves.
+2. Preserve queue bounds, control locks, turn-open tracking, fingerprint observation, per-engine settle windows, Cursor composer clearing, and bounded Enter retry logic.
+3. Permit side-effecting failover only for `not_started` or explicit `rejected` outcomes. `possibly_executed` requires transcript/capture observation and never triggers blind full-message replay.
+4. Give every multi-step question/profile interaction an agent-scoped control lease that pins locator identity + route generation. Validate before each phase; a route refresh for the same locator may continue, but a primary-locator switch releases/restarts the interaction instead of splitting it across terminals.
+5. Map Harness logical keys to each backend in the adapter, not inside engine-specific controllers.
+6. Feed real Herdr ANSI captures into existing picker/question/idle parsers. Adjust backend capture selection before changing parsers; change an engine parser only when a real fixture proves backend-independent semantics were missing.
+7. Keep deletion process-only. Revalidate `(pid, executable, startMarker)` immediately before SIGTERM and again immediately before any SIGKILL escalation; use a stable process handle such as pidfd where supported and fail closed on `unknown` or identity change elsewhere. Locator health is supporting evidence, not a prerequisite that could route deletion elsewhere.
+
+**Tests:**
+
+- Run existing controller suites against fake tmux and fake Herdr backends.
+- Add every dispatch-evidence branch, nested-locator primary selection, safe pre-dispatch failover, no post-dispatch double-send, pinned-control behavior across route refresh/primary change, stale route refresh, capture unavailable, moved pane during control, process replacement before deletion, and PID replacement between SIGTERM and SIGKILL.
+- Re-record Herdr fixtures for each supported engine’s available question/profile interactions.
+
+**Acceptance:** AE3, AE5, AE6, AE7, and R12/R13 pass; no consumer invokes tmux/Herdr directly.
+
+**Dependencies:** U2, U4–U6.
+
+### U8. Wire the daemon, status, and compatibility surfaces
+
+**Outcome:** The production daemon builds configured backends, publishes only verified active agents, and exposes additive backend metadata without breaking clients.
+
+**Files:**
+
+- `cli/src/cli.ts`
+- `cli/src/backendSocket.ts`
+- `cli/src/backendSocket.spec.ts`
+- `cli/src/webui.ts`
+- `cli/src/lib/askQuestion.ts`
+- `cli/src/config/env.ts`
+- `cli/src/lib/selfUpdate.ts` and `cli/src/lib/selfUpdate.spec.ts` only if fork-update safety needs code rather than documentation
+
+**Work:**
+
+1. Build `TmuxBackend` and one `HerdrBackend` per configured session; inject the coordinator into discovery, input, questions, profiles, titles, validation, and fallback message dispatch.
+2. Remove production direct imports of tmux operations outside the tmux adapter.
+3. Add one active/dormant lifecycle coordinator. On the last healthy locator becoming disabled/unknown: mark the agent dormant, reject queued input with the existing unavailable error, release control leases, pause outward turn/control events, and emit the existing client convergence deletion/offline event while preserving registry/name/session/transcript state. Keep transcript observation/cursor state so recovery can resynchronize without replaying stale control actions.
+4. On recovery: validate process + locator, reattach/resume transcript observation, publish the same `agentId` with current normalized state/recap, then re-enable input/control. An agent with any other healthy locator never enters the dormant transition.
+5. Update local status to report disabled/available/unavailable/incompatible targets, dormant-agent counts, and configured session counts.
+6. Add optional neutral terminal metadata. Populate legacy `tmuxPane` only for actual tmux agents and retain existing client error codes/events through aliases.
+7. Ensure backend recovery triggers a full snapshot and atomic reconciliation before dormant agents are republished.
+8. Document or enforce fork-safe self-update behavior until upstream merge.
+
+**Tests:**
+
+- Daemon composition for default tmux, Herdr-only stopped/available, both, nested same-process visibility, one-of-two target outage, all-transiently-unavailable degraded mode, all-structurally-incompatible fatal startup, disabled-backend dormant records, and recovery.
+- Live active→dormant→active convergence with a queued message and open control lease: one client removal/offline event, no delayed dispatch, same `agentId` on recovery, and no turn-event leak while dormant.
+- Backend-socket project snapshots remain compatible for tmux and contain no false `tmuxPane` for Herdr.
+
+**Acceptance:** AE1–AE4 and AE8 pass at daemon level; default startup remains tmux-only.
+
+**Dependencies:** U3–U7.
+
+### U9. Full matrix, documentation, rollout, and upstream delivery
+
+**Outcome:** Both backends are reproducibly verified, documented, and ready for upstream review without a permanent private divergence.
+
+**Files:**
+
+- `cli/package.json`
+- `cli/README.md`
+- root `README.md`
+- `CONTRIBUTING.md` if maintainers want the adapter contract clarified
+- `CHANGELOG.md`
+- CI workflow files under `.github/workflows/` as approved upstream
+- `cli/src/lib/herdrBackend.real.spec.ts`
+- `cli/src/lib/tmuxAgentDiscovery.real.spec.ts`
+
+**Work:**
+
+1. Harden the U1-created `npm run test:herdr-real` gate with timeout-bounded cleanup, stale-fixture recovery, deterministic isolation, and clear skip diagnostics when Herdr is absent.
+2. Run all supported engine discovery signatures under both backends. For Herdr, perform manual/recorded smoke tests for one prompt, capture-driven controls where applicable, session rotation/resume, and process-only deletion.
+3. Test same-route cross-session collision, duplicate canonical target rejection, workspace move with stale hook + two same-engine processes, daemon restart, Herdr server recovery, config disable/re-enable, active/dormant client convergence, protocol mismatch, default-tmux same-boot server restart, and recap isolation.
+4. Document configuration examples, supported Herdr/protocol range, named-session behavior, failure semantics, migration, rollback, and updater safety.
+5. Split the implementation into upstream-reviewable PR slices: neutral contract/tmux extraction; identity/config/discovery; Herdr backend; hooks/controls; matrix/docs. Rebase each slice onto current upstream and keep behavior-preserving commits separate from Herdr additions.
+6. Remove temporary spike-only code or convert it into durable real tests before merge.
+
+**Tests:**
+
+```bash
+cd cli
+npm install
+npm run typecheck
+npm test
+npm run build
+npm run bundle
+npm run test:tmux-real
+npm run test:herdr-real
+```
+
+**Acceptance:** All Success Criteria and Definition of Done checks pass; the issue/PR contains real-Herdr evidence and no claim relies only on mocks.
+
+**Dependencies:** U1–U8.
+
+---
+
+## Verification Contract
+
+### Required Automated Gates
+
+- `npm run typecheck` after every unit.
+- `npm test` after every unit; no test requires a real multiplexer unless explicitly gated.
+- `npm run build` and `npm run bundle` before any distributable/fork build.
+- `npm run test:tmux-real` after U2, U4, U8, and U9.
+- `npm run test:herdr-real` after U1, U5, U7, U8, and U9.
+
+### Contract Test Matrix
+
+| Scenario | Unit/fake | Real tmux | Real Herdr |
+|---|---:|---:|---:|
+| Inventory, cwd, root PID, title | Yes | Yes | Yes |
+| Literal text without submit | Yes | Yes | Yes |
+| Short, multiline, ~28 KB submit | Yes | Yes | Yes |
+| Prompt absent from argv/logs | Yes | N/A | Yes |
+| Dispatch-evidence failover branches | Yes | Yes | Yes |
+| Logical keys | Yes | Yes | Yes |
+| ANSI/wrap-joined capture | Yes | Yes | Yes |
+| `alive/gone/unknown` validation | Yes | Yes | Yes |
+| Endpoint outage and recovery | Yes | N/A | Yes |
+| Same pane route across endpoints | Yes | N/A | Yes |
+| Same process visible through nested backends | Yes | Yes | Yes |
+| Locator split: A survives, B adopts route | Yes | Yes | Yes |
+| Pane move with stable agent | Yes | N/A | Yes |
+| Process replacement in same terminal | Yes | Yes | Yes |
+| Legacy registry/hook migration | Yes | Smoke | Smoke |
+| Cross-process registry transaction/crash recovery | Yes | Smoke | Smoke |
+| Stale hook + verified caller PID | Yes | Yes | Yes |
+| Hook authentication, event binding, and ingress bounds | Yes | Smoke | Smoke |
+| Secure state/socket ownership, mode, no-follow, and best-effort peer checks | Yes | N/A | Yes |
+| Parser-level capture parity for every supported engine | Fixtures | N/A | Yes |
+| Recap worker isolation | Yes | Yes | Yes |
+
+### Manual Supported-Engine Matrix
+
+For Claude Code, Codex, Cursor, OpenCode, Pi, Hermes, Command Code, Devin, Muse, Amp, Kilo, and Grok:
+
+1. Discover a fresh top-level process.
+2. Bind its engine session/transcript through the real hook/store path.
+3. Submit a prompt and observe the actual turn start/answer.
+4. Exercise one question/profile picker when the engine exposes one.
+5. Rotate or resume the engine session where supported and preserve the same process agent semantics.
+6. Delete the agent and verify only the engine process is signalled; the user shell/pane survives.
+7. Run one recap and verify no phantom agent appears.
+
+Record engine/version, backend/session, capture source, and exceptions. A missing engine interaction is a documented unsupported engine capability, not silently skipped terminal parity.
+
+### Failure and Recovery Tests
+
+- Kill/restart a Herdr server during inventory, capture, and input requests.
+- Delay a Herdr response past timeout both before and after PTY dispatch.
+- Make `ps` time out while both backends are healthy.
+- Move a pane while a hook is firing and while a profile control owns the input lock.
+- Fire a stale moved-pane hook while two same-engine processes exist; only the verified caller process may bind.
+- Launch Herdr inside tmux and tmux inside Herdr; reverse probe completion order and verify one agent, deterministic primary locator, and one terminal action.
+- Reassign one locator from process A to process B while A remains visible through another locator; verify an atomic split, not replacement of A.
+- Disable Herdr with live persisted records, restart Harness, then re-enable and reconcile.
+- Feed malformed, oversized, and protocol-incompatible Herdr CLI/API responses.
+- Forge loopback hooks with missing/wrong/rotated credentials, another engine’s live PID, forged lifecycle events, and oversized/chunked bodies; every case fails before registry or controller mutation.
+- Replace or symlink state/socket artifacts and change ownership/modes between resolution and use; online and offline paths fail closed without leaking prompt bytes.
+- Reuse a PID between SIGTERM and SIGKILL; the replacement process is never signalled.
+- Interleave daemon and offline hook writes, duplicate a hook after a lost HTTP response, and fault every temp/fsync/rename boundary; no committed registration may be lost and corrupt input must remain byte-identical.
+- Change the machine boot ID fixture and confirm no tmux or Herdr placement reuses a prior process-owned `agentId`; name overrides may survive independently.
+
+### Rollback
+
+- Configuration rollback is `TERMINAL_BACKENDS=tmux`; tmux remains the default and its adapter/real suite are never removed.
+- Disabling Herdr must preserve Herdr locators; agents with a healthy tmux locator remain active and agents with no healthy locator become dormant without data loss.
+- Before upstream merge, fork builds use a fork-owned updater manifest or disable self-update.
+- If a release must revert code, stop the new daemon, archive the current mixed top-level array, replace `registry.json` with a generated legacy-readable tmux-only projection, and only then start the preceding binary. Do not rely on it understanding or preserving Herdr rows. Retain the pre-migration backup plus the rollback-time mixed archive until forward restoration fixtures pass.
+- If migration/load validation fails, leave the original registry and rollback backup untouched, publish no unvalidated agents, and require operator correction rather than writing an empty registry.
+
+---
+
+## Definition of Done
+
+### Product
+
+- [ ] `TERMINAL_BACKENDS` supports tmux, Herdr, or both; default tmux behavior is unchanged.
+- [ ] Configured Herdr named sessions are endpoint-scoped and collision-safe.
+- [ ] Workspace moves preserve agents; process replacement does not.
+- [ ] Every supported engine passes the required backend smoke or has an explicit evidence-backed limitation accepted upstream.
+- [ ] Web/device identity and transcript/provider behavior remain compatible.
+
+### Architecture
+
+- [ ] All daemon-side terminal operations flow through `TerminalBackend`/the coordinator; dependency-free `notify.mjs` is the sole bounded offline exception and stays fixture-locked to the adapter contracts.
+- [ ] Registry, hook, discovery, and controller APIs use typed runtime locators, not a generic `tmuxPane` string.
+- [ ] One process visible through multiple backends produces one agent with deterministic single-route control.
+- [ ] Process identity remains authoritative and all probe/action failures preserve `unknown` semantics.
+- [ ] Side-effecting failover requires proof that dispatch did not start; multi-step controls use a locator-generation lease.
+- [ ] Herdr transport is bounded, protocol-checked, recovery-safe, and limited to configured endpoints.
+- [ ] Every mutating hook request is authenticated, bounded, and bound to a verified process/session identity.
+- [ ] State files and any direct Herdr socket transport enforce owner/mode/type/no-follow checks and peer identity where supported.
+- [ ] No agent deletion path closes a user-owned pane.
+
+### Migration and Safety
+
+- [ ] Legacy tmux registry and hook payloads migrate without changing public agent identity and remain readable by the rollback fixture.
+- [ ] Every registry writer uses the same lock/transaction/invariant contract; corrupt or unknown-version files are never overwritten.
+- [ ] A machine reboot invalidates every process-owned agent regardless of backend; placement alone never carries an `agentId`.
+- [ ] Disabled/unavailable locators are preserved; agents are dormant only when no enabled locator is healthy and are revalidated before publication.
+- [ ] One-shot workers strip all terminal context and create no phantom agents.
+- [ ] Ambiguous input completion cannot trigger blind message replay.
+- [ ] Fork self-update cannot silently replace the custom build with an upstream build lacking Herdr.
+
+### Verification and Delivery
+
+- [ ] Typecheck, unit tests, build, bundle, real-tmux, and real-Herdr commands pass with captured output.
+- [ ] Real Herdr evidence covers identity, move, collision, input, capture, outage, and recovery behavior.
+- [ ] The manual supported-engine matrix is attached to the upstream issue/PR.
+- [ ] Documentation describes configuration, migration, support range, failure semantics, and rollback.
+- [ ] Owner-approved upstream issue precedes the local evidence spike leaving its exploratory branch; U1 evidence and maintainer direction precede U2–U9 landing, and PR slices remain independently reviewable.
+- [ ] No launch-blocking open question remains.
+
+---
+
+## Appendix
+
+### Delivery Shape
+
+Recommended upstream sequence:
+
+1. Owner-approved issue with the proposed runtime schema and U1 evidence gates; attach completed U1 evidence and obtain maintainer direction.
+2. PR 1: terminal contract + behavior-preserving tmux adapter.
+3. PR 2: registry/config migration + shared discovery/reconciler.
+4. PR 3: Herdr socket-API client/backend transport + real suite.
+5. PR 4: authenticated hooks, input/control consumers, and status.
+6. PR 5: full matrix, documentation, rollout, and migration/rollback evidence.
+
+This sequence minimizes long-lived divergence in a fast-moving repository and gives maintainers reviewable points to accept or redirect before the highest-cost units.
+
+### Review Disposition
+
+The deep document review applied all twenty actionable coherence, feasibility, scope, security, and adversarial findings. The only deferred product suggestion is an opt-in preview release after U8 with a reduced initial engine subset; it does not alter the approved full-parity destination or block implementation readiness. No launch-blocking review question remains.
+
+### Effort Envelope
+
+- **Feasibility gate:** approximately 1–2 engineering weeks after expanding U1 to include the direct socket API, nested-multiplexer topologies, representative parser evidence, secure endpoint checks, and the real five-second offline-hook deadline.
+- **Narrow usable integration:** approximately 2–4 weeks after architecture acceptance.
+- **Full parity and release hardening:** approximately 37–58 engineering days (roughly 7–12 weeks), dominated by registry migration, hook parity, interaction fixtures, and the all-engine real matrix rather than the Herdr command translations themselves.