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): the harness CLI

0xken15f08176d5d5c5
diff --git a/Makefile b/Makefile
new file mode 100644
index 000000000..f9fd6b7e0
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,24 @@
+# Convenience targets for this repository.
+#
+# Pass extra arguments to a target's script via ARGS, e.g.:
+# make install-cli ARGS="--no-restart"
+# make upload-cli ARGS="0.1.0"
+
+.PHONY: cli-test install-cli upload-cli
+
+## cli-test: typecheck + run the CLI test suite.
+cli-test:
+ cd cli && npx tsc --noEmit && npx vitest run
+
+## install-cli: bundle the CLI from THIS working tree and install it into ~/.harness/cli — the local dev
+## loop, nothing published. Restarts the daemon on the new bytes. Self-update stays ON: the build is
+## labelled with the published version, which the release you are level with cannot outrank, so your bytes
+## survive until a NEWER version ships — then it lands. ARGS="--no-updates" to pin instead.
+install-cli:
+ bash cli/scripts/install-cli.sh $(ARGS)
+
+## upload-cli: bump version -> bundle -> publish the CLI. MAINTAINER ONLY — it writes to the release
+## bucket, so it needs an authenticated `gsutil` with write access (plus node/npm for the bundle step).
+## Running daemons pick the new version up within ~1 min.
+upload-cli:
+ bash cli/scripts/upload-cli.sh $(ARGS)
diff --git a/README.md b/README.md
index e716360d0..9adac1378 100644
--- a/README.md
+++ b/README.md
@@ -11,6 +11,7 @@ reference implementations, and the tools to check your own work against them.
| | |
|---|---|
+| [`cli/`](cli/README.md) | **`harness` CLI** — run the coding-agent CLIs you already use (Claude Code, Codex, Cursor, OpenCode, Pi, Hermes, Command Code, Devin) in tmux on your own machine and drive them from the web app or the device. End-to-end encrypted browser channel; the agents stay your processes with your credentials |
| [`provider/`](provider/README.md) | **Provider protocol** — make your own agent platform available on the Machine. Users connect it with a URL and a credential, then drive it from the web app or the device. A profile of [A2A](https://github.com/a2aagent/A2A) v1.0.1, with a reference implementation and a conformance runner |
More will be published here as it stabilises. Each section is self-contained: its own README, its own
diff --git a/cli/.env.example b/cli/.env.example
new file mode 100644
index 000000000..b2dd3cb98
--- /dev/null
+++ b/cli/.env.example
@@ -0,0 +1,41 @@
+# Backend the CLI dials (`/api/adapter-ws`). Local dev: ws://localhost:8090
+# BACKEND_WS_URL=wss://harness-api.autonomous.ai
+
+# Web app base URL — used to print the agent's chat link on `adapter start`. Local: http://localhost:3000
+# WEB_URL=https://harness.autonomous.ai
+
+# Pair token (the agent apiKey). Usually passed as `adapter start <token>` and
+# persisted to ${ADAPTER_DATA_DIR}/token; this env var overrides both.
+# ADAPTER_TOKEN=
+
+# Localhost port for the SessionStart/SessionEnd hook callbacks (hook/notify.mjs).
+# Fixed — if it's already in use the adapter reports it (another adapter is likely running).
+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.
+# 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.
+# TMUX_REAP_INTERVAL_MS=5000
+
+# Device turn-recap (commander summary card). Only runs while a device is connected.
+# CLAUDE_PATH=/usr/local/bin/claude # else resolved from PATH
+# CURSOR_PATH=/usr/local/bin/agent # else resolved from PATH
+# SUMMARY_MODEL=sonnet # Claude model for the recap one-shot
+# CODEX_SUMMARY_MODEL=gpt-5.5 # Codex model for recap
+# CURSOR_SUMMARY_MODEL=auto # Cursor model for recap
+# SUMMARY_EFFORT=low # shared Claude/Codex recap effort; Cursor effort is in model id
+# RECAP_FORCE=false # test: summarize even with no device connected
+
+# Self-update: the daemon polls this GCS manifest and swaps its own bundle in place.
+# ADAPTER_UPDATE_URL=https://storage.googleapis.com/s3-autonomous-upgrade-3/harness/cli/metadata.json
+# ADAPTER_UPDATE_KEY=cli
+# 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
diff --git a/cli/.gitignore b/cli/.gitignore
new file mode 100644
index 000000000..d369c55f9
--- /dev/null
+++ b/cli/.gitignore
@@ -0,0 +1,5 @@
+node_modules/
+dist/
+.env
+*.tsbuildinfo
+.DS_Store
diff --git a/cli/README.md b/cli/README.md
new file mode 100644
index 000000000..2eb6f02ad
--- /dev/null
+++ b/cli/README.md
@@ -0,0 +1,152 @@
+# harness
+
+**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 — Claude Code, Codex,
+Cursor, OpenCode, Pi, Hermes, Command Code, Devin — 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.
+
+- Every agent you open in a tmux pane shows up as an 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.
+
+## Install & run (`harness`)
+
+Prerequisite: **Node ≥ 20**. Create or open a remote machine in the web UI first, then copy its connect
+token into the installer:
+
+```bash
+curl -fsSL https://harness.autonomous.ai/install.sh | bash -s -- <token>
+```
+
+(The installer is a first-party hosted script; it downloads the published bundle and writes a
+`~/.local/bin/harness` launcher.)
+
+```bash
+harness join <token> # connect this computer to an existing machine
+harness join # reconnects with the saved credential
+harness status # is it running? shows pid + the chat link
+harness stop # stop the background adapter
+harness version # print the installed version
+harness unjoin # leave the machine (also removes it on the web) + clear the saved credential
+harness join -f # reconnect in the FOREGROUND (for a supervisor: pm2/systemd), logs to stdout
+```
+
+`join` prints a uniform info block (status, backend, pid, logs, and the **web chat link**
+`WEB_URL/machine/<agentId>`) then detaches; raw logs go to `${ADAPTER_DATA_DIR}/machine.log`. The
+credential is persisted to `${ADAPTER_DATA_DIR}/token`, so later runs are just `harness join`.
+
+The log is **capped at 10 MB**: the daemon checks the size every minute and, over the cap, rewrites the
+file with the newest half (the oldest lines are dropped, marked by a `[log] trimmed` line at the top).
+It's one file, not a rotation — 10 MB is the total on disk. A pre-rename `adapter.log` is adopted by
+rename on the first daemon start, so existing history carries over.
+
+The daemon **auto-updates itself** — it polls the release manifest (default every 60 s) and, on a newer
+build, downloads + verifies + swaps its own bundle and restarts when idle (with rollback on a bad
+build). See [`RELEASE.md`](RELEASE.md) for publishing and the update internals. Disable with
+`ADAPTER_UPDATE_DISABLE=true`.
+
+**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.
+
+**Install your build as `harness` (no release):** `bash scripts/install-cli.sh` bundles this
+working tree into `~/.harness/cli` — the same layout the public installer produces — and restarts the
+daemon on it, so `harness` on this computer means your code without publishing a version. Self-update is
+turned **off** in the launcher it writes (otherwise the published release overwrites your build within
+the minute). See [`RELEASE.md`](RELEASE.md#local-install-no-upload).
+
+## How it works
+
+```
+claude in tmux pane %3 ──writes──▶ ~/.claude/projects/**.jsonl
+ ▲ │ chokidar + byte-offset tail (only new lines)
+ │ sendToTmux (tmux send-keys) ▼ normalize → ServerEvents (+ derived turn lifecycle)
+ adapter CLI ◀────── down:{agentId} ── backend /api/adapter-ws ── up:{agentId} ──▶ web chat
+```
+
+- **The adapter emulates a node** for its agentId on the backend hub: it answers the hosted runtime RPCs
+ (`projects_list` = the registered tmux sessions, `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.
+- **Hooks** (auto-installed into `~/.claude/settings.json`, tmux-only via `$TMUX_PANE`):
+ `SessionStart` registers, `SessionEnd` unregisters, and **`UserPromptSubmit`** is a *catch* hook
+ that re-registers on every prompt so a session whose SessionStart was missed still appears. A
+ **pane reaper** drops sessions whose pane was hard-killed.
+- **Live session sync** to web + device: on register → `agent_synced` (web tab) + `agent_renamed`
+ (device tile add); on removal → `agent_deleted` (both). One session **per tmux pane**.
+- **SessionEnd removes the session** — the list reflects *running* claude sessions. Exiting claude
+ (Ctrl+D / Ctrl+C×2) ends the session and drops it from the list **even though the tmux pane is
+ still alive** (the user is back at the shell; claude isn't running). A later `claude --resume`
+ fires SessionStart and **adds it back**. The one exception is `/clear`, which rotates in place: a
+ fresh SessionStart for the same pane follows immediately and replaces the old session via
+ pane-dedup, so it's kept to avoid a flicker.
+- **Reaper backstop:** when SessionEnd never fires (hard kill, pane closed) the tmux reaper polls
+ `tmux list-panes` and drops sessions whose pane is gone.
+- **Mirror-all**: every JSONL line streams up — prompts typed directly in the terminal render in
+ the web identically to web-sent ones (`turn_started`/`turn_ended` are derived from the file).
+- **Compaction (`/compact` or auto-compact):** claude does an **in-file** compact — the JSONL keeps
+ the **same sessionId** and stays **append-only** (pre-compact history is preserved on disk), so the
+ byte-offset tail streams straight through with no dead file and no truncation re-read. The injected
+ `system`/`compact_boundary` line becomes a single `context_compact` UI hint; the big
+ `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`.
+
+## Config (`.env`, see `.env.example`)
+
+| var | default | meaning |
+|-----|---------|---------|
+| `BACKEND_WS_URL` | `wss://harness-api.autonomous.ai` | backend to dial (`/api/adapter-ws`) |
+| `ADAPTER_TOKEN` | *(unset)* | pair token override (else CLI arg / saved file) |
+| `PORT` | `18473` | localhost port for the hook callbacks (FIXED — if taken, the adapter reports it rather than picking a random port) |
+| `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 |
+| `TMUX_REAP_INTERVAL_MS` | `5000` | how often the reaper drops dead-pane sessions |
+| `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 |
+| `ADAPTER_UPDATE_CHECK_MS` | `60000` | how often (ms) to poll for a newer build (check also runs on start) |
+| `ADAPTER_UPDATE_DISABLE` | `false` | set `true` to turn self-update off |
+| `ADAPTER_CLI_DIR` | `~/.harness/cli` | install dir holding the `cli.js`/`notify.mjs` the updater swaps |
+
+## Device (hardware commander)
+
+A paired device mirrors the same agent. The adapter emits a curated **commander stream** from the
+same watched JSONL (via `sendCommander`, `commanderEligible`): `commander_event` cards —
+`processing` (busy), `tool` (name + arg + color), `todos` checklist, `summary`, `done` (clear busy).
+It answers the device's `projects_list` (tiles) and `project_recent` (last summary) RPCs; voice
+turns arrive as an injected `message` → `sendToTmux`. A device that joins **mid-turn** converges via
+a client-count signal (`__clients`) — the adapter re-emits the open turn's live state on join (no
+periodic heartbeat).
+
+The per-turn **summary/recap** matches the hosted runtime: on turn end, *only while a device is
+connected*, the adapter runs a disposable one-shot from the session's own CLI engine
+(`SUMMARY_MODEL`, `CODEX_SUMMARY_MODEL`, or `CURSOR_SUMMARY_MODEL`) → `recap ≤15 words\n\n
+body ≤200`, shows a `Summarizing…` indicator while it runs, persists it per session
+(`${ADAPTER_DATA_DIR}/summaries.json`), and returns it on `project_recent` at device boot. A newer
+turn aborts a stale recap.
+
+## v1 limitations
+
+- Permission / question prompts are answered **in your terminal** (claude runs interactively);
+ neither the web nor the device shows those modals for remote agents.
+- `new_chat` / `/compact` from the web are no-ops; `cancel` best-effort sends `C-c` to the pane.
+- **One computer per machine.** The first computer to connect claims the machine; a *different* computer that
+ tries to join the same machine is rejected (HTTP 409) and prints an info message ("already connected
+ from another computer") then stops — it keeps its token but does not take over. Enforced by a stable
+ per-computer id (`${ADAPTER_DATA_DIR}/computer-id`) sent as `?computer=` and a server-side ownership claim, so
+ the *same* machine reconnecting after a blip/restart always reclaims. Stop the adapter on the first
+ machine (or wait for its presence to expire, ~30s) to move the machine to another computer.
+- Projects are tmux sessions — **create / rename / delete are disabled** (web hides them; the
+ adapter rejects the RPCs with `UNSUPPORTED_ON_REMOTE`).
+- Device recap uses the same Claude, Codex, or Cursor CLI engine as the session
+ (device-gated, like the hosted runtime); no sub-agent rows.
diff --git a/cli/build-bundle.mjs b/cli/build-bundle.mjs
new file mode 100644
index 000000000..97019f32c
--- /dev/null
+++ b/cli/build-bundle.mjs
@@ -0,0 +1,42 @@
+/**
+ * Release build: bundle the whole CLI into ONE self-contained `dist/cli.js` (all deps are pure-JS, so
+ * a single artifact runs on every OS under the user's Node) + copy the standalone hook script.
+ *
+ * Version is baked in via esbuild `define(__ADAPTER_VERSION__)`, sourced from `ADAPTER_VERSION`
+ * (set by scripts/upload-cli.sh) else package.json — so the running binary's version EXACTLY
+ * equals the published manifest version (the self-updater compares them).
+ *
+ * `bufferutil`/`utf-8-validate` are ws's OPTIONAL native deps — mark external and provide a real
+ * `require` via the banner so ws's try/catch fallback works without them.
+ */
+import * as esbuild from 'esbuild'
+import { readFileSync, copyFileSync, rmSync } from 'fs'
+
+const version =
+ process.env.ADAPTER_VERSION ||
+ JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version
+
+// Start clean so no stale per-file `dist/*.js` / sourcemaps leak into the release artifact.
+rmSync('dist', { recursive: true, force: true })
+
+await esbuild.build({
+ entryPoints: ['src/cli.ts'],
+ outfile: 'dist/cli.js',
+ bundle: true,
+ platform: 'node',
+ format: 'esm',
+ target: 'node20',
+ external: ['bufferutil', 'utf-8-validate'],
+ define: { __ADAPTER_VERSION__: JSON.stringify(version) },
+ banner: {
+ js: 'import{createRequire as ___cr}from"module";const require=___cr(import.meta.url);',
+ },
+ sourcemap: false,
+ minify: true,
+ keepNames: true,
+ legalComments: 'eof',
+ logLevel: 'info',
+})
+
+copyFileSync('hook/notify.mjs', 'dist/notify.mjs')
+console.log(`✓ Bundled dist/cli.js (v${version}) + dist/notify.mjs`)
diff --git a/cli/build.mjs b/cli/build.mjs
new file mode 100644
index 000000000..5a82525d9
--- /dev/null
+++ b/cli/build.mjs
@@ -0,0 +1,44 @@
+import * as esbuild from 'esbuild'
+import { readdirSync, statSync, readFileSync } from 'fs'
+import { join } from 'path'
+
+// Bake the version in so `node dist/cli.js version` works in the dev/per-file build too (parity with
+// build-bundle.mjs). The bundle build overrides this from ADAPTER_VERSION at release time.
+const version = JSON.parse(readFileSync('package.json', 'utf8')).version
+
+function getAllTsFiles(dir, fileList = []) {
+ const files = readdirSync(dir)
+
+ files.forEach((file) => {
+ const filePath = join(dir, file)
+ if (statSync(filePath).isDirectory()) {
+ getAllTsFiles(filePath, fileList)
+ } else if (file.endsWith('.ts')) {
+ fileList.push(filePath)
+ }
+ })
+
+ return fileList
+}
+
+const entryPoints = getAllTsFiles('src')
+
+try {
+ await esbuild.build({
+ entryPoints,
+ outdir: 'dist',
+ bundle: false,
+ platform: 'node',
+ format: 'esm',
+ target: 'node20',
+ sourcemap: true,
+ outExtension: { '.js': '.js' },
+ define: { __ADAPTER_VERSION__: JSON.stringify(version) },
+ logLevel: 'info',
+ })
+
+ console.log('✓ Build completed successfully')
+} catch (error) {
+ console.error('✗ Build failed:', error)
+ process.exit(1)
+}
diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjs
new file mode 100644
index 000000000..a3e06f56a
--- /dev/null
+++ b/cli/hook/notify.mjs
@@ -0,0 +1,608 @@
+#!/usr/bin/env node
+/**
+ * Claude Code / Codex / Cursor session hook for machine-adapter.
+ *
+ * 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: tells the adapter to drop the session (panel disappears).
+ *
+ * Always exits 0 quickly and swallows every error, so it can never block or
+ * delay claude's session start/teardown.
+ */
+
+import http from 'node:http'
+import { execFile } from 'node:child_process'
+import {
+ closeSync,
+ mkdirSync,
+ openSync,
+ readFileSync,
+ readSync,
+ realpathSync,
+ renameSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+} from 'node:fs'
+import { basename, dirname, join, relative } from 'node:path'
+import { homedir, uptime } from 'node:os'
+
+const BOOT_TOLERANCE_SEC = 120
+const LOCK_STALE_MS = 5000
+const LOCK_RETRIES = 20
+const LOCK_RETRY_MS = 25
+const SESSION_END_VERIFY_DELAY_MS = 2000
+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
+
+// 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) {
+ if (typeof value === 'string') return value
+ return typeof value?.id === 'string' ? value.id : null
+}
+
+function argPort() {
+ const i = process.argv.indexOf('--port')
+ if (i !== -1 && process.argv[i + 1]) return parseInt(process.argv[i + 1], 10)
+ return parseInt(process.env.AGENT_ADAPTER_PORT || '18473', 10)
+}
+
+function argValue(name, fallback) {
+ const i = process.argv.indexOf(name)
+ if (i !== -1 && process.argv[i + 1]) return process.argv[i + 1]
+ return fallback
+}
+
+function argEngine() {
+ const i = process.argv.indexOf('--engine')
+ const value = i !== -1 ? process.argv[i + 1] : ''
+ return value === 'codex' || value === 'cursor' || value === 'hermes' || value === 'commandcode' || value === 'devin' ? value : 'claude'
+}
+
+function paths() {
+ const cliDir = join(homedir(), '.harness', 'cli')
+ const dataDir = argValue('--data-dir', process.env.ADAPTER_DATA_DIR || join(cliDir, 'data'))
+ const claudeProjectsDir = argValue('--claude-projects-dir', process.env.CLAUDE_PROJECTS_DIR || join(homedir(), '.claude', 'projects'))
+ const codexHome = argValue('--codex-home', process.env.CODEX_HOME || join(homedir(), '.codex'))
+ const cursorHome = argValue('--cursor-home', process.env.CURSOR_HOME || join(homedir(), '.cursor'))
+ const commandcodeHome = argValue('--commandcode-home', process.env.COMMANDCODE_HOME || join(homedir(), '.commandcode'))
+ const devinHome = argValue('--devin-home', process.env.DEVIN_HOME || join(homedir(), '.local', 'share', 'devin', 'cli'))
+ return {
+ dataDir,
+ registryFile: join(dataDir, 'registry.json'),
+ bootFile: join(dataDir, 'registry-boot'),
+ claudeProjectsDir,
+ codexSessionsDir: join(codexHome, 'sessions'),
+ cursorProjectsDir: join(cursorHome, 'projects'),
+ commandcodeProjectsDir: join(commandcodeHome, 'projects'),
+ devinHome,
+ devinLocksDir: join(devinHome, 'session_locks'),
+ }
+}
+
+/** True when the path is a real file on disk right now (undefined/missing → false). */
+function existsPath(file) {
+ if (typeof file !== 'string' || !file) return false
+ try { return statSync(file).isFile() } catch { return false }
+}
+
+/**
+ * True when a hook payload came from Devin rather than the engine the hook was armed for. Devin session
+ * ids are lowercase word slugs (`blue-agustinia`) and every live session holds
+ * `<DEVIN_HOME>/session_locks/<id>.lock`, while claude's are UUIDs — so the lock file is the tell.
+ */
+function isDevinSession(input, p) {
+ const id = typeof input?.session_id === 'string' ? input.session_id : ''
+ if (!id || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id) || id.length > 64) return false
+ try { return statSync(join(p.devinLocksDir, `${id}.lock`)).isFile() } catch { return false }
+}
+
+function readStdin() {
+ return new Promise((resolve) => {
+ let data = ''
+ process.stdin.setEncoding('utf8')
+ process.stdin.on('data', (c) => (data += c))
+ process.stdin.on('end', () => resolve(data))
+ process.stdin.on('error', () => resolve(data))
+ // Safety: if stdin never ends, don't hang.
+ setTimeout(() => resolve(data), 1000)
+ })
+}
+
+function post(port, path, body) {
+ return new Promise((resolve) => {
+ const payload = JSON.stringify(body)
+ 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,
+ },
+ (res) => {
+ res.resume()
+ res.on('end', () => resolve((res.statusCode || 0) >= 200 && (res.statusCode || 0) < 300))
+ }
+ )
+ req.on('error', () => resolve(false))
+ req.on('timeout', () => {
+ req.destroy()
+ resolve(false)
+ })
+ req.write(payload)
+ req.end()
+ })
+}
+
+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) => {
+ resolve(err ? null : stdout)
+ })
+ })
+}
+
+async function panePid(pane) {
+ const stdout = await execFileText('tmux', ['display-message', '-p', '-t', pane, '#{pane_pid}'], 2000)
+ if (stdout === null) return undefined
+ const pid = Number((stdout || '').trim())
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : null
+}
+
+function processMatchesEngine(row, engine) {
+ const haystack = `${row.executable} ${row.args}`.toLowerCase()
+ if (engine === 'codex') return /(^|[\/\s])codex(?:[\s]|$)/.test(haystack)
+ if (engine === 'cursor') {
+ const executable = basename(row.executable).toLowerCase()
+ return executable === 'agent'
+ || executable === 'cursor-agent'
+ || /cursor-agent[\/\\]versions[\/\\][^/\\\s]+[\/\\]index\.js(?:\s|$)/.test(haystack)
+ }
+ return /(^|[\/\s])claude(?:[\s]|$)/.test(haystack)
+}
+
+async function processRows() {
+ const stdout = await execFileText('ps', ['-axo', 'pid=,ppid=,comm=,lstart=,args='], 3000)
+ if (stdout === null) return null
+ const rows = []
+ for (const line of stdout.split('\n')) {
+ const match = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(\S+\s+\S+\s+\S+\s+\S+\s+\S+)\s*(.*)$/.exec(line)
+ if (!match) continue
+ rows.push({
+ pid: Number(match[1]),
+ parentPid: Number(match[2]),
+ executable: match[3],
+ startMarker: match[4],
+ args: match[5],
+ })
+ }
+ return rows
+}
+
+async function paneEngineProcessState(pane, engine) {
+ const rootPid = await panePid(pane)
+ if (rootPid === undefined) return 'unknown'
+ if (!rootPid) return 'gone'
+ const rows = await processRows()
+ if (!rows) return 'unknown'
+ const children = new Map()
+ for (const row of rows) {
+ const list = children.get(row.parentPid) || []
+ list.push(row)
+ children.set(row.parentPid, list)
+ }
+ const queue = [rootPid]
+ while (queue.length > 0) {
+ const pid = queue.shift()
+ const row = rows.find((candidate) => candidate.pid === pid)
+ if (row && processMatchesEngine(row, engine)) return 'alive'
+ for (const child of children.get(pid) || []) queue.push(child.pid)
+ }
+ return 'gone'
+}
+
+function bootTimeSec() {
+ return Math.round(Date.now() / 1000 - uptime())
+}
+
+function readSavedBoot(bootFile) {
+ try {
+ const n = Number(readFileSync(bootFile, 'utf-8').trim())
+ return Number.isFinite(n) ? n : null
+ } catch {
+ return null
+ }
+}
+
+function writeBoot(bootFile) {
+ try {
+ mkdirSync(dirname(bootFile), { recursive: true })
+ writeFileSync(bootFile, String(bootTimeSec()))
+ } catch {
+ // best effort
+ }
+}
+
+function rebootedSinceSnapshot(bootFile) {
+ const saved = readSavedBoot(bootFile)
+ return saved !== null && Math.abs(bootTimeSec() - saved) > BOOT_TOLERANCE_SEC
+}
+
+function isWithin(root, file) {
+ const rel = relative(root, file)
+ return rel === '' || (!rel.startsWith('..') && !rel.startsWith('/') && !rel.startsWith('\\'))
+}
+
+function validTranscriptPath(engine, filePath, p) {
+ try {
+ const actual = realpathSync(filePath)
+ const root = realpathSync(
+ engine === 'codex' ? p.codexSessionsDir
+ : engine === 'cursor' ? p.cursorProjectsDir
+ : engine === 'commandcode' ? p.commandcodeProjectsDir
+ : p.claudeProjectsDir,
+ )
+ const st = statSync(actual)
+ if (!st.isFile() || !isWithin(root, actual)) return false
+ if (engine === 'cursor') {
+ const id = basename(actual).replace(/\.jsonl$/, '')
+ if (!id || basename(dirname(actual)) !== id || basename(dirname(dirname(actual))) !== 'agent-transcripts') return false
+ }
+ const uid = typeof process.getuid === 'function' ? process.getuid() : null
+ return uid === null || st.uid === uid
+ } catch {
+ return false
+ }
+}
+
+function isCodexSubagent(input, p) {
+ const source = input && typeof input.source === 'object' && !Array.isArray(input.source)
+ ? input.source
+ : null
+ if (source && source.subagent != null) return true
+ const file = typeof input.transcript_path === 'string' ? input.transcript_path : ''
+ if (!file || !validTranscriptPath('codex', file, p)) return false
+ let fd = null
+ try {
+ fd = openSync(file, 'r')
+ const buffer = Buffer.alloc(CODEX_META_MAX_BYTES)
+ const bytes = readSync(fd, buffer, 0, buffer.length, 0)
+ const firstLine = buffer.subarray(0, bytes).toString('utf8').split('\n').find((line) => line.trim())
+ if (!firstLine) return false
+ const record = JSON.parse(firstLine)
+ return record?.type === 'session_meta' && record?.payload?.source?.subagent != null
+ } catch {
+ return false
+ } finally {
+ if (fd !== null) {
+ try { closeSync(fd) } catch { /* best effort */ }
+ }
+ }
+}
+
+async function withRegistryLock(registryFile, fn) {
+ const lockDir = `${registryFile}.lock`
+ try { mkdirSync(dirname(registryFile), { recursive: true }) } catch { return }
+ for (let i = 0; i < LOCK_RETRIES; i++) {
+ try {
+ mkdirSync(lockDir)
+ try {
+ return fn()
+ } finally {
+ try { rmSync(lockDir, { recursive: true, force: true }) } catch { /* ignore */ }
+ }
+ } catch {
+ try {
+ const st = statSync(lockDir)
+ if (Date.now() - st.mtimeMs > LOCK_STALE_MS) rmSync(lockDir, { recursive: true, force: true })
+ } catch {
+ // lock disappeared between mkdir attempts
+ }
+ await sleep(LOCK_RETRY_MS)
+ }
+ }
+}
+
+function readRegistry(file) {
+ try {
+ const arr = JSON.parse(readFileSync(file, 'utf-8'))
+ return Array.isArray(arr) ? arr : []
+ } catch {
+ return []
+ }
+}
+
+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)
+}
+
+function cursorPendingFile() {
+ return join(paths().dataDir, 'cursor-pending-tasks.json')
+}
+
+function boundedJson(value) {
+ try {
+ const serialized = JSON.stringify(value ?? {})
+ if (Buffer.byteLength(serialized) <= CURSOR_TASK_MAX_INPUT_BYTES) return JSON.parse(serialized)
+ } catch {
+ // use the bounded fallback
+ }
+ const input = value && typeof value === 'object' && !Array.isArray(value) ? value : {}
+ return {
+ description: typeof input.description === 'string' ? input.description.slice(0, 2_000) : '',
+ prompt: typeof input.prompt === 'string' ? input.prompt.slice(0, 16_000) : '',
+ model: typeof input.model === 'string' ? input.model.slice(0, 200) : '',
+ }
+}
+
+async function persistCursorTask(input) {
+ const sessionId = input.session_id || input.conversation_id
+ const toolUseId = input.tool_use_id
+ if (typeof sessionId !== 'string' || !sessionId || typeof toolUseId !== 'string' || !toolUseId) return
+ const file = cursorPendingFile()
+ await withRegistryLock(file, () => {
+ const now = Date.now()
+ const existing = readRegistry(file).filter((item) =>
+ item
+ && typeof item.sessionId === 'string'
+ && typeof item.toolUseId === 'string'
+ && typeof item.createdAt === 'number'
+ && now - item.createdAt <= CURSOR_TASK_MAX_AGE_MS
+ && item.toolUseId !== toolUseId)
+ existing.push({ sessionId, toolUseId, input: boundedJson(input.tool_input), createdAt: now })
+ writeRegistry(file, existing.slice(-CURSOR_TASK_MAX_ENTRIES))
+ })
+}
+
+async function clearCursorTasks(sessionId) {
+ if (typeof sessionId !== 'string' || !sessionId) return
+ const file = cursorPendingFile()
+ await withRegistryLock(file, () => {
+ const current = readRegistry(file)
+ const next = current.filter((item) => !item || item.sessionId !== sessionId)
+ if (next.length) writeRegistry(file, next)
+ else {
+ try { rmSync(file, { force: true }) } catch { /* best effort */ }
+ }
+ })
+}
+
+async function fallbackRegister(input, engine, tmuxPane, launcherId) {
+ const p = paths()
+ const transcriptPath = typeof input.transcript_path === 'string' ? input.transcript_path : ''
+ const rawSessionId = input.session_id || input.conversation_id
+ const sessionId = typeof rawSessionId === 'string' && rawSessionId
+ ? rawSessionId
+ : (transcriptPath ? basename(transcriptPath).replace(/\.jsonl$/, '') : '')
+ if (!sessionId || !/^%\d+$/.test(tmuxPane)) return
+ if (engine !== 'cursor' && !transcriptPath) return
+ if (transcriptPath && !validTranscriptPath(engine, transcriptPath, p)) return
+
+ await withRegistryLock(p.registryFile, () => {
+ let sessions = rebootedSinceSnapshot(p.bootFile) ? [] : readRegistry(p.registryFile)
+ writeBoot(p.bootFile)
+ const now = Date.now()
+ const existingIndex = sessions.findIndex((s) => s && s.sessionId === sessionId)
+ const existing = existingIndex >= 0 ? sessions[existingIndex] : null
+ if (existingIndex < 0) {
+ sessions = sessions.filter((s) => !s || s.tmuxPane !== tmuxPane)
+ }
+ const entry = {
+ sessionId,
+ engine,
+ // Mirrors RegisteredSession.agentId/launcherId — the launcher uuid IS the agent id, and an
+ // offline-written record must carry it, or the daemon prunes it on the next load as an unowned
+ // (pre-machine-ID) leftover. Both names are written: the daemon reads `agentId` and falls back to
+ // `launcherId`, and an older daemon (mid-rollout) reads only `launcherId`.
+ agentId: launcherId,
+ launcherId,
+ boundAt: Date.now(),
+ transcriptPath: transcriptPath || existing?.transcriptPath || null,
+ projectDir: transcriptPath
+ ? basename(dirname(transcriptPath))
+ : basename(typeof input.cwd === 'string' ? input.cwd : '') || sessionId,
+ cwd: typeof input.cwd === 'string' ? input.cwd : (existing?.cwd ?? null),
+ tmuxPane,
+ 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),
+ cliVersion: typeof (input.cli_version || input.version) === 'string' ? (input.cli_version || input.version) : (existing?.cliVersion ?? null),
+ processIdentity: /^(?:SessionStart|sessionStart)$/.test(input.hook_event_name) ? null : (existing?.processIdentity ?? null),
+ registeredAt: typeof existing?.registeredAt === 'number' ? existing.registeredAt : now,
+ updatedAt: now,
+ lastHookAt: now,
+ lastTranscriptAt: typeof existing?.lastTranscriptAt === 'number' ? existing.lastTranscriptAt : now,
+ }
+ if (existingIndex >= 0) sessions[existingIndex] = entry
+ else sessions.push(entry)
+ writeRegistry(p.registryFile, sessions)
+ })
+}
+
+async function fallbackSessionEnd(sessionId, reason, engine, tmuxPane) {
+ if (!sessionId || reason === 'clear') return
+ await sleep(SESSION_END_VERIFY_DELAY_MS)
+ const state = await paneEngineProcessState(tmuxPane, engine)
+ if (state !== 'gone') return
+ const p = paths()
+ await withRegistryLock(p.registryFile, () => {
+ let sessions = rebootedSinceSnapshot(p.bootFile) ? [] : readRegistry(p.registryFile)
+ writeBoot(p.bootFile)
+ const next = sessions.filter((s) => !s || s.sessionId !== sessionId)
+ if (next.length !== sessions.length) writeRegistry(p.registryFile, next)
+ })
+}
+
+async function main() {
+ const port = argPort()
+ const engine = argEngine()
+ const raw = await readStdin()
+ let input = {}
+ try {
+ input = JSON.parse(raw)
+ } catch {
+ return
+ }
+
+ const event = input.hook_event_name
+ const tmuxPane = process.env.TMUX_PANE
+ if (!tmuxPane) return // tmux-only: ignore every lifecycle event from standalone CLI sessions
+ // machine-launched only: `harness <engine>` exports MACHINE_ID into the CLI's env, and that id is what
+ // binds this session's lifetime to a live launcher. A CLI the user started by hand has no id, so it is
+ // not an agent — drop its events here, exactly like a non-tmux one above.
+ const launcherId = process.env.MACHINE_ID
+ if (!launcherId) return
+ 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
+ // Devin session can fire the machine's CLAUDE hook and register itself as claude (wrong engine, and a
+ // session id claude's path validation then rejects). Devin has its own hook installed with
+ // `--engine devin`; drop the claude-armed duplicate. Cheap and scoped: a real claude session has a UUID
+ // session id and no Devin lock file.
+ if (engine === 'claude' && isDevinSession(input, paths())) return
+
+ if (((engine === 'claude' || engine === 'devin') && event === 'SessionEnd') || (engine === 'cursor' && event === 'sessionEnd')) {
+ const ok = await post(port, '/api/hook/session-end', {
+ sessionId: input.session_id || input.conversation_id,
+ reason: input.reason,
+ })
+ 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)
+ return
+ }
+
+ // Command Code's only live signal that a turn is running. Fired per tool call, so the adapter side is
+ // idempotent (see onTurnStart) — this opens a turn at the FIRST tool of a turn and is a no-op after.
+ if (engine === 'commandcode' && (event === 'PreToolUse' || event === 'preToolUse')) {
+ await post(port, '/api/hook/turn-start', {
+ sessionId: input.session_id || input.conversation_id,
+ })
+ return
+ }
+
+ if (engine === 'cursor' && event === 'preToolUse') {
+ if (input.tool_name === 'Task' && typeof input.tool_use_id === 'string') {
+ await persistCursorTask(input)
+ await post(port, '/api/hook/tool-start', {
+ sessionId: input.session_id || input.conversation_id,
+ toolUseId: input.tool_use_id,
+ toolName: input.tool_name,
+ input: input.tool_input,
+ })
+ }
+ return
+ }
+
+ if (engine === 'cursor' && event === 'stop') {
+ const sessionId = input.session_id || input.conversation_id
+ const body = {
+ engine,
+ hookEvent: event,
+ sessionId,
+ transcriptPath: input.transcript_path,
+ cwd: Array.isArray(input.workspace_roots) ? input.workspace_roots[0] : input.cwd,
+ tmuxPane,
+ model: modelName(input.model),
+ cliVersion: input.cursor_version || input.version,
+ }
+ const registered = await post(port, '/api/hook/session-start', body)
+ if (!registered) await fallbackRegister(input, engine, tmuxPane, launcherId)
+ const stopped = await post(port, '/api/hook/turn-stop', {
+ sessionId,
+ status: input.status,
+ transcriptPath: input.transcript_path,
+ })
+ if (stopped) await clearCursorTasks(sessionId)
+ return
+ }
+
+ // Stop / StopFailure (claude): the authoritative turn-close signal, independent of JSONL parsing.
+ // Stop fires when Claude finishes responding (incl. max_tokens / refusal); StopFailure fires when the
+ // turn ends on an API error (Stop does NOT fire then). Both → tell the adapter to close the turn. We
+ // write nothing to stdout so Claude stops normally (only exit 2 / decision:block would continue it).
+ // Command Code exposes no UserPromptSubmit, so Stop is its only turn-close signal (same shape as claude's).
+ if ((engine === 'claude' || engine === 'commandcode' || engine === 'devin') && (event === 'Stop' || event === 'StopFailure')) {
+ // Command Code's whole hook set is PreToolUse/PostToolUse/Stop/SessionStart — no UserPromptSubmit, so
+ // Stop is also its ONLY catch hook. Without re-registering here, a session that left the registry for
+ // any reason (a reaper miss, a daemon restart, a fresh data dir) can never come back while the CLI
+ // keeps running: the web/device just show nothing until the user quits and relaunches commandcode.
+ // Registration is idempotent, and this is also where a session first announced without a transcript
+ // (Command Code fires SessionStart before creating the file) finally gets its real path.
+ if (engine === 'commandcode') {
+ const registered = await post(port, '/api/hook/session-start', {
+ engine,
+ hookEvent: event,
+ sessionId: input.session_id,
+ transcriptPath: existsPath(input.transcript_path) ? input.transcript_path : undefined,
+ cwd: input.cwd,
+ tmuxPane,
+ title: input.session_title,
+ model: modelName(input.model),
+ cliVersion: input.cli_version || input.version,
+ })
+ if (!registered) await fallbackRegister(input, engine, tmuxPane, launcherId)
+ }
+ await post(port, '/api/hook/turn-stop', {
+ sessionId: input.session_id,
+ transcriptPath: input.transcript_path,
+ status: event === 'StopFailure' ? 'error' : undefined,
+ })
+ return
+ }
+
+ // SessionStart or UserPromptSubmit (the catch hook) → register the session. Registration is
+ // idempotent, so re-registering on every prompt is cheap. (We print nothing to stdout, so this
+ // never injects context into a UserPromptSubmit turn.)
+ // Command Code fires SessionStart BEFORE it writes the transcript, and the daemon validates the path
+ // (realpath) — sending one that isn't on disk yet gets the whole registration rejected. Announce
+ // without it; the session is registered again with the real path on the first Stop. Scoped to
+ // commandcode: every other engine REQUIRES a transcriptPath, so dropping it would break them.
+ // Devin keeps history in sessions.db and writes no transcript file (unless the user passes --export),
+ // so it registers with none — like opencode/pi/hermes.
+ const transcriptPath = engine === 'devin'
+ ? undefined
+ : engine === 'commandcode' && !existsPath(input.transcript_path)
+ ? undefined
+ : input.transcript_path
+ const body = {
+ engine,
+ launcherId,
+ hookEvent: event,
+ sessionId: input.session_id || input.conversation_id,
+ transcriptPath,
+ // 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,
+ title: input.session_title,
+ model: modelName(input.model),
+ cliVersion: input.cli_version || input.cursor_version || input.version,
+ }
+ const ok = await post(port, '/api/hook/session-start', body)
+ if (!ok) await fallbackRegister(input, engine, tmuxPane, launcherId)
+}
+
+main()
+ .catch(() => {})
+ .finally(() => {
+ // Cursor and Hermes parse the hook's stdout as JSON; `{}` is the explicit no-op (for Hermes it also
+ // guarantees a pre_llm_call hook never injects context). Claude/Codex want no stdout at all.
+ const e = argEngine()
+ if (e === 'cursor' || e === 'hermes') process.stdout.write('{}\n', () => process.exit(0))
+ else process.exit(0)
+ })
diff --git a/cli/package-lock.json b/cli/package-lock.json
new file mode 100644
index 000000000..a5384684a
--- /dev/null
+++ b/cli/package-lock.json
@@ -0,0 +1,2422 @@
+{
+ "name": "harness",
+ "version": "0.0.1",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "harness",
+ "version": "0.0.1",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@noble/ciphers": "^1.3.0",
+ "@noble/curves": "^1.9.7",
+ "@noble/hashes": "^1.8.0",
+ "chokidar": "^4.0.0",
+ "dotenv": "^17.2.3",
+ "ws": "^8.18.0",
+ "zod": "^4.0.0"
+ },
+ "bin": {
+ "harness": "dist/cli.js"
+ },
+ "devDependencies": {
+ "@types/node": "^20.14.10",
+ "@types/ws": "^8.18.1",
+ "esbuild": "^0.27.2",
+ "tsx": "^4.16.2",
+ "typescript": "^5.5.3",
+ "vitest": "^4.1.10"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@emnapi/core": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz",
+ "integrity": "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/wasi-threads": "1.2.2",
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@emnapi/runtime": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.1.tgz",
+ "integrity": "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@emnapi/wasi-threads": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz",
+ "integrity": "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz",
+ "integrity": "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.7.tgz",
+ "integrity": "sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.7.tgz",
+ "integrity": "sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.7.tgz",
+ "integrity": "sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.7.tgz",
+ "integrity": "sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.7.tgz",
+ "integrity": "sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.7.tgz",
+ "integrity": "sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.7.tgz",
+ "integrity": "sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.7.tgz",
+ "integrity": "sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.7.tgz",
+ "integrity": "sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.7.tgz",
+ "integrity": "sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.7.tgz",
+ "integrity": "sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.7.tgz",
+ "integrity": "sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.7.tgz",
+ "integrity": "sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.7.tgz",
+ "integrity": "sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.7.tgz",
+ "integrity": "sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.7.tgz",
+ "integrity": "sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.7.tgz",
+ "integrity": "sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.7.tgz",
+ "integrity": "sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.7.tgz",
+ "integrity": "sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.7.tgz",
+ "integrity": "sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.7.tgz",
+ "integrity": "sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.7.tgz",
+ "integrity": "sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.7.tgz",
+ "integrity": "sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.7.tgz",
+ "integrity": "sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.7.tgz",
+ "integrity": "sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.5.5",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@napi-rs/wasm-runtime": {
+ "version": "1.1.6",
+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz",
+ "integrity": "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@tybys/wasm-util": "^0.10.3"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ },
+ "peerDependencies": {
+ "@emnapi/core": "^1.7.1",
+ "@emnapi/runtime": "^1.7.1"
+ }
+ },
+ "node_modules/@noble/ciphers": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz",
+ "integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==",
+ "license": "MIT",
+ "engines": {
+ "node": "^14.21.3 || >=16"
+ },
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
+ "node_modules/@noble/curves": {
+ "version": "1.9.7",
+ "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz",
+ "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==",
+ "license": "MIT",
+ "dependencies": {
+ "@noble/hashes": "1.8.0"
+ },
+ "engines": {
+ "node": "^14.21.3 || >=16"
+ },
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
+ "node_modules/@noble/hashes": {
+ "version": "1.8.0",
+ "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
+ "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
+ "license": "MIT",
+ "engines": {
+ "node": "^14.21.3 || >=16"
+ },
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
+ "node_modules/@oxc-project/types": {
+ "version": "0.139.0",
+ "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.139.0.tgz",
+ "integrity": "sha512-r9gHphtCs+1M7J0pw6Sn/hh/Wpa/iQrOOkrNAlVLF/gHq+/CJmHIWKKUUhdWjcD6CIa8idarspCsASiXCXvFUw==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/Boshen"
+ }
+ },
+ "node_modules/@rolldown/binding-android-arm64": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.1.5.tgz",
+ "integrity": "sha512-lZg8fqIv2v7FF237bwMgzGZEJvGL79/s5knJ/i6FmsGF4XXlzccZ4jb+TrFIxtSSxFtIpdsgrPZeMk1I9AFcyQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-darwin-arm64": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.1.5.tgz",
+ "integrity": "sha512-51Bnx9pNiMRKSUNtBfySkNJ9vMU9Hh3I1ozDd6gyPPYzaXCfnptUcEZxXGYFn+ul2dtcMUiqGR1Yai2K10uoTw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-darwin-x64": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.1.5.tgz",
+ "integrity": "sha512-Tm+gbfC0aHu1tBA/JvKQh32S0K6YgCHkiAF4/W6xX0K0RmNuc94VeK419dJoE65R5aRxmo+noZQSWrAMF6yb6g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-freebsd-x64": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.1.5.tgz",
+ "integrity": "sha512-JMzDKCCXq93YccG5gz3hvOs1oXRKAf0XYpfOS88e+wZrC8Iugj6j68867vrYZkvpDDpKn/KoKORThmchMpF6TA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm-gnueabihf": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.1.5.tgz",
+ "integrity": "sha512-uML21j2K5TfPGutKxub+M+nLjZIrWjXQ5Grx4lCe/nimTj9B4L63zHpjXLl4y0L3mcm2htEQIb06oCG/szerNw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm64-gnu": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.1.5.tgz",
+ "integrity": "sha512-navSiuTMogvnQoZoM/v+l3ZWo50/NTwSHSzheABx/RCnmUPaKwq9qSo4Br2OYRs21+Fz8uFqITZM3H4opOB0/Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm64-musl": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.1.5.tgz",
+ "integrity": "sha512-lAryqH7IteztmCXQXk0etKj4wBQ7Gx5S6LjKhsgp9zb8I5bsuvU/2llH1hDQcjsFeqIsovMVN339/8pUDDBXxA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-ppc64-gnu": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.1.5.tgz",
+ "integrity": "sha512-fsK/sNBnxzBlL4O1JNrZakVQxPspqpED5dLtNsZS9oOKmtSpdNIzxH2kkol5HYTWJN47sE20ztMJPxfZ89qGOg==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-s390x-gnu": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.1.5.tgz",
+ "integrity": "sha512-gLYb4BIadlfTOYT5gO503n8zQjXflgzpD0FcyKh0Mzx3rqCZKnHoJWV9xe1KXUJ5lx2JfcSHr/mhzS0PC/McAA==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-gnu": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.1.5.tgz",
+ "integrity": "sha512-FjcpEKUyJygHgs1o50VYNvkt5+7Le/VEdYt0AkRpkL33MnyQfwr8l5mXwMmfmTbyMPr5vJLC+8/Gd9gXnwU1QQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-musl": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.1.5.tgz",
+ "integrity": "sha512-Me+PfPI2TMeOQk0gYWfLQZtTktrmzbr8cDboqX83XKc7UrgAi55gF+2dUkWdxd19n55Essp2yeca+O9N5rBxHg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-openharmony-arm64": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.1.5.tgz",
+ "integrity": "sha512-yc5WrLzXks6zCQfn9Oxr8pORKyl/pF+QjHmW/Qx3qu0oyrrNC+y2JLTU1E2rcWYAmzlnqngWXHQjy51VzW70Vw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-wasm32-wasi": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.1.5.tgz",
+ "integrity": "sha512-VbQGPX2b4r48TAMIM2cjgluIM1HYutm4pcTEJsle7iEP7sB1dFqtPLBVbdLAZCxy1txCcPxf4QFf4v8uvltPqA==",
+ "cpu": [
+ "wasm32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/core": "1.11.1",
+ "@emnapi/runtime": "1.11.1",
+ "@napi-rs/wasm-runtime": "^1.1.6"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-arm64-msvc": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.1.5.tgz",
+ "integrity": "sha512-gHv82k63z4qpV5+Q1y/12KrK0ltWBukVDI8nZcbT7Tt/ZlOIVwppazneq0F93oDxTo3IgAMEDIoQh3E2n6mVsw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-x64-msvc": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.1.5.tgz",
+ "integrity": "sha512-tTZuDBPw85tEN5PQi1pnEBzDy0Z49HtScLAbD5t6hyeU92A95pRWaSMw1GZZi/RwgSgUIl0xrSlXIT/9QzvYSA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/pluginutils": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",
+ "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@standard-schema/spec": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
+ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@tybys/wasm-util": {
+ "version": "0.10.3",
+ "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz",
+ "integrity": "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@types/chai": {
+ "version": "5.2.3",
+ "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
+ "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/deep-eql": "*",
+ "assertion-error": "^2.0.1"
+ }
+ },
+ "node_modules/@types/deep-eql": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
+ "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "20.19.43",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz",
+ "integrity": "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~6.21.0"
+ }
+ },
+ "node_modules/@types/ws": {
+ "version": "8.18.1",
+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
+ "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
+ "node_modules/@vitest/expect": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.10.tgz",
+ "integrity": "sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@standard-schema/spec": "^1.1.0",
+ "@types/chai": "^5.2.2",
+ "@vitest/spy": "4.1.10",
+ "@vitest/utils": "4.1.10",
+ "chai": "^6.2.2",
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/mocker": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.10.tgz",
+ "integrity": "sha512-v0xaezt+DKEmKfaxg133ldzADrwLGd7Ze1MfQQTYfvs8OqZIwbxyxaYURivwV7sWy5fqn3rH5uOrSp07bp44Ow==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/spy": "4.1.10",
+ "estree-walker": "^3.0.3",
+ "magic-string": "^0.30.21"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "msw": "^2.4.9",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "msw": {
+ "optional": true
+ },
+ "vite": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@vitest/pretty-format": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.10.tgz",
+ "integrity": "sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/runner": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.10.tgz",
+ "integrity": "sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/utils": "4.1.10",
+ "pathe": "^2.0.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/snapshot": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.10.tgz",
+ "integrity": "sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "4.1.10",
+ "@vitest/utils": "4.1.10",
+ "magic-string": "^0.30.21",
+ "pathe": "^2.0.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/spy": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.10.tgz",
+ "integrity": "sha512-PLf/Ugvoq5wO/b4rwYCR1h2PSIdXz7wnkQFMiUpLdtM7l6pqVFcQIBEHyT1+l+cj7mNwAfZHzqXqDyjvOuwbDw==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/utils": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.10.tgz",
+ "integrity": "sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "4.1.10",
+ "convert-source-map": "^2.0.0",
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/assertion-error": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/chai": {
+ "version": "6.2.2",
+ "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",
+ "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/chokidar": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz",
+ "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==",
+ "license": "MIT",
+ "dependencies": {
+ "readdirp": "^4.0.1"
+ },
+ "engines": {
+ "node": ">= 14.16.0"
+ },
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
+ "node_modules/convert-source-map": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
+ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/detect-libc": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/dotenv": {
+ "version": "17.4.2",
+ "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz",
+ "integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==",
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://dotenvx.com"
+ }
+ },
+ "node_modules/es-module-lexer": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.0.tgz",
+ "integrity": "sha512-KLdwQm2NvGLDkQDCGvmiQrhkd0JbMzXthwQAUgWjQuQdBLFa3eiBP5arXZyA+f8x+x7OXgud6bq2rxjGtHV2tw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/esbuild": {
+ "version": "0.27.7",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.7.tgz",
+ "integrity": "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.27.7",
+ "@esbuild/android-arm": "0.27.7",
+ "@esbuild/android-arm64": "0.27.7",
+ "@esbuild/android-x64": "0.27.7",
+ "@esbuild/darwin-arm64": "0.27.7",
+ "@esbuild/darwin-x64": "0.27.7",
+ "@esbuild/freebsd-arm64": "0.27.7",
+ "@esbuild/freebsd-x64": "0.27.7",
+ "@esbuild/linux-arm": "0.27.7",
+ "@esbuild/linux-arm64": "0.27.7",
+ "@esbuild/linux-ia32": "0.27.7",
+ "@esbuild/linux-loong64": "0.27.7",
+ "@esbuild/linux-mips64el": "0.27.7",
+ "@esbuild/linux-ppc64": "0.27.7",
+ "@esbuild/linux-riscv64": "0.27.7",
+ "@esbuild/linux-s390x": "0.27.7",
+ "@esbuild/linux-x64": "0.27.7",
+ "@esbuild/netbsd-arm64": "0.27.7",
+ "@esbuild/netbsd-x64": "0.27.7",
+ "@esbuild/openbsd-arm64": "0.27.7",
+ "@esbuild/openbsd-x64": "0.27.7",
+ "@esbuild/openharmony-arm64": "0.27.7",
+ "@esbuild/sunos-x64": "0.27.7",
+ "@esbuild/win32-arm64": "0.27.7",
+ "@esbuild/win32-ia32": "0.27.7",
+ "@esbuild/win32-x64": "0.27.7"
+ }
+ },
+ "node_modules/estree-walker": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0"
+ }
+ },
+ "node_modules/expect-type": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
+ "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
+ "node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/lightningcss": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",
+ "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==",
+ "dev": true,
+ "license": "MPL-2.0",
+ "dependencies": {
+ "detect-libc": "^2.0.3"
+ },
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ },
+ "optionalDependencies": {
+ "lightningcss-android-arm64": "1.32.0",
+ "lightningcss-darwin-arm64": "1.32.0",
+ "lightningcss-darwin-x64": "1.32.0",
+ "lightningcss-freebsd-x64": "1.32.0",
+ "lightningcss-linux-arm-gnueabihf": "1.32.0",
+ "lightningcss-linux-arm64-gnu": "1.32.0",
+ "lightningcss-linux-arm64-musl": "1.32.0",
+ "lightningcss-linux-x64-gnu": "1.32.0",
+ "lightningcss-linux-x64-musl": "1.32.0",
+ "lightningcss-win32-arm64-msvc": "1.32.0",
+ "lightningcss-win32-x64-msvc": "1.32.0"
+ }
+ },
+ "node_modules/lightningcss-android-arm64": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz",
+ "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-arm64": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz",
+ "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-x64": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz",
+ "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-freebsd-x64": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz",
+ "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm-gnueabihf": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz",
+ "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-gnu": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz",
+ "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-musl": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz",
+ "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-gnu": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz",
+ "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-musl": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz",
+ "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-arm64-msvc": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz",
+ "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-x64-msvc": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz",
+ "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/magic-string": {
+ "version": "0.30.21",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.5"
+ }
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.15",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.15.tgz",
+ "integrity": "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/obug": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.3.tgz",
+ "integrity": "sha512-9miFgM2OFba7hB+pRgvtV84pYTBaoTHohvmIgiRt6dRIzbwEOIaNaP+dIlGs2fNFoB0SeISs0Jz5WFVRid6Xyg==",
+ "dev": true,
+ "funding": [
+ "https://github.com/sponsors/sxzz",
+ "https://opencollective.com/debug"
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
+ "node_modules/pathe": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/picomatch": {
+ "version": "4.0.5",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz",
+ "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/postcss": {
+ "version": "8.5.16",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.16.tgz",
+ "integrity": "sha512-vuwillviilfKZsg0VGj5R/YwwcHx4SLsIOI/7K6mQkWx+l5cUHTjj5g0AasTBcyXsbfTgrwsUNmVUb5xVwyPwg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.12",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/readdirp": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz",
+ "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 14.18.0"
+ },
+ "funding": {
+ "type": "individual",
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
+ "node_modules/rolldown": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.1.5.tgz",
+ "integrity": "sha512-t9z29cJjXf/vxQ8dyhCSpt6H6aSwHTk8cT5I3iy6SMXuFpk5mB6PL6XfC8PCwrPTx93udwKUm9HRteAlTGBLiA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@oxc-project/types": "=0.139.0",
+ "@rolldown/pluginutils": "^1.0.0"
+ },
+ "bin": {
+ "rolldown": "bin/cli.mjs"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "optionalDependencies": {
+ "@rolldown/binding-android-arm64": "1.1.5",
+ "@rolldown/binding-darwin-arm64": "1.1.5",
+ "@rolldown/binding-darwin-x64": "1.1.5",
+ "@rolldown/binding-freebsd-x64": "1.1.5",
+ "@rolldown/binding-linux-arm-gnueabihf": "1.1.5",
+ "@rolldown/binding-linux-arm64-gnu": "1.1.5",
+ "@rolldown/binding-linux-arm64-musl": "1.1.5",
+ "@rolldown/binding-linux-ppc64-gnu": "1.1.5",
+ "@rolldown/binding-linux-s390x-gnu": "1.1.5",
+ "@rolldown/binding-linux-x64-gnu": "1.1.5",
+ "@rolldown/binding-linux-x64-musl": "1.1.5",
+ "@rolldown/binding-openharmony-arm64": "1.1.5",
+ "@rolldown/binding-wasm32-wasi": "1.1.5",
+ "@rolldown/binding-win32-arm64-msvc": "1.1.5",
+ "@rolldown/binding-win32-x64-msvc": "1.1.5"
+ }
+ },
+ "node_modules/siginfo": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
+ "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/stackback": {
+ "version": "0.0.2",
+ "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
+ "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/std-env": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz",
+ "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tinybench": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
+ "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tinyexec": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.2.4.tgz",
+ "integrity": "sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tinyglobby": {
+ "version": "0.2.17",
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.4"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/SuperchupuDev"
+ }
+ },
+ "node_modules/tinyrainbow": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz",
+ "integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/tslib": {
+ "version": "2.8.1",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
+ "dev": true,
+ "license": "0BSD",
+ "optional": true
+ },
+ "node_modules/tsx": {
+ "version": "4.23.0",
+ "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.0.tgz",
+ "integrity": "sha512-eUdUIaCr963q2h5u3+QwvYp0+eqPvn+egeqZUm0hwERCqqx1E3kK5ehbGCvqSE5MQAULr67ww0cA3jKc3YkM1w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "esbuild": "~0.28.0"
+ },
+ "bin": {
+ "tsx": "dist/cli.mjs"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/aix-ppc64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",
+ "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/android-arm": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",
+ "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/android-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",
+ "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/android-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",
+ "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/darwin-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",
+ "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/darwin-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",
+ "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",
+ "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/freebsd-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",
+ "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/linux-arm": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",
+ "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/linux-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",
+ "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/linux-ia32": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",
+ "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/linux-loong64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",
+ "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/linux-mips64el": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",
+ "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/linux-ppc64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",
+ "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/linux-riscv64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",
+ "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/linux-s390x": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",
+ "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/linux-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",
+ "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",
+ "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/netbsd-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",
+ "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",
+ "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/openbsd-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",
+ "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",
+ "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/sunos-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",
+ "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/win32-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",
+ "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/win32-ia32": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",
+ "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/win32-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",
+ "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/esbuild": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",
+ "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.28.1",
+ "@esbuild/android-arm": "0.28.1",
+ "@esbuild/android-arm64": "0.28.1",
+ "@esbuild/android-x64": "0.28.1",
+ "@esbuild/darwin-arm64": "0.28.1",
+ "@esbuild/darwin-x64": "0.28.1",
+ "@esbuild/freebsd-arm64": "0.28.1",
+ "@esbuild/freebsd-x64": "0.28.1",
+ "@esbuild/linux-arm": "0.28.1",
+ "@esbuild/linux-arm64": "0.28.1",
+ "@esbuild/linux-ia32": "0.28.1",
+ "@esbuild/linux-loong64": "0.28.1",
+ "@esbuild/linux-mips64el": "0.28.1",
+ "@esbuild/linux-ppc64": "0.28.1",
+ "@esbuild/linux-riscv64": "0.28.1",
+ "@esbuild/linux-s390x": "0.28.1",
+ "@esbuild/linux-x64": "0.28.1",
+ "@esbuild/netbsd-arm64": "0.28.1",
+ "@esbuild/netbsd-x64": "0.28.1",
+ "@esbuild/openbsd-arm64": "0.28.1",
+ "@esbuild/openbsd-x64": "0.28.1",
+ "@esbuild/openharmony-arm64": "0.28.1",
+ "@esbuild/sunos-x64": "0.28.1",
+ "@esbuild/win32-arm64": "0.28.1",
+ "@esbuild/win32-ia32": "0.28.1",
+ "@esbuild/win32-x64": "0.28.1"
+ }
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "6.21.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/vite": {
+ "version": "8.1.4",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-8.1.4.tgz",
+ "integrity": "sha512-bTT9PsdWO+MQMNG9ZXIP/qM9wGh37DFxTV/sPq9cFpHr3w4jkgef032PkAL9jAqhk3Nz8NQw3O8n6/xFkqO4QQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "lightningcss": "^1.32.0",
+ "picomatch": "^4.0.5",
+ "postcss": "^8.5.16",
+ "rolldown": "~1.1.4",
+ "tinyglobby": "^0.2.17"
+ },
+ "bin": {
+ "vite": "bin/vite.js"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/vitejs/vite?sponsor=1"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ },
+ "peerDependencies": {
+ "@types/node": "^20.19.0 || >=22.12.0",
+ "@vitejs/devtools": "^0.3.0",
+ "esbuild": "^0.27.0 || ^0.28.0",
+ "jiti": ">=1.21.0",
+ "less": "^4.0.0",
+ "sass": "^1.70.0",
+ "sass-embedded": "^1.70.0",
+ "stylus": ">=0.54.8",
+ "sugarss": "^5.0.0",
+ "terser": "^5.16.0",
+ "tsx": "^4.8.1",
+ "yaml": "^2.4.2"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ },
+ "@vitejs/devtools": {
+ "optional": true
+ },
+ "esbuild": {
+ "optional": true
+ },
+ "jiti": {
+ "optional": true
+ },
+ "less": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ },
+ "sass-embedded": {
+ "optional": true
+ },
+ "stylus": {
+ "optional": true
+ },
+ "sugarss": {
+ "optional": true
+ },
+ "terser": {
+ "optional": true
+ },
+ "tsx": {
+ "optional": true
+ },
+ "yaml": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/vitest": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.10.tgz",
+ "integrity": "sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/expect": "4.1.10",
+ "@vitest/mocker": "4.1.10",
+ "@vitest/pretty-format": "4.1.10",
+ "@vitest/runner": "4.1.10",
+ "@vitest/snapshot": "4.1.10",
+ "@vitest/spy": "4.1.10",
+ "@vitest/utils": "4.1.10",
+ "es-module-lexer": "^2.0.0",
+ "expect-type": "^1.3.0",
+ "magic-string": "^0.30.21",
+ "obug": "^2.1.1",
+ "pathe": "^2.0.3",
+ "picomatch": "^4.0.3",
+ "std-env": "^4.0.0-rc.1",
+ "tinybench": "^2.9.0",
+ "tinyexec": "^1.0.2",
+ "tinyglobby": "^0.2.15",
+ "tinyrainbow": "^3.1.0",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0",
+ "why-is-node-running": "^2.3.0"
+ },
+ "bin": {
+ "vitest": "vitest.mjs"
+ },
+ "engines": {
+ "node": "^20.0.0 || ^22.0.0 || >=24.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "@edge-runtime/vm": "*",
+ "@opentelemetry/api": "^1.9.0",
+ "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",
+ "@vitest/browser-playwright": "4.1.10",
+ "@vitest/browser-preview": "4.1.10",
+ "@vitest/browser-webdriverio": "4.1.10",
+ "@vitest/coverage-istanbul": "4.1.10",
+ "@vitest/coverage-v8": "4.1.10",
+ "@vitest/ui": "4.1.10",
+ "happy-dom": "*",
+ "jsdom": "*",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@edge-runtime/vm": {
+ "optional": true
+ },
+ "@opentelemetry/api": {
+ "optional": true
+ },
+ "@types/node": {
+ "optional": true
+ },
+ "@vitest/browser-playwright": {
+ "optional": true
+ },
+ "@vitest/browser-preview": {
+ "optional": true
+ },
+ "@vitest/browser-webdriverio": {
+ "optional": true
+ },
+ "@vitest/coverage-istanbul": {
+ "optional": true
+ },
+ "@vitest/coverage-v8": {
+ "optional": true
+ },
+ "@vitest/ui": {
+ "optional": true
+ },
+ "happy-dom": {
+ "optional": true
+ },
+ "jsdom": {
+ "optional": true
+ },
+ "vite": {
+ "optional": false
+ }
+ }
+ },
+ "node_modules/why-is-node-running": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
+ "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "siginfo": "^2.0.0",
+ "stackback": "0.0.2"
+ },
+ "bin": {
+ "why-is-node-running": "cli.js"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/ws": {
+ "version": "8.21.0",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
+ "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": ">=5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/zod": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz",
+ "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
+ }
+ }
+}
diff --git a/cli/package.json b/cli/package.json
new file mode 100644
index 000000000..9a9bbb9d3
--- /dev/null
+++ b/cli/package.json
@@ -0,0 +1,46 @@
+{
+ "name": "harness",
+ "version": "0.0.1",
+ "type": "module",
+ "bin": {
+ "harness": "dist/cli.js"
+ },
+ "scripts": {
+ "dev": "tsx src/cli.ts",
+ "build": "node build.mjs",
+ "bundle": "node build-bundle.mjs",
+ "typecheck": "tsc --noEmit",
+ "start": "node dist/cli.js",
+ "test": "vitest run",
+ "test:cursor-e2e": "RUN_CURSOR_E2E=1 vitest run src/engines/cursor/localE2e.spec.ts",
+ "release": "bash scripts/upload-cli.sh"
+ },
+ "dependencies": {
+ "@noble/ciphers": "^1.3.0",
+ "@noble/curves": "^1.9.7",
+ "@noble/hashes": "^1.8.0",
+ "chokidar": "^4.0.0",
+ "dotenv": "^17.2.3",
+ "ws": "^8.18.0",
+ "zod": "^4.0.0"
+ },
+ "devDependencies": {
+ "@types/node": "^20.14.10",
+ "@types/ws": "^8.18.1",
+ "esbuild": "^0.27.2",
+ "tsx": "^4.16.2",
+ "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) in tmux and drive them from the web or a paired device.",
+ "license": "Apache-2.0",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/autonomous-ai/autonomous-harness.git",
+ "directory": "cli"
+ },
+ "homepage": "https://github.com/autonomous-ai/autonomous-harness/tree/main/cli",
+ "engines": {
+ "node": ">=20"
+ }
+}
diff --git a/cli/scripts/install-cli.sh b/cli/scripts/install-cli.sh
new file mode 100755
index 000000000..6c1cebc2f
--- /dev/null
+++ b/cli/scripts/install-cli.sh
@@ -0,0 +1,187 @@
+#!/usr/bin/env bash
+# Install the adapter CLI from THIS working tree into ~/.harness/cli — the local twin of
+# scripts/upload-cli.sh with the GCS round-trip cut out. It produces exactly the layout the public
+# installer does (the hosted installer), so afterwards `harness` on this computer IS
+# your build. Nothing is uploaded, nothing is version-bumped, nothing is git-committed.
+#
+# Usage:
+# bash scripts/install-cli.sh # bundle -> install -> restart the daemon if it was running
+# bash scripts/install-cli.sh --no-build # install the existing dist/ as-is
+# bash scripts/install-cli.sh --no-restart # swap the bytes, leave the daemon stopped
+# bash scripts/install-cli.sh --no-updates # pin this build: turn self-update OFF (default: ON)
+#
+# SELF-UPDATE STAYS ON BY DEFAULT, and the version label is what makes that safe. The build is labelled
+# `<published-core>-dev.<sha>`, and semverGt() (lib/selfUpdate.ts) compares the X.Y.Z core ONLY and is
+# false on equality — so the release you are level with can never overwrite your build, while the NEXT
+# release does. That is the behaviour you want: develop on your own bytes, and still be carried forward
+# when a real version ships.
+#
+# It used to default to OFF, which pinned the computer silently: a new release would land in the manifest
+# and simply never arrive, and the only clue was `harness update` working by hand while nothing happened
+# on its own. `--no-updates` still gives you that, deliberately — it exports ADAPTER_UPDATE_DISABLE=true
+# in the launcher, switching off both the 60s poll and `harness join`'s update-before-connect (cli.ts
+# `stageLatestBundle`). To rejoin the release train from a pinned install, re-run this without the flag,
+# or the public installer:
+# curl -fsSL https://harness.autonomous.ai/install.sh | bash
+set -euo pipefail
+
+ADAPTER_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" # this package
+SRC_CLI="$ADAPTER_DIR/dist/cli.js"
+SRC_NOTIFY="$ADAPTER_DIR/dist/notify.mjs"
+
+# Install layout — same defaults as src/config/env.ts, overridable for a sandboxed try-out.
+CLI_DIR="${ADAPTER_CLI_DIR:-$HOME/.harness/cli}"
+DATA_DIR="${ADAPTER_DATA_DIR:-$CLI_DIR/data}"
+BIN_DIR="${HARNESS_BIN_DIR:-$HOME/.local/bin}"
+LAUNCHER="$BIN_DIR/harness"
+PID_FILE="$DATA_DIR/adapter.pid"
+
+# Source of truth for the *core* X.Y.Z, same as upload-cli.sh: whatever is published. Only used to
+# label the build (see step 1) — this script never publishes.
+GCS_BUCKET="${GCS_BUCKET:-s3-autonomous-upgrade-3}"
+GCS_PUBLIC_BASE_URL="${GCS_PUBLIC_BASE_URL:-https://storage.googleapis.com/${GCS_BUCKET}}"
+METADATA_PATH="${METADATA_PATH:-harness/cli/metadata.json}"
+OTA_KEY="${OTA_KEY:-cli}" # must match ADAPTER_UPDATE_KEY in src/config/env.ts
+
+# --- Parse args ---
+DO_BUILD=1
+DO_RESTART=1
+KEEP_UPDATES=1 # self-update ON unless --no-updates says otherwise (see the header)
+LABEL="" # the version this run bundles; stays empty under --no-build (nothing was built to label)
+for arg in "$@"; do
+ case "$arg" in
+ --no-build) DO_BUILD=0 ;;
+ --no-restart) DO_RESTART=0 ;;
+ --updates) KEEP_UPDATES=1 ;; # accepted for muscle memory; it is the default now
+ --no-updates) KEEP_UPDATES=0 ;;
+ *) echo "error: unknown argument '$arg' (see the header of $0)" >&2; exit 1 ;;
+ esac
+done
+
+command -v node >/dev/null 2>&1 || { echo "error: node not found — the CLI is plain JS run by your Node (>= 20)" >&2; exit 1; }
+NODE_MAJOR="$(node -e 'process.stdout.write(String(process.versions.node.split(".")[0]))')"
+[ "$NODE_MAJOR" -ge 20 ] || { echo "error: Node >= 20 required (found $(node -v))" >&2; exit 1; }
+if [ "$DO_BUILD" -eq 1 ]; then
+ command -v npm >/dev/null 2>&1 || { echo "error: npm not found (needed for the bundle step; use --no-build to skip)" >&2; exit 1; }
+fi
+
+# --- Step 1: bundle, labelled <published-core>-dev.<sha>[.dirty] ---
+# The core matches the release so `harness version`/`status` read sensibly next to prod, and the
+# prerelease suffix makes it unmistakably a local build. semverGt() (lib/selfUpdate.ts) compares the
+# X.Y.Z core only, so this is never NEWER than the published release — a second layer under the
+# launcher's disable: even with updates on, the computer sits still until the next real release
+# instead of oscillating.
+if [ "$DO_BUILD" -eq 1 ]; then
+ META_URL="${GCS_PUBLIC_BASE_URL%/}/${METADATA_PATH#/}"
+ CORE="$(curl -fsSL --max-time 6 "$META_URL" 2>/dev/null | node -e '
+let s=""; process.stdin.on("data",d=>s+=d).on("end",()=>{
+ try { process.stdout.write(String((JSON.parse(s)[process.argv[1]]||{}).version||"")) } catch { process.stdout.write("") }
+})' "$OTA_KEY" 2>/dev/null || true)"
+ if [ -z "$CORE" ]; then
+ CORE="$(node -p "require('$ADAPTER_DIR/package.json').version" 2>/dev/null || echo '0.0.0')"
+ echo ">> manifest unreachable — labelling against package.json: $CORE" >&2
+ fi
+ SHA="$(git -C "$ADAPTER_DIR" rev-parse --short HEAD 2>/dev/null || echo nogit)"
+ DIRTY=""
+ # --porcelain, not `diff --quiet`: an UNTRACKED new source file changes the bundle too. dist/ is
+ # gitignored, so bundling never makes the next run look dirty by itself.
+ [ -z "$(git -C "$ADAPTER_DIR" status --porcelain -- "$ADAPTER_DIR" 2>/dev/null)" ] || DIRTY=".dirty"
+ LABEL="${CORE}-dev.${SHA}${DIRTY}"
+ echo ">> bundling ${LABEL}…" # braces required: bash 3.2 swallows the following UTF-8 byte into the name
+ ( cd "$ADAPTER_DIR" && ADAPTER_VERSION="$LABEL" npm run bundle )
+fi
+[ -f "$SRC_CLI" ] && [ -f "$SRC_NOTIFY" ] || { echo "error: dist/cli.js or dist/notify.mjs missing — bundle first (drop --no-build)" >&2; exit 1; }
+head -1 "$SRC_CLI" | grep -q '^#!' || { echo "error: dist/cli.js lost its shebang on line 1 (esbuild change?)" >&2; exit 1; }
+
+# --- Step 2: canary + read back the version REALLY in the artifact ---
+# Runs before anything on disk is touched: a bundle that can't even print its own version must not
+# replace a working install (the same gate the self-updater applies). Everything below reports
+# `node dist/cli.js version` rather than the label above, so `--no-build` — where dist/ may hold a
+# bundle some other command produced — can never announce a version it isn't installing.
+VER="$(node "$SRC_CLI" version 2>/dev/null || true)"
+[ -n "$VER" ] || { echo "error: 'node dist/cli.js version' failed — refusing to install a broken bundle" >&2; exit 1; }
+if [ "$DO_BUILD" -eq 1 ] && [ "$VER" != "$LABEL" ]; then
+ echo "error: bundle reports '$VER', expected '$LABEL' (ADAPTER_VERSION not injected)" >&2; exit 1
+fi
+echo ">> installing $VER"
+case "$VER" in
+ *-*) : ;; # has a prerelease suffix → a published release can never outrank it
+ *) echo " note: '$VER' looks like a RELEASE version, not a -dev build. With self-update on, a newer" >&2
+ echo " published release would replace it; rebuild without --no-build to get a -dev label." >&2 ;;
+esac
+
+# --- Step 3: stop the running daemon (it holds the OLD bytes in memory) ---
+WAS_RUNNING=0
+RUNNING_PID=""
+if [ -f "$PID_FILE" ]; then RUNNING_PID="$(tr -dc '0-9' < "$PID_FILE" || true)"; fi
+if [ -n "$RUNNING_PID" ] && kill -0 "$RUNNING_PID" 2>/dev/null; then
+ WAS_RUNNING=1
+ echo ">> stopping the running adapter (pid $RUNNING_PID)…"
+ # Prefer the CLI's own stop (graceful WS close → releases the machine-owner claim, clears the pid
+ # file); fall back to signals if the currently-installed bundle is broken or missing.
+ node "$CLI_DIR/cli.js" stop >/dev/null 2>&1 || kill -TERM "$RUNNING_PID" 2>/dev/null || true
+ for _ in 1 2 3 4 5 6 7 8 9 10; do kill -0 "$RUNNING_PID" 2>/dev/null || break; sleep 0.3; done
+ if kill -0 "$RUNNING_PID" 2>/dev/null; then kill -KILL "$RUNNING_PID" 2>/dev/null || true; sleep 0.5; fi
+ rm -f "$PID_FILE"
+fi
+
+# --- Step 4: install the artifacts (write-then-rename; never touch DATA_DIR) ---
+# DATA_DIR lives INSIDE CLI_DIR and holds the token, computer-id, log and session registry — this step
+# only ever replaces the three packaged files, so a reinstall keeps the computer joined to its machine.
+mkdir -p "$CLI_DIR" "$BIN_DIR"
+install_file() {
+ local src="$1" dst="$2" mode="$3"
+ cp "$src" "$dst.tmp"
+ chmod "$mode" "$dst.tmp"
+ mv -f "$dst.tmp" "$dst" # atomic within the same filesystem
+}
+install_file "$SRC_CLI" "$CLI_DIR/cli.js" 644
+install_file "$SRC_NOTIFY" "$CLI_DIR/notify.mjs" 644
+printf '{"type":"module"}\n' > "$CLI_DIR/package.json" # the bundle is ESM
+# Drop any .prev left by a previous self-update: a rollback to that release build would silently undo
+# this install.
+rm -f "$CLI_DIR/cli.js.prev" "$CLI_DIR/notify.mjs.prev"
+
+# --- Step 5: the launcher ---
+if [ "$KEEP_UPDATES" -eq 1 ]; then
+ cat > "$LAUNCHER.tmp" <<EOF
+#!/bin/sh
+exec node "$CLI_DIR/cli.js" "\$@"
+EOF
+else
+ cat > "$LAUNCHER.tmp" <<EOF
+#!/bin/sh
+# Local dev install, PINNED with --no-updates (see scripts/install-cli.sh).
+# Self-update is off: no release will ever reach this computer on its own, not even a newer one.
+# Re-run install-cli.sh without --no-updates (or the public installer) to rejoin the release train.
+ADAPTER_UPDATE_DISABLE=true
+export ADAPTER_UPDATE_DISABLE
+exec node "$CLI_DIR/cli.js" "\$@"
+EOF
+fi
+chmod 755 "$LAUNCHER.tmp"
+mv -f "$LAUNCHER.tmp" "$LAUNCHER"
+
+echo " ✓ installed $VER → $CLI_DIR"
+echo " launcher: $LAUNCHER$([ "$KEEP_UPDATES" -eq 1 ] && echo ' (self-update ON)' || echo ' (self-update OFF)')"
+
+# --- Step 6: bring the daemon back on the new bytes ---
+if [ "$WAS_RUNNING" -eq 1 ] && [ "$DO_RESTART" -eq 1 ]; then
+ echo ">> reconnecting on the new build…"
+ sleep 1 # grace for the backend to release the one-machine claim (as `harness update` does)
+ "$LAUNCHER" join
+elif [ "$WAS_RUNNING" -eq 1 ]; then
+ echo " (daemon stopped and NOT restarted — run: harness join)"
+else
+ echo " (no daemon was running — run \`harness join\` to connect, or \`harness join <token>\` on a fresh machine)"
+fi
+
+# --- Step 7: PATH hint (this script deliberately does not edit your shell rc) ---
+case ":${PATH}:" in
+ *":$BIN_DIR:"*) : ;;
+ *)
+ echo ""
+ echo " note: $BIN_DIR is not on PATH. For this shell:"
+ echo " export PATH=\"$BIN_DIR:\$PATH\""
+ ;;
+esac
diff --git a/cli/scripts/merge-manifest.mjs b/cli/scripts/merge-manifest.mjs
new file mode 100644
index 000000000..6494f4285
--- /dev/null
+++ b/cli/scripts/merge-manifest.mjs
@@ -0,0 +1,23 @@
+// Merge ONE key into the GCS metadata.json (download-merge-reupload), leaving other keys (e.g. the
+// device `commander` entry) untouched. Paths/values come via argv so no stdin/pipe is claimed.
+import { readFileSync, writeFileSync } from 'fs'
+
+const [src, dst, key, version, cliUrl, cliSha, cliSize, notifyUrl, notifySha, notifySize] =
+ process.argv.slice(2)
+
+let data = {}
+try {
+ const raw = readFileSync(src, 'utf8')
+ data = raw.trim() ? JSON.parse(raw) : {}
+} catch {
+ data = {}
+}
+if (typeof data !== 'object' || data === null || Array.isArray(data)) data = {}
+
+data[key] = {
+ version,
+ cli: { url: cliUrl, sha256: cliSha, size: Number(cliSize) },
+ notify: { url: notifyUrl, sha256: notifySha, size: Number(notifySize) },
+}
+
+writeFileSync(dst, JSON.stringify(data, null, 2) + '\n')
diff --git a/cli/scripts/upload-cli.sh b/cli/scripts/upload-cli.sh
new file mode 100755
index 000000000..d5c6f86b5
--- /dev/null
+++ b/cli/scripts/upload-cli.sh
@@ -0,0 +1,126 @@
+#!/usr/bin/env bash
+# Release the `harness` adapter CLI: bump version -> bundle -> upload to a PUBLIC GCS bucket.
+# Running daemons poll the manifest (ADAPTER_UPDATE_URL) and self-update within ~1 min. See RELEASE.md.
+#
+# Usage:
+# bash scripts/upload-cli.sh # auto-bump (0.0.1 -> 0.0.2; 0.0.99 -> 0.1.1)
+# bash scripts/upload-cli.sh 0.1.0 # release an explicit version
+# bash scripts/upload-cli.sh --no-bump # keep the current version, bundle + upload
+# bash scripts/upload-cli.sh --no-build # upload the existing dist/ artifact as-is
+# GCS_BUCKET=other bash scripts/upload-cli.sh # env overrides (see below)
+#
+# The CURRENT version is read from the remote metadata.json on GCS (single source of truth) and the
+# patch is bumped from there — nothing is git-committed (the version is injected into the bundle via
+# ADAPTER_VERSION, so the running binary's version equals the published manifest version).
+# Prereqs: `gsutil` authenticated with WRITE access; the bucket/objects must be public-read; `node`+`npm`.
+set -euo pipefail
+
+ADAPTER_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" # this package
+CLI="$ADAPTER_DIR/dist/cli.js"
+NOTIFY="$ADAPTER_DIR/dist/notify.mjs"
+
+# --- GCS config (all overridable via env) ---
+GCS_BUCKET="${GCS_BUCKET:-s3-autonomous-upgrade-3}"
+GCS_PUBLIC_BASE_URL="${GCS_PUBLIC_BASE_URL:-https://storage.googleapis.com/${GCS_BUCKET}}"
+METADATA_PATH="${METADATA_PATH:-harness/cli/metadata.json}"
+OTA_KEY="${OTA_KEY:-cli}" # must match ADAPTER_UPDATE_KEY in src/config/env.ts
+
+next_adapter_version() {
+ local current="$1" major minor patch
+ if [[ ! "$current" =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then
+ echo "error: version '$current' must look like X.Y.Z" >&2
+ return 1
+ fi
+ major=$((10#${BASH_REMATCH[1]}))
+ minor=$((10#${BASH_REMATCH[2]}))
+ patch=$((10#${BASH_REMATCH[3]}))
+ if (( patch >= 99 )); then
+ printf '%d.%d.1\n' "$major" "$((minor + 1))"
+ else
+ printf '%d.%d.%d\n' "$major" "$minor" "$((patch + 1))"
+ fi
+}
+
+# --- Parse args (optional explicit version + flags) ---
+NEW_VER=""
+DO_BUMP=1
+DO_BUILD=1
+for arg in "$@"; do
+ case "$arg" in
+ --no-bump) DO_BUMP=0 ;;
+ --no-build) DO_BUILD=0 ;;
+ -*) echo "error: unknown flag '$arg'" >&2; exit 1 ;;
+ *) NEW_VER="$arg" ;;
+ esac
+done
+
+command -v gsutil >/dev/null 2>&1 || { echo "error: gsutil not found — install/authenticate the gcloud SDK" >&2; exit 1; }
+command -v node >/dev/null 2>&1 || { echo "error: node not found" >&2; exit 1; }
+
+cleanup() { rm -f "${SRC:-}" "${DST:-}"; }
+trap cleanup EXIT
+
+# --- Step 1: resolve the version (source of truth = remote metadata.json; fallback = package.json) ---
+META_URL="${GCS_PUBLIC_BASE_URL%/}/${METADATA_PATH#/}"
+CUR="$(curl -fsSL "$META_URL" 2>/dev/null | node -e '
+let s=""; process.stdin.on("data",d=>s+=d).on("end",()=>{
+ try { process.stdout.write(String((JSON.parse(s)[process.argv[1]]||{}).version||"")) } catch { process.stdout.write("") }
+})' "$OTA_KEY" 2>/dev/null || true)"
+if [ -n "$CUR" ]; then
+ echo ">> current published version (from metadata.json): $CUR"
+else
+ CUR="$(node -p "require('$ADAPTER_DIR/package.json').version" 2>/dev/null || echo '0.0.0')"
+ echo ">> could not read remote metadata — falling back to package.json: $CUR" >&2
+fi
+if [ -n "$NEW_VER" ]; then
+ VER="$NEW_VER" # explicit version wins
+elif [ "$DO_BUMP" -eq 1 ]; then
+ VER="$(next_adapter_version "$CUR")"
+else
+ VER="$CUR" # --no-bump: keep current
+fi
+[[ "$VER" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo "error: version '$VER' must look like X.Y.Z" >&2; exit 1; }
+echo ">> releasing adapter version: $VER"
+
+# --- Step 2: bundle (version baked into the artifact) ---
+if [ "$DO_BUILD" -eq 1 ]; then
+ echo ">> bundling…"
+ ( cd "$ADAPTER_DIR" && ADAPTER_VERSION="$VER" npm run bundle )
+fi
+[ -f "$CLI" ] && [ -f "$NOTIFY" ] || { echo "error: dist/cli.js or dist/notify.mjs missing — bundle first (drop --no-build)" >&2; exit 1; }
+head -1 "$CLI" | grep -q '^#!' || { echo "error: dist/cli.js lost its shebang on line 1 (esbuild change?)" >&2; exit 1; }
+[ "$(node "$CLI" version)" = "$VER" ] || { echo "error: bundled version != $VER (ADAPTER_VERSION not injected)" >&2; exit 1; }
+
+# --- Step 3: upload both artifacts + merge the manifest ---
+CLI_GCS="harness/cli/${VER}/cli.js"
+NOTIFY_GCS="harness/cli/${VER}/notify.mjs"
+CLI_URL="${GCS_PUBLIC_BASE_URL%/}/${CLI_GCS}"
+NOTIFY_URL="${GCS_PUBLIC_BASE_URL%/}/${NOTIFY_GCS}"
+CLI_SHA="$(shasum -a 256 "$CLI" | awk '{print $1}')"; CLI_SIZE="$(wc -c < "$CLI" | tr -d ' ')"
+NOTIFY_SHA="$(shasum -a 256 "$NOTIFY" | awk '{print $1}')"; NOTIFY_SIZE="$(wc -c < "$NOTIFY" | tr -d ' ')"
+
+echo ">> uploading cli.js ($CLI_SIZE bytes) + notify.mjs ($NOTIFY_SIZE bytes)"
+gsutil -h "Cache-Control:no-cache, no-store, must-revalidate" cp "$CLI" "gs://${GCS_BUCKET}/${CLI_GCS}"
+gsutil -h "Cache-Control:no-cache, no-store, must-revalidate" cp "$NOTIFY" "gs://${GCS_BUCKET}/${NOTIFY_GCS}"
+
+echo ">> merging manifest: gs://${GCS_BUCKET}/${METADATA_PATH} (${OTA_KEY})"
+SRC="$(mktemp)"; DST="$(mktemp)" # removed by cleanup() on EXIT
+if ! gsutil cp "gs://${GCS_BUCKET}/${METADATA_PATH}" "$SRC" 2>/dev/null; then
+ echo " (no existing metadata.json — creating a new one)"
+ printf '{}' > "$SRC"
+fi
+# Pass paths/values via argv (NOT a heredoc through stdin — that would claim the pipe and blank the file).
+node "$ADAPTER_DIR/scripts/merge-manifest.mjs" \
+ "$SRC" "$DST" "$OTA_KEY" "$VER" \
+ "$CLI_URL" "$CLI_SHA" "$CLI_SIZE" \
+ "$NOTIFY_URL" "$NOTIFY_SHA" "$NOTIFY_SIZE"
+gsutil -h "Content-Type:application/json" \
+ -h "Cache-Control:no-cache, no-store, must-revalidate" \
+ cp "$DST" "gs://${GCS_BUCKET}/${METADATA_PATH}"
+
+echo ""
+echo ">> published adapter $VER"
+echo " cli: $CLI_URL (sha256 $CLI_SHA)"
+echo " notify: $NOTIFY_URL"
+echo " manifest: $META_URL"
+echo " running daemons self-update to $VER within ~1 min."
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
new file mode 100644
index 000000000..37852b73e
--- /dev/null
+++ b/cli/src/backendSocket.spec.ts
@@ -0,0 +1,338 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { BackendSocket, compactRuntimePickerModels, deviceAgentListItem } from './backendSocket.js'
+
+const wsMock = vi.hoisted(() => {
+ const instances: MockWebSocket[] = []
+
+ class MockWebSocket {
+ static CONNECTING = 0
+ static OPEN = 1
+ static CLOSED = 3
+ readyState = MockWebSocket.CONNECTING
+ sent: string[] = []
+ failNextSend: Error | null = null
+ private handlers = new Map<string, Array<(...args: unknown[]) => void>>()
+
+ constructor(readonly url: string, readonly protocols: string[]) {
+ instances.push(this)
+ }
+
+ on(event: string, cb: (...args: unknown[]) => void): this {
+ const list = this.handlers.get(event) ?? []
+ list.push(cb)
+ this.handlers.set(event, list)
+ return this
+ }
+
+ private emit(event: string, ...args: unknown[]): void {
+ for (const cb of this.handlers.get(event) ?? []) cb(...args)
+ }
+
+ open(): void {
+ this.readyState = MockWebSocket.OPEN
+ this.emit('open')
+ }
+
+ message(value: unknown): void {
+ this.emit('message', Buffer.from(JSON.stringify(value)))
+ }
+
+ send(data: string, cb?: (err?: Error) => void): void {
+ if (this.failNextSend) {
+ const err = this.failNextSend
+ this.failNextSend = null
+ cb?.(err)
+ return
+ }
+ this.sent.push(data)
+ cb?.()
+ }
+
+ close(): void {
+ this.readyState = MockWebSocket.CLOSED
+ this.emit('close', 1006)
+ }
+
+ terminate(): void {
+ this.close()
+ }
+
+ ping(): void {
+ this.emit('pong')
+ }
+ }
+
+ return { instances, MockWebSocket }
+})
+
+vi.mock('ws', () => ({ WebSocket: wsMock.MockWebSocket }))
+
+function parseSent(ws: InstanceType<typeof wsMock.MockWebSocket>): Array<Record<string, unknown>> {
+ return ws.sent.map((s) => JSON.parse(s) as Record<string, unknown>)
+}
+
+describe('BackendSocket outbound queue', () => {
+ afterEach(() => {
+ wsMock.instances.length = 0
+ vi.restoreAllMocks()
+ vi.useRealTimers()
+ })
+
+ it('queues web and device frames before open and flushes them in FIFO order', async () => {
+ const socket = new BackendSocket('token')
+ socket.connect()
+ const ws = wsMock.instances[0]
+
+ socket.send({ type: 'turn_summary_pending', dbSessionId: 's1', payload: { sessionId: 's1' } })
+ socket.sendCommander({ type: 'commander_event', agentId: 's1', dbSessionId: 's1', payload: { kind: 'done', text: 'done' } })
+ expect(ws.sent).toHaveLength(0)
+
+ ws.open()
+ const sent = parseSent(ws)
+ expect(sent).toHaveLength(2)
+ expect((sent[0].frame as { type?: string }).type).toBe('turn_summary_pending')
+ expect((sent[1].frame as { type?: string }).type).toBe('commander_event')
+ expect(sent[1]).toMatchObject({ webEligible: false, commanderEligible: true })
+
+ await socket.stop()
+ })
+
+ it('keeps a frame queued when ws.send reports an error and retries after reconnect', async () => {
+ vi.useFakeTimers()
+ const socket = new BackendSocket('token')
+ socket.connect()
+ const ws1 = wsMock.instances[0]
+ ws1.open()
+ ws1.failNextSend = new Error('boom')
+
+ socket.sendTo('conn-1', { type: 'e2e_rekey', payload: { n: 1 } })
+ expect(ws1.sent).toHaveLength(0)
+
+ await vi.advanceTimersByTimeAsync(1_000)
+ const ws2 = wsMock.instances[1]
+ ws2.open()
+ const sent = parseSent(ws2)
+ expect(sent).toHaveLength(1)
+ expect(sent[0]).toMatchObject({ t: 'up', targetConnId: 'conn-1' })
+
+ await socket.stop()
+ })
+
+ it('serves the opaque runtime catalog through the existing models_list RPC', async () => {
+ const socket = new BackendSocket('token')
+ socket.runtimeModelsProvider = async () => [
+ { id: 'runtime-v1:s1:codex:gpt-5.6-sol@high', displayName: 'GPT-5.6 Sol / High' },
+ ]
+ socket.connect()
+ const ws = wsMock.instances[0]
+ ws.open()
+ vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({
+ type: 'models_list', payload: { requestId: 'models-1' },
+ })
+ vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)
+ const wrapReply = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({
+ type: 'models_list_result', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } },
+ })
+ ws.message({
+ t: 'down',
+ connId: 'web-1',
+ frame: { type: 'models_list', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } } },
+ })
+
+ await vi.waitFor(() => {
+ const result = parseSent(ws).find((item) => (item.frame as { type?: string })?.type === 'models_list_result')
+ expect(result).toMatchObject({
+ targetConnId: 'web-1',
+ frame: { payload: { __e2e: { ct: 'ciphertext' } } },
+ })
+ })
+ expect(wrapReply).toHaveBeenCalledWith('web-1', 'models_list_result', 'models-1', {
+ models: [{ id: 'runtime-v1:s1:codex:gpt-5.6-sol@high', displayName: 'GPT-5.6 Sol / High' }],
+ })
+ await socket.stop()
+ })
+
+ it('filters and compacts the runtime catalog for a device agent', async () => {
+ const socket = new BackendSocket('token')
+ const provider = vi.fn(async (_sessionId?: string) => [
+ { id: 'runtime-v1:s1:codex:gpt-5.6-sol@high', displayName: 'GPT-5.6 Sol / High' },
+ { id: 'runtime-v1:s1:codex:gpt-5.6-sol@auto', displayName: 'GPT-5.6 Sol / Auto' },
+ { id: 'runtime-v1:s1:codex:o3@medium', displayName: 'o3 / Medium' },
+ { id: 'runtime-v1:s1:codex:o3@auto', displayName: 'o3 / Auto' },
+ ])
+ socket.runtimeModelsProvider = provider
+ socket.connect()
+ const ws = wsMock.instances[0]
+ ws.open()
+ vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({
+ type: 'models_list',
+ payload: {
+ requestId: 'models-compact',
+ agentId: 's1',
+ compact: true,
+ pickerMode: 'model',
+ selectedModel: 'runtime-v1:s1:codex:gpt-5.6-sol@high',
+ },
+ })
+ vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)
+ const wrapReply = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({
+ type: 'models_list_result', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } },
+ })
+ ws.message({
+ t: 'down',
+ connId: 'device-1',
+ frame: { type: 'models_list', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } } },
+ })
+
+ await vi.waitFor(() => {
+ expect(wrapReply).toHaveBeenCalledWith('device-1', 'models_list_result', 'models-compact', {
+ models: [
+ { id: 'runtime-v1:s1:codex:gpt-5.6-sol@high' },
+ { id: 'runtime-v1:s1:codex:o3@auto' },
+ ],
+ })
+ })
+ expect(provider).toHaveBeenCalledWith('s1')
+ await socket.stop()
+ })
+
+ it('fails a plaintext runtime catalog request closed before reading local data', async () => {
+ const socket = new BackendSocket('token')
+ const provider = vi.fn(async () => [
+ { id: 'runtime-v1:s1:codex:gpt-5.6-sol@high', displayName: 'sensitive' },
+ ])
+ socket.runtimeModelsProvider = provider
+ socket.connect()
+ const ws = wsMock.instances[0]
+ ws.open()
+ ws.message({
+ t: 'down', connId: 'unpaired-web',
+ frame: { type: 'models_list', payload: { requestId: 'plaintext-models' } },
+ })
+
+ await vi.waitFor(() => {
+ const result = parseSent(ws).find((item) => (item.frame as { type?: string })?.type === 'models_list_result')
+ expect(result).toMatchObject({
+ targetConnId: 'unpaired-web',
+ frame: { payload: { requestId: 'plaintext-models', error: 'E2EE_REQUIRED' } },
+ })
+ })
+ expect(provider).not.toHaveBeenCalled()
+ await socket.stop()
+ })
+
+ it('reports commander presence only when it crosses zero', async () => {
+ const socket = new BackendSocket('token')
+ const changes: boolean[] = []
+ socket.onCommanderPresenceChanged = (connected) => changes.push(connected)
+ socket.connect()
+ const ws = wsMock.instances[0]
+ ws.open()
+
+ const clients = (commander: number) => ws.message({
+ t: 'down', connId: '', frame: { type: '__clients', payload: { commander } },
+ })
+ clients(1)
+ clients(2)
+ clients(0)
+ clients(0)
+ clients(1)
+ expect(changes).toEqual([true, false, true])
+
+ await socket.stop()
+ expect(changes).toEqual([true, false, true, false])
+ })
+
+ // "The device is gone" reaches us two ways: the backend says so (`__clients` → 0), or our own link to
+ // the backend dies and we can no longer know. Both have to release the device's E2EE session — the
+ // dashboard's device dot reads `deviceE2eeConnected()`, so a session left behind reports a device that
+ // may have been gone for hours.
+ it('drops the device E2EE session when the count reaches zero', async () => {
+ const socket = new BackendSocket('token')
+ const drop = vi.spyOn(socket.e2ee, 'dropSessionsByRole')
+ socket.connect()
+ const ws = wsMock.instances[0]
+ ws.open()
+
+ ws.message({ t: 'down', connId: '', frame: { type: '__clients', payload: { commander: 1 } } })
+ expect(drop).not.toHaveBeenCalled()
+
+ ws.message({ t: 'down', connId: '', frame: { type: '__clients', payload: { commander: 0 } } })
+ expect(drop).toHaveBeenCalledWith('device')
+
+ await socket.stop()
+ })
+
+ it('drops the device E2EE session when OUR backend link dies, not just when the backend says so', async () => {
+ vi.useFakeTimers()
+ const socket = new BackendSocket('token')
+ const drop = vi.spyOn(socket.e2ee, 'dropSessionsByRole')
+ socket.connect()
+ const ws = wsMock.instances[0]
+ ws.open()
+
+ ws.message({ t: 'down', connId: '', frame: { type: '__clients', payload: { commander: 1 } } })
+ drop.mockClear()
+
+ ws.close() // transport gone — no `__clients` frame will ever tell us the device left
+ expect(socket.hasCommander()).toBe(false)
+ expect(drop).toHaveBeenCalledWith('device')
+
+ await socket.stop()
+ })
+})
+
+describe('compact runtime picker catalog', () => {
+ const models = [
+ { id: 'runtime-v1:s1:codex:gpt-5.6-sol@auto', displayName: 'Sol / Auto' },
+ { id: 'runtime-v1:s1:codex:gpt-5.6-sol@medium', displayName: 'Sol / Medium' },
+ { id: 'runtime-v1:s1:codex:gpt-5.6-sol@high', displayName: 'Sol / High' },
+ { id: 'runtime-v1:s1:codex:o3@high', displayName: 'o3 / High' },
+ { id: 'runtime-v1:s2:claude:sonnet@high', displayName: 'Sonnet / High' },
+ ]
+
+ it('returns only explicit efforts for the selected session model', () => {
+ expect(compactRuntimePickerModels(
+ models,
+ 's1',
+ 'effort',
+ 'runtime-v1:s1:codex:gpt-5.6-sol@medium',
+ )).toEqual([
+ { id: 'runtime-v1:s1:codex:gpt-5.6-sol@medium' },
+ { id: 'runtime-v1:s1:codex:gpt-5.6-sol@high' },
+ ])
+ })
+
+ it('caps the device model list and keeps the running model in it', () => {
+ // Devin publishes 72 models; a 49-row wheel already tripped the device's task watchdog once.
+ const many = Array.from({ length: 40 }, (_, i) => ({
+ id: `runtime-v1:s1:devin:model-${i}@auto`,
+ displayName: `Model ${i}`,
+ }))
+ const capped = compactRuntimePickerModels(many, 's1', 'model', 'runtime-v1:s1:devin:model-39@auto')
+
+ expect(capped).toHaveLength(24)
+ // The model the agent is running would have fallen off the end of the catalog order.
+ expect(capped[0]).toEqual({ id: 'runtime-v1:s1:devin:model-39@auto' })
+ // The web asks without a picker mode and still gets the whole catalog.
+ expect(compactRuntimePickerModels(many, 's1', undefined, null)).toHaveLength(40)
+ })
+})
+
+describe('device agent list contract', () => {
+ it('keeps the engine discriminator while trimming web-only fields', () => {
+ expect(deviceAgentListItem({ id: 's1', name: 'Codex agent', engine: 'codex', userId: 'secret' })).toEqual({
+ id: 's1', name: 'Codex agent', engine: 'codex',
+ })
+ })
+
+ it('surfaces the runtime-v1 model/effort profile so the device can render + change it', () => {
+ const profile = 'runtime-v1:s1:codex:gpt-5.6-sol@high'
+ expect(deviceAgentListItem({ id: 's1', name: 'A', engine: 'codex', selectedModel: profile })).toEqual({
+ id: 's1', name: 'A', engine: 'codex', selectedModel: profile,
+ })
+ expect(deviceAgentListItem({ id: 's1', name: 'A', engine: 'claude', selectedModel: null })).toEqual({
+ id: 's1', name: 'A', engine: 'claude', selectedModel: null,
+ })
+ })
+})
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
new file mode 100644
index 000000000..9186a36a2
--- /dev/null
+++ b/cli/src/backendSocket.ts
@@ -0,0 +1,1026 @@
+/**
+ * BackendSocket — the CLI's dial-out connection to the backend's `/api/adapter-ws`.
+ *
+ * The adapter occupies the NODE side of its agentId on the backend hub:
+ * - `up` { t:'up', frame } → normalized claude events + `<x>_result` RPC replies
+ * - `down` { t:'down', connId, frame } → web chat/control + data-plane RPC requests
+ *
+ * Mirrors the hosted runtime’s managerSocket: idempotent connect, exponential backoff (1s→30s),
+ * WS ping/pong keep-alive + a 15s app-level `{t:'ping'}` that refreshes the backend presence
+ * key, and a bounded FIFO queue for client-facing outbound frames.
+ *
+ * Auth: the connect token (agent apiKey) rides as the first WS subprotocol.
+ */
+
+import { WebSocket } from 'ws'
+import { stat, readFile } from 'fs/promises'
+import { join } from 'path'
+import { hostname } from 'os'
+import { createHash } from 'crypto'
+import { env } from './config/env.js'
+import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'
+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'
+import { opencodeMessagesToEvents, windowOpencodeMessages } from './engines/opencode/normalizer.js'
+import { piMessagesToEvents, windowPiLines } from './engines/pi/normalizer.js'
+import { commandcodeMessagesToEvents, windowCommandCodeLines } from './engines/commandcode/normalizer.js'
+import { hermesMessagesToEvents, windowHermesMessages } from './engines/hermes/normalizer.js'
+import { devinMessagesToEvents, windowDevinMessages } from './engines/devin/normalizer.js'
+import { readHermesMessages } from './engines/hermes/reader.js'
+import { readDevinMessages } from './engines/devin/reader.js'
+import { readOpencodeMessages } from './engines/opencode/reader.js'
+import { E2eeManager, type PairResult } from './lib/e2ee/manager.js'
+import { ENCRYPTED_RPC_RESULT_TYPES, isEncryptedDownType, isWrapped } from './lib/e2ee/core.js'
+import { DEVICE_RECENT_SAFE_FRAME_BYTES, fitRecentReplyPayloadForDevice } from './lib/deviceRecentTrim.js'
+import { shouldReplayCommander } from './lib/commanderReplay.js'
+import { RuntimeProfileControlError, type RuntimeProfileErrorCode } from './lib/runtimeProfileController.js'
+import { parseRuntimeProfile, type RuntimeModelOption } from './lib/runtimeProfile.js'
+import { sid, preview } from './lib/log.js'
+
+// OpenCode has no per-session transcript file — its history is read from this SQLite store.
+const OPENCODE_DB = join(env.OPENCODE_DATA_DIR, 'opencode.db')
+const DEVIN_DB = join(env.DEVIN_HOME, 'sessions.db')
+// Hermes history likewise comes from a SQLite store, not a per-session file.
+const HERMES_DB = join(env.HERMES_HOME, 'state.db')
+
+/** Answers the device `project_recent` RPC — set by cli.ts to the CommanderMirror's `recent`. */
+export type RecentProvider = (sessionId: string, n: number) => Array<{ kind: string; text: string; recap?: string }>
+
+
+const HEARTBEAT_MS = 20_000
+const APP_PING_MS = 15_000
+const BASE_DELAY_MS = 1_000
+const MAX_DELAY_MS = 30_000
+const QUEUE_MAX = 2_000
+const DEVICE_AGENT_LIST_LIMIT = 100
+const DEVICE_AGENT_NAME_MAX_CODEPOINTS = 15
+const DEVICE_AGENT_NAME_MAX_BYTES = 39 // device project_t.name[40], including trailing NUL on-device.
+const DEVICE_ELLIPSIS = '…'
+
+type Frame = Record<string, unknown>
+type OutboundEnvelope = Record<string, unknown>
+
+interface QueueItem {
+ id: number
+ data: string
+ msg: OutboundEnvelope
+ attempts: number
+}
+
+interface DownEnvelope {
+ t: 'down'
+ connId?: string
+ frame?: Frame
+}
+
+function byteLen(s: string): number {
+ return Buffer.byteLength(s, 'utf8')
+}
+
+function clipDeviceAgentName(input: string): string {
+ const chars = [...input]
+ if (chars.length <= DEVICE_AGENT_NAME_MAX_CODEPOINTS && byteLen(input) <= DEVICE_AGENT_NAME_MAX_BYTES) return input
+ const ellipsisBytes = byteLen(DEVICE_ELLIPSIS)
+ let out = ''
+ for (const ch of chars.slice(0, DEVICE_AGENT_NAME_MAX_CODEPOINTS)) {
+ if (byteLen(out) + byteLen(ch) + ellipsisBytes > DEVICE_AGENT_NAME_MAX_BYTES) break
+ out += ch
+ }
+ return `${out}${DEVICE_ELLIPSIS}`
+}
+
+export function deviceAgentListItem(
+ raw: unknown,
+): { id: unknown; name?: string; engine?: 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin'; selectedModel?: string | null } {
+ const o = (raw ?? {}) as Record<string, unknown>
+ const item: { id: unknown; name?: string; engine?: 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin'; selectedModel?: string | null } = { id: o.id }
+ if (typeof o.name === 'string') item.name = clipDeviceAgentName(o.name)
+ if (o.engine === 'claude' || o.engine === 'codex' || o.engine === 'cursor' || o.engine === 'opencode' || o.engine === 'pi' || o.engine === 'hermes' || o.engine === 'commandcode' || o.engine === 'devin') item.engine = o.engine
+ // Runtime model/effort profile (opaque runtime-v1:...) — lets the device render + change model/effort.
+ if (typeof o.selectedModel === 'string' || o.selectedModel === null) item.selectedModel = o.selectedModel
+ return item
+}
+
+/**
+ * How many models the DEVICE picker may receive. Matches its own PICK_MAX (ui_screens.c) so the wheel
+ * never renders more rows than it was built for; the web picker is unbounded and still gets everything.
+ */
+const DEVICE_PICKER_MAX_MODELS = 24
+
+export function compactRuntimePickerModels(
+ models: RuntimeModelOption[],
+ sessionId: string | undefined,
+ pickerMode: unknown,
+ selectedModel: unknown,
+): Array<{ id: string }> {
+ const compact = models.map(({ id }) => ({ id }))
+ if ((pickerMode !== 'model' && pickerMode !== 'effort') || !sessionId) return compact
+
+ const profiles = models.flatMap((item) => {
+ const profile = parseRuntimeProfile(item.id)
+ return profile?.sessionId === sessionId ? [{ item, profile }] : []
+ })
+ const selected = parseRuntimeProfile(selectedModel)
+ const current = selected?.sessionId === sessionId ? selected : null
+
+ if (pickerMode === 'effort') {
+ if (!current) return []
+ const seen = new Set<string>()
+ return profiles.flatMap(({ item, profile }) => {
+ if (profile.model !== current.model || profile.effort === 'auto' || seen.has(profile.effort)) return []
+ seen.add(profile.effort)
+ return [{ id: item.id }]
+ })
+ }
+
+ const byModel = new Map<string, typeof profiles>()
+ for (const entry of profiles) {
+ const group = byModel.get(entry.profile.model) ?? []
+ group.push(entry)
+ byModel.set(entry.profile.model, group)
+ }
+ const rows = [...byModel.values()].map((group) => {
+ const target = group.find(({ profile }) => current && profile.effort === current.effort)
+ ?? group.find(({ profile }) => profile.effort === 'auto')
+ ?? group[0]
+ return { id: target.item.id, model: target.profile.model }
+ })
+ // Top N only. The picker is a scroll wheel on a 1.9" round screen, and a 49-row one was enough to stall
+ // the device's the device UI task into a task-watchdog reset; devin alone publishes 72
+ // models. The catalog arrives in the engine's own order — its curated/most-used first — so "top" is that
+ // order, with the model the agent is RUNNING pinned in front so the list can never hide it.
+ const ordered = current
+ ? [...rows].sort((a, b) => Number(b.model === current.model) - Number(a.model === current.model))
+ : rows
+ return ordered.slice(0, DEVICE_PICKER_MAX_MODELS).map(({ id }) => ({ id }))
+}
+
+/** Fill in missing sub-agent aggregates on tool_end events by reading the sub-agent's own transcript
+ * (`<session>/subagents/agent-<id>.jsonl`). Async/background launchers only record
+ * `{status:'async_launched', agentId}` in the main transcript — without this join the delegation
+ * card shows "0 tools · worked for 0s" forever. Best-effort per agent; missing files are skipped. */
+async function enrichSubagentStats(events: SessionEvent[], transcriptPath: string): Promise<void> {
+ const subagentsDir = join(transcriptPath.replace(/\.jsonl$/, ''), 'subagents')
+ for (const e of events) {
+ if (e.type !== 'tool_end') continue
+ const sub = e.payload.subagent
+ if (!sub?.agentId || typeof sub.totalToolUseCount === 'number') continue
+ try {
+ const txt = await readFile(join(subagentsDir, `agent-${sub.agentId}.jsonl`), 'utf8')
+ const stats = subagentStatsFromRawLines(txt.split('\n'))
+ sub.totalToolUseCount = stats.totalToolUseCount
+ if (sub.totalDurationMs === undefined) sub.totalDurationMs = stats.totalDurationMs
+ if (sub.totalTokens === undefined) sub.totalTokens = stats.totalTokens
+ } catch { /* subagent transcript absent (still spawning / pruned) — leave as-is */ }
+ }
+}
+
+export class BackendSocket {
+ private ws: WebSocket | null = null
+ private token: string
+ private url: string
+ private attempts = 0
+ private closed = false
+ private queue: QueueItem[] = []
+ private draining = false
+ private nextQueueId = 1
+ private droppedSinceLog = 0
+ private heartbeat: NodeJS.Timeout | null = null
+ private appPing: NodeJS.Timeout | null = null
+ private isAlive = true
+ private onStatus: (connected: boolean) => void
+ /** Cross-instance commander (device) client count, from backend `__clients` frames. */
+ private commanderCount = 0
+ /** Subset of commanderCount whose device is ACTIVELY rendering this machine (multi-attach). null = the
+ * backend doesn't send the signal (old build) → fall back to hasCommander so streaming isn't gated off. */
+ private commanderActive: number | null = null
+ private replayedCommanderGeneration: number | undefined
+ private replayCommanderOnNextSnapshot = true
+ /** Called when a commander attach is observed — cli.ts replays live state. */
+ onCommanderJoin: (() => void) | null = null
+ /** Called only when commander presence crosses zero; drives the disposable recap-worker grace. */
+ 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. */
+ 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. */
+ onMessage: ((sessionId: string, content: 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
+ * 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
+ * upgrade) — cli clears the saved token and shuts the adapter down instead of retrying forever. */
+ onRevoked: (() => void) | null = null
+ /** Called with the machine's display name (`machine_meta` down-frame: seeded on connect, pushed on a
+ * web rename; null = unnamed) — cli mirrors it to a local file for `harness status`. */
+ onMachineMeta: ((name: string | null) => void) | null = null
+ /** Called when this machine is already connected from ANOTHER machine (HTTP 409 on the upgrade) — the
+ * credential is valid, just in use elsewhere, so cli keeps the token and stops (no retry loop). */
+ onBusy: (() => void) | null = null
+ /** Answers the device `project_recent` RPC (cli.ts wires this to CommanderMirror.recent). */
+ recentProvider: RecentProvider | null = null
+ /** Runtime Model/Effort integration, wired by cli.ts for registered tmux sessions. */
+ runtimeModelsProvider: ((sessionId?: string) => Promise<RuntimeModelOption[]>) | null = null
+ runtimeProfileProvider: ((session: RegisteredSession) => string | null) | null = null
+ onRuntimeProfileUpdate: ((sessionId: string, selectedModel: string) => Promise<void>) | null = null
+ /** Web↔adapter E2EE: group-encrypts user events, runs the CPace pairing, holds per-conn sessions. */
+ readonly e2ee: E2eeManager
+ /** agentId = sha256(token)[:32] — exposed for the local dashboard status. */
+ readonly machineId: string
+
+ /** The ONE place commander presence changes. Both callers — the `__clients` snapshot and `onGone` (our
+ * own backend link died) — mean the same thing when the count reaches zero: nobody is watching. They
+ * used to differ, and `onGone` forgot to drop the device's E2EE session, so `deviceE2eeConnected()`
+ * stayed true and the local dashboard kept a green "device connected" dot for a device long gone. */
+ private setCommanderCount(commander: number, active: number | null): void {
+ const hadCommander = this.commanderCount > 0
+ this.commanderCount = commander
+ this.commanderActive = active
+ if (hadCommander !== (commander > 0)) this.onCommanderPresenceChanged?.(commander > 0)
+ if (commander <= 0) this.e2ee.dropSessionsByRole('device')
+ }
+
+ /** True while at least one device (commander) client is connected — gates the LLM recap. */
+ hasCommander(): boolean {
+ return this.commanderCount > 0
+ }
+
+ /** True while at least one connected device is ACTIVELY rendering this machine — gates the full turn-card
+ * STREAM (processing/tool/todos). The recap still runs on hasCommander(), so a BACKGROUND machine gets its
+ * turn-done `summary` card (badge) without the live stream. Falls back to hasCommander() against a
+ * backend that doesn't emit the signal (commanderActive === null). */
+ hasActiveCommander(): boolean {
+ return this.commanderActive == null ? this.hasCommander() : this.commanderActive > 0
+ }
+
+ /** True after a paired device has completed the E2EE hello/welcome session. */
+ deviceE2eeConnected(): boolean {
+ return this.e2ee.deviceConnected()
+ }
+
+ /** Live backend link state (local dashboard + E2EE gating). */
+ isConnected(): boolean {
+ return this.ws?.readyState === WebSocket.OPEN
+ }
+
+ /** A browser waiting to pair (local dashboard), or null. */
+ pendingPair(): ReturnType<E2eeManager['pendingPair']> {
+ return this.e2ee.pendingPair()
+ }
+
+ /** Record the local dashboard port so it's surfaced to the web (in e2e_status) for approve-via-web. */
+ setDashboardPort(port: number): void {
+ this.e2ee.dashboardPort = port
+ }
+
+ constructor(token: string, onStatus: (connected: boolean) => void = () => {}, computerId = '') {
+ this.token = token
+ // `?label=<hostname>` lets the backend record which machine connected (shown on the machine card);
+ // `?computer=<stable id>` enforces one-computer-per-computer (a 2nd computer is rejected with HTTP 409).
+ const base = `${env.BACKEND_WS_URL.replace(/\/$/, '')}/api/adapter-ws?label=${encodeURIComponent(hostname())}`
+ this.url = computerId ? `${base}&computer=${encodeURIComponent(computerId)}` : base
+ this.onStatus = onStatus
+ this.machineId = createHash('sha256').update(token).digest('hex').slice(0, 32)
+ this.e2ee = new E2eeManager({
+ machineId: this.machineId,
+ sendTo: (connId, frame) => this.sendTo(connId, frame),
+ sendUser: (frame) => this.sendUser(frame),
+ isConnected: () => this.isConnected(),
+ })
+ }
+
+ /** Run CPace pairing for a code entered via `harness pair <code>` (delegated to the manager). */
+ pair(code: string): Promise<PairResult> {
+ return this.e2ee.onPair(code)
+ }
+ e2eeFingerprint(): string {
+ return this.e2ee.fingerprint()
+ }
+ createSetupToken(): ReturnType<E2eeManager['createSetupToken']> {
+ return this.e2ee.createSetupToken()
+ }
+ /** `harness pairings` — list paired clients. */
+ listPairs(): ReturnType<E2eeManager['listPaired']> {
+ return this.e2ee.listPaired()
+ }
+ /** `harness unpair <id>` — unpair one client (signals it to re-pair if online). */
+ revoke(id: string): ReturnType<E2eeManager['revoke']> {
+ return this.e2ee.revoke(id)
+ }
+ /** `harness unpair --all` — unpair every client. */
+ revokeAll(): ReturnType<E2eeManager['revokeAll']> {
+ return this.e2ee.revokeAll()
+ }
+
+ connect(): void {
+ if (this.closed || this.ws) return
+ const ws = new WebSocket(this.url, [this.token])
+ this.ws = ws
+
+ ws.on('open', () => {
+ this.attempts = 0
+ this.isAlive = true
+ console.log(`[backend] connected → ${this.url}`)
+ this.onStatus(true)
+ this.drainQueue()
+
+ this.heartbeat = setInterval(() => {
+ if (!this.isAlive) {
+ try { ws.terminate() } catch { /* ignore */ }
+ return
+ }
+ this.isAlive = false
+ try { ws.ping() } catch { /* ignore */ }
+ }, HEARTBEAT_MS)
+ ws.on('pong', () => { this.isAlive = true })
+
+ // App-level ping refreshes the backend's presence key (TTL 30s).
+ this.appPing = setInterval(() => this.sendBestEffort({ t: 'ping' }), APP_PING_MS)
+ })
+
+ ws.on('message', (raw) => {
+ let env_: DownEnvelope
+ try { env_ = JSON.parse(raw.toString()) as DownEnvelope } catch { return }
+ if (env_.t === 'down' && env_.frame) {
+ // A malformed/hostile down-frame (bad __e2e envelope, bad ephemeral key) can throw in the
+ // pre-`try` part of dispatchDown; without this .catch that becomes an unhandledRejection and the
+ // daemon exits. Contain it: log, drop the frame, keep the socket alive.
+ void this.dispatchDown(env_.frame, env_.connId ?? '').catch((err) =>
+ console.error('[backend] down-frame dispatch failed:', err instanceof Error ? err.message : err))
+ }
+ })
+
+ const onGone = (why: string): void => {
+ if (this.ws !== ws) return
+ this.ws = null
+ if (this.heartbeat) { clearInterval(this.heartbeat); this.heartbeat = null }
+ if (this.appPing) { clearInterval(this.appPing); this.appPing = null }
+ this.draining = false
+ // While the backend link is down we can neither observe device presence nor deliver a card, so
+ // default the recap gate to OFF (safe value) instead of holding a stale count — otherwise a turn
+ // completing during the gap burns a `claude -p` recap that goes nowhere. attachAdapter always
+ // re-pushes the true count via recomputeAndSendClients on reconnect (and 0→N re-fires the replay).
+ this.setCommanderCount(0, null) // active count is unknown until the next __clients snapshot
+ this.replayCommanderOnNextSnapshot = true
+ this.onStatus(false)
+ if (this.closed) return
+ const delay = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** Math.min(this.attempts++, 5))
+ console.log(`[backend] disconnected (${why}) — retrying in ${Math.round(delay / 1000)}s (attempt ${this.attempts})`)
+ setTimeout(() => this.connect(), delay)
+ }
+ ws.on('close', (code) => onGone(`close ${code}`))
+ ws.on('error', (err) => {
+ const e = err as Error & { code?: string }
+ const msg = e.message || e.code || String(err)
+ console.error('[backend] socket error:', msg)
+ // 401/403 on the upgrade = this machine is gone/invalid (deleted while we were offline, or a bad
+ // token). Retrying can't help → stop for good and let the CLI clear the saved token + shut down.
+ if (/Unexpected server response: 40[13]\b/.test(msg)) {
+ this.closed = true
+ this.onRevoked?.()
+ }
+ // 409 = one machine per machine: another computer already holds this machine. Keep the token; stop
+ // retrying (the 40[13] regex above deliberately excludes 409, so without this it would loop).
+ else if (/Unexpected server response: 409\b/.test(msg)) {
+ this.closed = true
+ this.onBusy?.()
+ }
+ try { ws.close() } catch { /* ignore */ }
+ })
+ }
+
+ async stop(): Promise<void> {
+ this.closed = true
+ if (this.heartbeat) clearInterval(this.heartbeat)
+ if (this.appPing) clearInterval(this.appPing)
+ try { this.ws?.close() } catch { /* ignore */ }
+ this.ws = null
+ }
+
+ /** Send an up-frame (event or RPC reply) to the WEB audience. Queued while disconnected.
+ * User-content events are group-encrypted (E2EE) here; system frames pass through as plaintext. */
+ send(frame: Frame): void {
+ this.enqueue({ t: 'up', frame: this.e2ee.wrapUp(frame) })
+ }
+
+ /** Send an up-frame to exactly ONE web connection (E2EE pairing/welcome + targeted RPC replies). */
+ sendTo(connId: string, frame: Frame): void {
+ this.enqueue({ t: 'up', targetConnId: connId, frame })
+ }
+
+ /** Send a user-level notification to every logged-in browser that owns this machine. */
+ sendUser(frame: Frame): void {
+ this.enqueue({ t: 'up', userEligible: true, webEligible: false, frame })
+ }
+
+ /** Send a DEVICE-audience frame (commanderEligible, not web). User/data frames are group-encrypted
+ * (E2EE) here so the backend relays only ciphertext; system/presence frames pass through. */
+ sendCommander(frame: Frame): void {
+ this.enqueue({ t: 'up', webEligible: false, commanderEligible: true, frame: this.e2ee.wrapCommander(frame) })
+ }
+
+ private enqueue(msg: OutboundEnvelope): void {
+ const item: QueueItem = { id: this.nextQueueId++, data: JSON.stringify(msg), msg, attempts: 0 }
+ if (this.queue.length >= QUEUE_MAX) this.dropOneQueued()
+ if (this.queue.length >= QUEUE_MAX) {
+ this.droppedSinceLog++
+ this.logQueueDrops()
+ return
+ }
+ this.queue.push(item)
+ this.drainQueue()
+ }
+
+ private sendBestEffort(msg: OutboundEnvelope): void {
+ const data = JSON.stringify(msg)
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
+ try { this.ws.send(data) } catch { /* ignore */ }
+ }
+ }
+
+ private drainQueue(): void {
+ if (this.draining || !this.queue.length) return
+ const ws = this.ws
+ if (!ws || ws.readyState !== WebSocket.OPEN) return
+ const item = this.queue[0]
+ this.draining = true
+ try {
+ ws.send(item.data, (err?: Error) => {
+ if (this.ws !== ws) return
+ if (err) {
+ item.attempts++
+ this.draining = false
+ console.error(`[backend] queued send failed (id=${item.id}, attempts=${item.attempts}):`, err.message)
+ try { ws.close() } catch { /* ignore */ }
+ return
+ }
+ if (this.queue[0] === item) this.queue.shift()
+ this.draining = false
+ this.drainQueue()
+ })
+ } catch (err) {
+ item.attempts++
+ this.draining = false
+ console.error(`[backend] queued send threw (id=${item.id}, attempts=${item.attempts}):`, err instanceof Error ? err.message : err)
+ try { ws.close() } catch { /* ignore */ }
+ }
+ }
+
+ private dropOneQueued(): void {
+ const idx = this.queue.findIndex((item) => !('targetConnId' in item.msg))
+ const dropAt = idx >= 0 ? idx : 0
+ if (this.queue.splice(dropAt, 1).length) {
+ this.droppedSinceLog++
+ this.logQueueDrops()
+ }
+ }
+
+ private logQueueDrops(): void {
+ if (this.droppedSinceLog === 1 || this.droppedSinceLog % 100 === 0) {
+ console.warn(`[backend] outbound queue full; dropped ${this.droppedSinceLog} frame(s) so far`)
+ }
+ }
+
+ // ── down-frame dispatch (the hosted runtime-role RPC switch) ────────────────────────────────────────────
+
+ /** Emit an RPC reply. For an E2EE-session requester whose result carries user content, the reply is
+ * encrypted with that connection's session key and delivered ONLY to it. Content-bearing adapter data
+ * is never returned plaintext: even legacy backend nodeRequest (`connId === ''`) gets only an error. */
+ private emitReply(connId: string, type: string, requestId: unknown, payload: Record<string, unknown>): void {
+ const resultType = `${type}_result`
+ if (connId && this.e2ee.hasSession(connId) && ENCRYPTED_RPC_RESULT_TYPES.has(resultType)) {
+ let replyPayload = payload
+ if (resultType === 'agent_recent_result') {
+ const trim = fitRecentReplyPayloadForDevice(
+ payload,
+ (candidate) => this.e2ee.rpcReplyFrameBytes(connId, resultType, requestId, candidate),
+ )
+ replyPayload = trim.payload
+ if (trim.trimmed) {
+ console.warn(
+ `[recent-trim] agent=${String(payload.agentId ?? '')} originalFrame=${trim.originalBytes ?? 'unknown'} ` +
+ `finalFrame=${trim.finalBytes ?? 'unknown'} target=${DEVICE_RECENT_SAFE_FRAME_BYTES} ` +
+ `textBytes=${trim.textBytes} recapBytes=${trim.recapBytes}`,
+ )
+ }
+ }
+ const wrapped = this.e2ee.wrapRpcReply(connId, resultType, requestId, replyPayload)
+ if (wrapped) { this.sendTo(connId, wrapped); return }
+ }
+ // Enforcement ("no E2EE ⇒ no adapter data"): content-bearing RPC replies must never leave the
+ // adapter plaintext. A real client gets a targeted error; the legacy backend nodeRequest awaiter
+ // (`connId === ''`) gets a broadcast error with the same requestId so it fails closed without data.
+ //
+ if (ENCRYPTED_RPC_RESULT_TYPES.has(resultType)) {
+ const errorFrame = { type: resultType, payload: { requestId, error: 'E2EE_REQUIRED' } }
+ if (connId) this.sendTo(connId, errorFrame)
+ else this.send(errorFrame)
+ return
+ }
+ this.send({ type: resultType, payload: { requestId, ...payload } })
+ }
+
+ private async dispatchDown(frame: Frame, connId: string): Promise<void> {
+ const type = frame.type as string | undefined
+ if (!type) return
+ // E2EE control frames (pairing/handshake) are handled by the manager, never as node RPCs.
+ if (type.startsWith('e2e_')) { this.e2ee.handleFrame(connId, frame); return }
+ // Client→adapter encrypted frames: chat messages plus trusted web control actions. Plaintext
+ // passes through for legacy/device transition paths; undecryptable ciphertext is dropped.
+ if (isEncryptedDownType(type)) {
+ if (type !== 'message' && type !== 'question_response' && !isWrapped(frame.payload)) {
+ const requestId = (frame.payload as { requestId?: unknown } | undefined)?.requestId
+ if (requestId !== undefined) this.emitReply(connId, type, requestId, { error: 'E2EE_REQUIRED' })
+ return
+ }
+ const dec = this.e2ee.unwrapDown(connId, frame)
+ if (!dec) return
+ frame = dec
+ }
+ const reply = (t: string, rid: unknown, p: Record<string, unknown>): void => this.emitReply(connId, t, rid, p)
+ // Cross-instance client snapshot. Generation detects leave/join cycles that coalesce to the same
+ // count; count rise remains the compatibility fallback for older backends.
+ if (type === '__clients') {
+ const payload = (frame.payload ?? {}) as { commander?: number; commanderActive?: number; commanderJoinGeneration?: number }
+ const commander = Number(payload.commander ?? 0)
+ const rawGeneration = payload.commanderJoinGeneration
+ const generation = typeof rawGeneration === 'number' && Number.isSafeInteger(rawGeneration) && rawGeneration >= 0
+ ? rawGeneration
+ : undefined
+ const replay = shouldReplayCommander(
+ this.commanderCount,
+ commander,
+ this.replayedCommanderGeneration,
+ generation,
+ this.replayCommanderOnNextSnapshot,
+ )
+ this.setCommanderCount(commander, payload.commanderActive != null ? Number(payload.commanderActive) : null)
+ if (replay) {
+ this.replayCommanderOnNextSnapshot = false
+ if (generation != null) this.replayedCommanderGeneration = generation
+ this.onCommanderJoin?.()
+ }
+ return
+ }
+ // Other backend-hub internal control frames (__clients_dirty) — not for us; drop silently.
+ if (type.startsWith('__')) return
+
+ // The machine was deleted/revoked from the web → stop for good (don't reconnect) and let the CLI
+ // clear the saved token. `closed` blocks the reconnect that would otherwise fire on socket drop.
+ if (type === 'machine_revoked') { this.closed = true; this.onRevoked?.(); return }
+
+ // Machine display name (seed on connect + web renames) — mirrored locally for `harness status`.
+ if (type === 'machine_meta') {
+ const name = (frame.payload as { name?: unknown } | undefined)?.name
+ this.onMachineMeta?.(typeof name === 'string' && name.trim() ? name.trim() : null)
+ return
+ }
+
+ const payload = (frame.payload ?? {}) as Record<string, unknown>
+ const requestId = payload.requestId
+
+ try {
+ switch (type) {
+ case 'device_e2ee_pair':
+ await this.e2ee.pairDeviceFromTrustedWeb(connId, payload)
+ return
+
+ case 'e2ee_pairings_list':
+ reply(type, requestId, { pairs: this.e2ee.listPaired(connId) })
+ return
+
+ case 'e2ee_pairing_unpair':
+ this.e2ee.revokeFromTrustedWeb(connId, payload)
+ return
+
+ case 'e2ee_pairings_unpair_all':
+ this.e2ee.revokeAllFromTrustedWeb(connId, requestId)
+ return
+
+ case 'e2ee_browser_link_create': {
+ const setup = this.e2ee.createSetupToken()
+ reply(type, requestId, setup)
+ return
+ }
+
+ case 'agents_list': {
+ const projects = await Promise.all(registry.list().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))
+ if (this.e2ee.sessionRole(connId) === 'device') {
+ reply(type, requestId, { agents: projects.slice(0, DEVICE_AGENT_LIST_LIMIT).map(deviceAgentListItem) })
+ return
+ }
+ reply(type, requestId, { agents: projects })
+ return
+ }
+
+ case 'sessions_list': {
+ const projectId = payload.agentId as string | undefined
+ if (!projectId) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }
+ const s = registry.resolve(projectId)
+ // An agent whose engine has not reported a session yet has no transcript to list. Saying so
+ // plainly beats inventing one: the web then shows the tab with an empty thread until the bind
+ // lands, instead of pinning `currentSessionId` to an id no event will ever carry.
+ if (!s || !s.sessionId) { reply(type, requestId, { sessions: [] }); return }
+ const lines = s.transcriptPath ? await tailFile(s.transcriptPath, Infinity) : []
+ const st = s.transcriptPath ? await stat(s.transcriptPath).catch(() => null) : null
+ reply(type, requestId, {
+ sessions: [{
+ id: s.sessionId,
+ title: projectDisplayName(s),
+ timestamp: new Date(s.registeredAt).toISOString(),
+ messageCount: lines.length,
+ lastActivity: new Date(st?.mtimeMs ?? s.updatedAt).toISOString(),
+ participants: [],
+ }],
+ })
+ return
+ }
+
+ case 'session_get': {
+ const sessionId = payload.sessionId as string | undefined
+ if (!sessionId) { reply(type, requestId, { error: 'MISSING_SESSION_ID' }); return }
+ // Only serve transcripts for a REGISTERED tmux session, read from its own trusted
+ // transcriptPath — never resolve an arbitrary request-supplied id to a file (that let a
+ // caller read any *.jsonl on the computer, incl. unshared claude history / traversal).
+ const s = registry.resolve(sessionId)
+ if (!s) { reply(type, requestId, { error: 'NOT_FOUND' }); return }
+ if (s.engine === 'devin') {
+ // Devin history comes from its SQLite store (no transcript file). Same replay/window shape.
+ const rawLimit = payload.limit
+ const limit = typeof rawLimit === 'number' && rawLimit > 0 ? Math.min(Math.floor(rawLimit), 500) : undefined
+ const before = typeof payload.before === 'string' ? payload.before : undefined
+ const messages = await readDevinMessages(DEVIN_DB, sessionId)
+ const timestamp = new Date(s.updatedAt).toISOString()
+ if (!limit) {
+ reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events: devinMessagesToEvents(messages), timestamp, engine: s.engine })
+ return
+ }
+ const w = windowDevinMessages(messages, { limit, before })
+ if (w.staleCursor) {
+ reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events: [], timestamp, engine: s.engine, hasMore: false, oldestCursor: null, staleCursor: true })
+ return
+ }
+ const events = devinMessagesToEvents(w.window)
+ if (before && events[events.length - 1]?.type === 'done') events.pop()
+ reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events, timestamp, engine: s.engine, hasMore: w.hasMore, oldestCursor: w.oldestCursor })
+ return
+ }
+ if (s.engine === 'hermes') {
+ // Hermes history lives in its SQLite store (no transcript file). Same replay/window shape.
+ const rawLimit = payload.limit
+ const limit = typeof rawLimit === 'number' && rawLimit > 0 ? Math.min(Math.floor(rawLimit), 500) : undefined
+ const before = typeof payload.before === 'string' ? payload.before : undefined
+ const messages = await readHermesMessages(HERMES_DB, sessionId)
+ const timestamp = new Date(s.updatedAt).toISOString()
+ if (!limit) {
+ reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events: hermesMessagesToEvents(messages), timestamp, engine: s.engine })
+ return
+ }
+ const w = windowHermesMessages(messages, { limit, before })
+ if (w.staleCursor) {
+ reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events: [], timestamp, engine: s.engine, hasMore: false, oldestCursor: null, staleCursor: true })
+ return
+ }
+ const events = hermesMessagesToEvents(w.window)
+ if (before && events[events.length - 1]?.type === 'done') events.pop()
+ reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events, timestamp, engine: s.engine, hasMore: w.hasMore, oldestCursor: w.oldestCursor })
+ return
+ }
+ if (s.engine === 'opencode') {
+ // OpenCode history comes from its SQLite DB (no transcript file). Same replay/window shape.
+ const rawLimit = payload.limit
+ const limit = typeof rawLimit === 'number' && rawLimit > 0 ? Math.min(Math.floor(rawLimit), 500) : undefined
+ const before = typeof payload.before === 'string' ? payload.before : undefined
+ const messages = await readOpencodeMessages(OPENCODE_DB, sessionId)
+ const timestamp = new Date(s.updatedAt).toISOString()
+ if (!limit) {
+ reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events: opencodeMessagesToEvents(messages), timestamp, engine: s.engine })
+ return
+ }
+ const w = windowOpencodeMessages(messages, { limit, before })
+ if (w.staleCursor) {
+ reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events: [], timestamp, engine: s.engine, hasMore: false, oldestCursor: null, staleCursor: true })
+ return
+ }
+ const events = opencodeMessagesToEvents(w.window)
+ if (before && events[events.length - 1]?.type === 'done') events.pop()
+ reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events, timestamp, engine: s.engine, hasMore: w.hasMore, oldestCursor: w.oldestCursor })
+ return
+ }
+ if (!s.transcriptPath) {
+ reply(type, requestId, {
+ id: sessionId,
+ title: projectDisplayName(s),
+ events: [],
+ timestamp: new Date(s.updatedAt).toISOString(),
+ engine: s.engine,
+ hasMore: false,
+ oldestCursor: null,
+ })
+ return
+ }
+ // Optional pagination: `limit` = window size; `before` = uuid cursor (oldest line the
+ // client already holds). Absent → full transcript (legacy). Clamp limit defensively.
+ const rawLimit = payload.limit
+ const limit = typeof rawLimit === 'number' && rawLimit > 0 ? Math.min(Math.floor(rawLimit), 500) : undefined
+ const before = typeof payload.before === 'string' ? payload.before : undefined
+ const lines = await tailFile(s.transcriptPath, Infinity)
+ const st = await stat(s.transcriptPath).catch(() => null)
+ const timestamp = new Date(st?.mtimeMs ?? Date.now()).toISOString()
+
+ if (!limit) {
+ const fullEvents = s.engine === 'codex'
+ ? codexMessagesToEvents(lines)
+ : s.engine === 'cursor'
+ ? cursorMessagesToEvents(lines, sessionId, await loadCursorReplayTaskLinks(env.CURSOR_HOME, sessionId))
+ : s.engine === 'pi'
+ ? piMessagesToEvents(lines)
+ : s.engine === 'commandcode'
+ ? commandcodeMessagesToEvents(lines)
+ : messagesToEvents(lines)
+ if (s.engine !== 'cursor' && s.engine !== 'pi' && s.engine !== 'commandcode') await enrichSubagentStats(fullEvents, s.transcriptPath)
+ reply(type, requestId, {
+ id: sessionId,
+ title: projectDisplayName(s),
+ events: fullEvents,
+ timestamp,
+ engine: s.engine,
+ })
+ return
+ }
+
+ const w = s.engine === 'codex'
+ ? windowCodexLines(lines, { limit, before })
+ : s.engine === 'cursor'
+ ? windowCursorLines(lines, { limit, before })
+ : s.engine === 'pi'
+ ? windowPiLines(lines, { limit, before })
+ : s.engine === 'commandcode'
+ ? windowCommandCodeLines(lines, { limit, before })
+ : windowRawLines(lines, { limit, before })
+ if (w.staleCursor) {
+ reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events: [], timestamp, engine: s.engine, hasMore: false, oldestCursor: null, staleCursor: true })
+ return
+ }
+ const events = s.engine === 'codex'
+ ? codexMessagesToEvents(w.window)
+ : s.engine === 'cursor'
+ ? cursorMessagesToEvents(
+ w.window,
+ sessionId,
+ await loadCursorReplayTaskLinks(env.CURSOR_HOME, sessionId),
+ 'startIndex' in w && typeof w.startIndex === 'number' ? w.startIndex : 0,
+ 'initialTodos' in w && Array.isArray(w.initialTodos) ? w.initialTodos : [],
+ )
+ : s.engine === 'pi'
+ ? piMessagesToEvents(w.window)
+ : s.engine === 'commandcode'
+ ? commandcodeMessagesToEvents(w.window)
+ : messagesToEvents(w.window)
+ if (s.engine !== 'cursor' && s.engine !== 'pi' && s.engine !== 'commandcode') await enrichSubagentStats(events, s.transcriptPath)
+ // Older pages must not inject a spurious end-of-transcript marker mid-scroll.
+ if (before && events[events.length - 1]?.type === 'done') events.pop()
+ reply(type, requestId, {
+ id: sessionId,
+ title: projectDisplayName(s),
+ events,
+ timestamp,
+ engine: s.engine,
+ hasMore: w.hasMore,
+ oldestCursor: w.oldestCursor,
+ })
+ return
+ }
+
+ case 'models_list': {
+ const sessionId = typeof payload.agentId === 'string' && payload.agentId
+ ? payload.agentId
+ : undefined
+ const models = this.runtimeModelsProvider
+ ? await this.runtimeModelsProvider(sessionId)
+ : [{ id: 'default', displayName: 'Remote CLI default' }]
+ reply(type, requestId, {
+ // The device derives labels from the opaque runtime-v1 id. Omitting the duplicate
+ // displayName keeps the encrypted picker response below its 16 KiB decrypt cap.
+ models: payload.compact === true
+ ? compactRuntimePickerModels(models, sessionId, payload.pickerMode, payload.selectedModel)
+ : models,
+ })
+ return
+ }
+
+ case 'agent_recent': {
+ // Device tile restore at boot: the session's persisted LLM turn-summary (recap + body),
+ // mirroring the hosted runtime’s SessionService.getRecentEvents. Empty until a turn was summarized
+ // (device-gated) — never a resurrected full-text card.
+ const projectId = payload.agentId as string | undefined
+ if (!projectId) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }
+ const n = Math.max(1, Math.min(5, Number(payload.n) || 2))
+ const events = this.recentProvider ? this.recentProvider(projectId, n) : []
+ reply(type, requestId, { agentId: projectId, events })
+ return
+ }
+
+ case 'voice_route': {
+ // Voice router (REMOTE machine): pick the best-fit agent for a transcribed Overview voice task,
+ // using each agent's name + recent-turn recap. Backend-originated (connId===''), so the transcript
+ // is plaintext and the reply falls through emitReply's plaintext path (voice_route is not E2EE-gated).
+ const transcript = typeof payload.transcript === 'string' ? payload.transcript : ''
+ if (!transcript.trim()) {
+ console.log('[voice-route] backend sent an empty transcript — nothing to route')
+ 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 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.
+ const recents = this.recentProvider?.(p.id, 3) ?? []
+ const recentSummary = recents.map((r) => r?.recap || r?.text || '').filter(Boolean).join(' · ')
+ // engine: the router classifies with a CLI the machine actually runs (a live agent proves it is
+ // installed and logged in), so it has to travel with the agent.
+ return { id: p.id, name: p.name, recentSummary, engine: registry.resolve(p.id)?.engine }
+ })
+ const decision = await routeVoiceTask(transcript, agents) // logs the task, candidates and pick
+ const chosen = projects.find((p) => p.id === decision.agentId)
+ reply(type, requestId, { ...decision, agentName: chosen?.name ?? '' })
+ return
+ }
+
+ case 'agent_update': {
+ const projectId = payload.agentId as string | undefined
+ if (!projectId) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }
+ const hasName = Object.prototype.hasOwnProperty.call(payload, 'name')
+ const hasProfile = Object.prototype.hasOwnProperty.call(payload, 'selectedModel')
+ if (!hasName && !hasProfile) { reply(type, requestId, { error: 'MISSING_UPDATE' }); return }
+ const name = typeof payload.name === 'string' ? payload.name.trim() : ''
+ if (hasName && !name) { reply(type, requestId, { error: 'MISSING_NAME' }); return }
+ let s = registry.resolve(projectId)
+ if (!s) { reply(type, requestId, { error: 'AGENT_NOT_FOUND' }); return }
+ if (hasProfile) {
+ if (typeof payload.selectedModel !== 'string' || !this.onRuntimeProfileUpdate) {
+ reply(type, requestId, { error: 'INVALID_RUNTIME_PROFILE' })
+ return
+ }
+ try {
+ await this.onRuntimeProfileUpdate(projectId, payload.selectedModel)
+ } catch (error) {
+ const code: RuntimeProfileErrorCode | 'INTERNAL' = error instanceof RuntimeProfileControlError ? error.code : 'INTERNAL'
+ reply(type, requestId, { error: code })
+ return
+ }
+ }
+ if (hasName) s = registry.rename(projectId, name) ?? s
+ const agent = await this.toProject(s)
+ reply(type, requestId, { agent })
+ if (hasName) {
+ const renamed = { type: 'agent_renamed', payload: { agentId: s.agentId, name, engine: s.engine } }
+ this.send(renamed) // every OTHER web client on this machine (group-encrypted)
+ this.sendCommander(renamed) // and the device
+ // The whole rename path was silent end to end, which is why "web1 renamed it, web2 never saw
+ // it" had no evidence to work from: nothing said whether the request even arrived. One line
+ // here splits the question in two — no line means it never reached the adapter, a line means
+ // the fan-out is downstream.
+ console.log(`[rename] ${sid(projectId)} → "${preview(name, 40)}" · broadcast to web + device`)
+ }
+ return
+ }
+
+ // A project IS a tmux session; the web/device can't 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
+ // 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': {
+ const target = (payload.agentId as string | undefined) || (payload.sessionId as string | undefined)
+ if (!target) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }
+ this.onDeleteAgent?.(target)
+ reply(type, requestId, { deleted: true })
+ return
+ }
+
+ case 'agent_files': {
+ // SourceTree list — rooted at the tmux session's working dir.
+ const projectId = payload.agentId as string | undefined
+ if (!projectId) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }
+ const s = registry.resolve(projectId)
+ if (!s?.cwd) { reply(type, requestId, { error: 'AGENT_NOT_FOUND' }); return }
+ try { reply(type, requestId, { files: listFileTree(s.cwd) }) }
+ catch (e) { reply(type, requestId, { error: e instanceof Error ? e.message : 'FILE_TREE_ERROR' }) }
+ return
+ }
+
+ case 'agent_read_file': {
+ // View one file — ≤5MB, text-only (mirror the hosted runtime’s guard).
+ const projectId = payload.agentId as string | undefined
+ const path = payload.path as string | undefined
+ if (!projectId || !path) { reply(type, requestId, { error: 'MISSING_AGENT_OR_PATH' }); return }
+ const s = registry.resolve(projectId)
+ if (!s?.cwd) { reply(type, requestId, { error: 'AGENT_NOT_FOUND' }); return }
+ try { reply(type, requestId, { path, content: readProjectFile(s.cwd, path) }) }
+ catch (e) { reply(type, requestId, { error: e instanceof Error ? e.message : 'NOT_FOUND' }) }
+ return
+ }
+
+ case 'claude_login_status':
+ // Legacy RPC name; report the selected agent's actual engine when one was supplied.
+ {
+ const target = (payload.agentId as string | undefined) || (payload.sessionId as string | undefined)
+ reply(type, requestId, { loggedIn: true, engine: (target ? registry.resolve(target)?.engine : undefined) ?? 'claude', account: hostname() })
+ }
+ return
+
+ case 'message': {
+ const content = payload.content as string | undefined
+ const target = (payload.agentId as string | undefined) || (payload.sessionId as string | undefined)
+ if (!content || !target) return
+ // Inject into the pane; the resulting JSONL user/assistant lines drive the turn lifecycle back
+ // 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) }
+ return
+ }
+
+ case 'cancel': {
+ const target = (payload.agentId as string | undefined) || (payload.sessionId as string | undefined)
+ if (target) this.onCancel?.(target)
+ return
+ }
+
+ case 'speaking': {
+ // A device is capturing a voice instruction. Mirror the hosted runtime: re-broadcast the presence
+ // signal to the web (indicator) + other devices. Ephemeral, no requestId.
+ const p = payload as { speaking?: boolean; agentId?: string; sessionId?: string }
+ const sessionId = p.sessionId ?? p.agentId
+ const projectId = p.agentId ?? p.sessionId ?? null
+ const on = p.speaking !== false
+ // Echo the canonical agent id, whichever id the sender used to address it.
+ const speaker = projectId ? registry.resolve(projectId) : undefined
+ const speakerAgentId = speaker?.agentId ?? projectId
+ const evt = { type: 'speaking', dbSessionId: speaker?.sessionId ?? sessionId, agentId: speakerAgentId, payload: { speaking: on, agentId: speakerAgentId, sessionId: speaker?.sessionId ?? sessionId } }
+ this.send(evt) // web
+ this.sendCommander(evt) // other devices (firmware ignores its own echo; matches node forwardToCommander)
+ return
+ }
+
+ case 'question_response': {
+ // A device answered an AskUserQuestion. There's no control channel into an interactive CLI, so
+ // cli.ts keys the answer straight into that session's tmux dialog.
+ const p = payload as { requestId?: string; sessionId?: string; agentId?: string; answers?: Record<string, string> }
+ this.onQuestionAnswer?.(p)
+ return
+ }
+
+ // v1 no-ops: no programmatic session control over an interactive tmux claude.
+ case 'new_chat':
+ case 'compact':
+ case 'permission_response':
+ return
+
+ default:
+ // Unknown RPC with a requestId: reject fast so the web promise doesn't wait out its 20s.
+ if (requestId !== undefined) reply(type, requestId, { error: 'UNSUPPORTED' })
+ return
+ }
+ } catch (err) {
+ console.error(`[backend] dispatch ${type} failed:`, err)
+ if (requestId !== undefined) reply(type, requestId, { error: 'INTERNAL' })
+ }
+ }
+
+ /** 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
+ }> {
+ const st = s.transcriptPath ? await stat(s.transcriptPath).catch(() => null) : null
+ return {
+ id: s.agentId,
+ userId: '',
+ name: projectDisplayName(s),
+ status: 'active',
+ createdAt: new Date(s.registeredAt).toISOString(),
+ updatedAt: new Date(st?.mtimeMs ?? s.updatedAt).toISOString(),
+ tmuxPane: s.tmuxPane,
+ engine: s.engine,
+ selectedModel: this.runtimeProfileProvider?.(s) ?? null,
+ }
+ }
+}
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
new file mode 100644
index 000000000..b85ae27fb
--- /dev/null
+++ b/cli/src/cli.ts
@@ -0,0 +1,2403 @@
+#!/usr/bin/env node
+/**
+ * machine-adapter CLI (the `harness` command) — connect this computer to a "remote" agent.
+ *
+ * Terminology: the MACHINE *joins* a machine (`join <token>` → saved apiKey); a BROWSER
+ * *pairs* with the computer for end-to-end encryption (`pair`/`unpair`/`pairings`, code + fingerprint).
+ * Keeping "pair" for the browser relationship only avoids overloading the word across two trust relations.
+ *
+ * harness join <token> connect this computer to an existing remote machine. Later `harness join`
+ * reconnects with the saved credential. `adapter unjoin` leaves + clears it.
+ *
+ * What runs: the Claude hooks installer (SessionStart/SessionEnd → localhost hook server →
+ * session registry), the JSONL watcher (chokidar + byte-offset tail), the tmux pane reaper,
+ * and the backend socket (events up / chat + RPCs down).
+ */
+
+import 'dotenv/config'
+import { readFileSync, writeFileSync, mkdirSync, openSync, existsSync, rmSync, statSync } from 'fs'
+import { join, resolve } from 'path'
+import { fileURLToPath } from 'url'
+import { spawn } from 'child_process'
+import { createHash, randomUUID } from 'crypto'
+import { homedir } from 'os'
+import { env } from './config/env.js'
+import { VERSION } from './version.js'
+import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'
+import { installCodexHooks, installCommandCodeHooks, installCursorHooks, installDevinHooks, installHermesHooks, installOpencodePlugin, installPiExtension, installSessionHooks } from './lib/hooks.js'
+import { PID_FILE, TOKEN_FILE, daemonPort, isAlive, readPid } from './lib/daemonState.js'
+import { ENGINES, aliasesFor, engineBin, engineCommand, resolveEngine } from './lib/engineBin.js'
+import { launcherSessions } from './lib/launcherSessions.js'
+import { clearDeleted, isRecentlyDeleted, markDeleted } from './lib/deletedSessions.js'
+import { terminateDeletedAgent } from './lib/deleteAgentFallback.js'
+import { findLiveSession } from './lib/sessionRepair.js'
+import { launchEngine } from './lib/launch.js'
+import {
+ startTmuxReaper,
+ sendToTmux,
+ sendKeyToTmux,
+ sendLiteralToTmux,
+ validateSessionRuntime,
+ captureTmuxPane,
+ discoverTmuxResumes,
+ resolvePaneEngineProcess,
+ listPaneTitles,
+} from './lib/tmux.js'
+import { Watcher, type LineEvent } from './watcher/watcher.js'
+import { startHookServer } from './hookServer.js'
+import { BackendSocket } from './backendSocket.js'
+import { lastTurnTextFromRawLines, lineToEvents, newTurnState, type LiveEvent, type TurnState } from './lib/normalize.js'
+import { AskQuestionController, pollsQuestions, QuestionWatcher } from './lib/askQuestion.js'
+import { CommanderMirror } from './lib/commander.js'
+import {
+ setSummaryPoolDeviceConnected,
+ shutdownSummaryPool,
+ summarizeTurnText,
+ syncSummaryPoolSessions,
+} from './lib/summarize.js'
+import { setVoiceRouterDeviceConnected, setVoiceRouterSessions, shutdownVoiceRouter } from './lib/voiceRouter.js'
+import { tailFile } from './lib/sessions.js'
+import { E2eeStore } from './lib/e2ee/store.js'
+import {
+ startSelfUpdater, restore as restoreUpdate, confirm as confirmUpdate,
+ fetchManifest, downloadVerified, canary, stage, semverGt,
+ type Poller, type UpdateEntry,
+} from './lib/selfUpdate.js'
+import { stat } from 'fs/promises'
+import { CodexNormalizer, codexTaskError, lastCodexTurnText } from './engines/codex/normalizer.js'
+import { CursorNormalizer, lastCursorTurnText } from './engines/cursor/normalizer.js'
+import { CursorTranscriptDiscovery, findCursorTranscript } from './engines/cursor/discovery.js'
+import { CursorSubagentManager } from './engines/cursor/subagent.js'
+import { CursorTaskHookQueue } from './engines/cursor/taskHookQueue.js'
+import { loadCursorPendingTasks, removeCursorPendingTasks } from './engines/cursor/pendingTasks.js'
+import { OpencodeReader, readOpencodeMessages } from './engines/opencode/reader.js'
+import { lastOpencodeTurnText } from './engines/opencode/normalizer.js'
+import { PiNormalizer, lastPiTurnText } from './engines/pi/normalizer.js'
+import { HermesReader, readHermesMessages } from './engines/hermes/reader.js'
+import { DevinReader, readDevinMessages } from './engines/devin/reader.js'
+import { lastHermesTurnText } from './engines/hermes/normalizer.js'
+import { lastDevinTurnText } from './engines/devin/normalizer.js'
+import {
+ CommandCodeNormalizer,
+ commandCodeRunError,
+ commandCodeRunErrorSummary,
+ lastCommandCodeTurnText,
+} from './engines/commandcode/normalizer.js'
+import { SessionInputController } from './lib/sessionInput.js'
+import { adaptSlashCommand } from './lib/goalCommand.js'
+import { RuntimeProfileManager } from './lib/runtimeProfile.js'
+import { RuntimeProfileController } from './lib/runtimeProfileController.js'
+import { deviceErrorText } from './lib/deviceErrors.js'
+import {
+ installTimestampedConsole, sid, preview,
+ prepareLogFile, trimLogFile, LOG_CHECK_INTERVAL_MS,
+} from './lib/log.js'
+
+// Claude's Stop hook fires when the agent finishes, but the transcript can lag a moment behind
+// (docs: "the transcript file may lag behind the in-memory conversation"). Acting immediately races
+// that flush → an empty recap + a premature close. So the Stop hook is a DELAYED fallback: poll, and
+// only if the turn is still open after this grace + a re-poll do we force-close (by then the assistant
+// text is on disk, so the natural close usually wins and the recap isn't empty).
+const STOP_HOOK_GRACE_MS = 1_500
+
+// After a daemon restart every launcher socket is gone; surviving launchers reconnect in ~1s. Sessions
+// loaded from disk get this long to be re-claimed before they are dropped as orphans.
+const MACHINE_RECONNECT_GRACE_MS = 15_000
+
+// Daemon stdout/stderr. Capped at LOG_MAX_BYTES — see prepareLogFile/trimLogFile in lib/log.ts.
+const LOG_FILE = join(env.ADAPTER_DATA_DIR, 'machine.log')
+// Pre-rename name. Adopted (renamed, keeping the inode) the first time a daemon opens the log, so a
+// machine that updates mid-run keeps its history instead of stranding it in a file nobody tails.
+const LEGACY_LOG_FILE = join(env.ADAPTER_DATA_DIR, 'adapter.log')
+const COMPUTER_ID_FILE = join(env.ADAPTER_DATA_DIR, 'computer-id')
+// The machine's display name, mirrored from the backend (`machine_meta` on connect + web renames) by the
+// daemon so the separate `harness status` process can print it. Absent = unnamed machine.
+const MACHINE_NAME_FILE = join(env.ADAPTER_DATA_DIR, 'machine-name')
+// OpenCode's SQLite store — polled per session by OpencodeReader (no per-session transcript file).
+const OPENCODE_DB = join(env.OPENCODE_DATA_DIR, 'opencode.db')
+// Hermes keeps every surface's history in one SQLite store — polled per session by HermesReader.
+const HERMES_DB = join(env.HERMES_HOME, 'state.db')
+// Devin likewise keeps all history in one SQLite store (WAL) — polled per session by DevinReader.
+const DEVIN_DB = join(env.DEVIN_HOME, 'sessions.db')
+
+// How long `harness start` waits for the background daemon to report "[backend] connected" before
+// declaring an error. A healthy backend connects in well under this; a timeout ⇒ unreachable.
+const CONNECT_WAIT_MS = 10_000
+
+/** How long after a launcher's `open` its engine process needs to exist — see `onLauncherOpened`. */
+const ENGINE_SPAWN_GRACE_MS = 2_500
+/** Between repair attempts for the same launcher. Scanning an engine's store on every 5s tick, for a
+ * launcher whose session cannot be resolved at all, is pure noise. */
+const REPAIR_RETRY_MS = 60_000
+
+function usage(): never {
+ console.log(`harness v${VERSION} — connect this computer to your machine
+
+Agents — run one INSIDE tmux, after "harness join" (every argument after the engine name is
+passed through to that CLI untouched, e.g. harness claude --resume <id> --model opus):
+${ENGINES.map((e) => { const a = aliasesFor(e); return ` harness ${engineCommand(e).padEnd(12)} runs \`${engineBin(e)}\`${a.length ? ` (also: ${a.map((x) => `harness ${x}`).join(', ')})` : ''}` }).join('\n')}
+
+ These agents are driven from the web and the device, where nobody can answer a prompt — so each one
+ starts with ITS OWN permission checks bypassed (claude gets --dangerously-skip-permissions, codex
+ --yolo, devin --permission-mode dangerous, …). Name any permission or trust flag of that CLI
+ yourself and harness adds none: 'harness codex --sandbox read-only' stays sandboxed.
+ Two CLIs keep directory trust in their config rather than a flag — codex and devin ask "do you trust
+ this directory?" the first time you run one in a new directory. Answer it in the pane; harness will
+ not edit your config to skip it.
+
+Machine:
+ harness join <token> connect this computer to an existing machine using the token from its machine page
+ harness join reconnect with the saved credential
+ harness join -f run in the FOREGROUND (for a supervisor; logs to stdout)
+ harness unjoin leave the machine (removes it on the web too) + clear the saved credential
+ harness stop stop the background adapter (keeps the credential)
+ harness reset stop the adapter and clear local CLI state
+ harness status show whether it's running (+ version)
+ harness version print the installed version (v${VERSION})
+ harness update update to the latest build now (it also self-updates in the background)
+
+Browser end-to-end encryption:
+ harness browser-link print a one-time setup link for this browser
+ harness pair <code> pair a BROWSER (code shown on the machine page)
+ harness pairings list paired clients
+ harness unpair <#|fp> unpair one browser (by list number or fingerprint)
+ harness unpair --all unpair every browser
+
+ harness --help
+
+Env: BACKEND_WS_URL (${env.BACKEND_WS_URL}), WEB_URL (${env.WEB_URL}), ADAPTER_DATA_DIR, CLAUDE_PROJECTS_DIR, PORT`)
+ process.exit(0)
+}
+
+/** agentId = sha256(token)[:32] — same derivation as the backend (agentIdFromKey). */
+function agentIdFromToken(token: string): string {
+ return createHash('sha256').update(token).digest('hex').slice(0, 32)
+}
+
+/** Compact a home-relative path with `~` for display. */
+function tildify(p: string): string {
+ const h = homedir()
+ return p.startsWith(h) ? '~' + p.slice(h.length) : p
+}
+
+/** The currently-running script — dist/cli.js when built, src/cli.ts under tsx. */
+const SCRIPT_PATH = fileURLToPath(import.meta.url)
+
+// The saved credential IS the agent apiKey — 32 random bytes as hex (64 chars).
+const TOKEN_RE = /^[0-9a-f]{64}$/i
+
+/** The saved credential (env override, else the token file), or null if this computer hasn't joined. */
+function readSavedToken(): string | null {
+ const fromEnv = env.ADAPTER_TOKEN
+ if (fromEnv && TOKEN_RE.test(fromEnv)) return fromEnv
+ try {
+ const saved = readFileSync(TOKEN_FILE, 'utf-8').trim()
+ if (saved && TOKEN_RE.test(saved)) return saved
+ } catch { /* none */ }
+ return null
+}
+
+function saveToken(token: string): void {
+ mkdirSync(env.ADAPTER_DATA_DIR, { recursive: true })
+ writeFileSync(TOKEN_FILE, token + '\n', { mode: 0o600 })
+}
+
+/** Stable per-computer id (persisted in ${ADAPTER_DATA_DIR}/computer-id, created once). Sent on connect
+ * so the backend can enforce one machine per machine — and tell a same-machine reconnect (its 30s
+ * presence may still be alive) apart from a genuine second machine. Survives `unjoin`. */
+function computerId(): string {
+ try {
+ const saved = readFileSync(COMPUTER_ID_FILE, 'utf-8').trim()
+ if (saved) return saved
+ } catch { /* create below */ }
+ const id = randomUUID()
+ mkdirSync(env.ADAPTER_DATA_DIR, { recursive: true })
+ writeFileSync(COMPUTER_ID_FILE, id + '\n', { mode: 0o600 })
+ return id
+}
+
+// ── join ───────────────────────────────────────────────────────────────────────────────────────
+// The REST base for control endpoints, derived from the WS URL (wss→https, ws→http).
+function backendHttpBase(): string {
+ return env.BACKEND_WS_URL.replace(/\/$/, '').replace(/^wss:/, 'https:').replace(/^ws:/, 'http:')
+}
+function webBase(): string {
+ return env.WEB_URL.replace(/\/$/, '')
+}
+function createSetupToken(machineId?: string): { token: string; expiresAt: number; fingerprint: string } {
+ const store = new E2eeStore()
+ store.init()
+ return store.createSetupToken(machineId)
+}
+function setupBrowserLink(machineId: string, token: string): string {
+ const u = new URL(`${webBase()}/machine/${machineId}`)
+ u.hash = `setup=browser&t=${encodeURIComponent(token)}`
+ return u.toString()
+}
+
+/** POST JSON to the backend and return its `data` envelope; throws on a non-2xx / bad body. */
+async function postJson<T>(path: string, body: unknown, headers: Record<string, string> = {}): Promise<T> {
+ const res = await fetch(`${backendHttpBase()}${path}`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', ...headers },
+ body: JSON.stringify(body),
+ })
+ const json = (await res.json().catch(() => ({}))) as { success?: boolean; data?: T; error?: { message?: string } }
+ if (!res.ok || json.success === false) {
+ throw new Error(json.error?.message || `HTTP ${res.status}`)
+ }
+ return json.data as T
+}
+
+function printJoinTokenRequired(): never {
+ console.error('\n✗ This computer is not connected to a machine yet.')
+ console.error(' Create or open a remote machine in the web UI, copy its connect token, then run:')
+ console.error('\n harness join <token>\n')
+ process.exit(1)
+}
+
+/**
+ * `harness join [token]` — the single connect command.
+ * - `join <token>`: connect a machine to an existing machine using the token shown on its machine page.
+ * - `join` (no token): reconnect with the saved credential. Fresh machines must pass a token.
+ */
+async function joinCommand(foreground: boolean, argToken?: string): Promise<void> {
+ // Update-before-connect: pull the newest bundle FIRST so a machine always reconnects on the latest
+ // build. Staging swaps ~/.harness/cli/cli.js, and the daemon join spawns below (`node cli.js __run`)
+ // executes those fresh bytes. Skipped in the foreground (THIS process becomes the long-lived daemon
+ // and self-updates on its own) and on a dev/repo build; never blocks the join if the check fails.
+ if (!foreground) {
+ const v = await stageLatestBundle((m) => console.log(m))
+ if (v) console.log(` ✓ updated to v${v} — connecting on the new build`)
+ }
+ if (argToken) {
+ if (!TOKEN_RE.test(argToken)) {
+ console.error('Invalid token — expected the 64-char hex key shown on the machine page ("Connect this computer").')
+ process.exit(1)
+ }
+ saveToken(argToken)
+ // Explicit token = the user chose a SPECIFIC machine → on deauth do NOT create a new one; say so.
+ if ((await launch(argToken, foreground)) === 'deauth') {
+ console.error("\n✗ That token isn't valid for any machine (it may have been deleted).")
+ console.error(' Copy the current token from the machine page, then run: harness join <token>')
+ process.exit(1)
+ }
+ return
+ }
+ const token = readSavedToken()
+ if (!token) printJoinTokenRequired()
+ // If the saved token was rejected (machine deleted/revoked → 401/403), launch wipes it and returns
+ // 'deauth'; do not create a new machine from the CLI.
+ if ((await launch(token, foreground)) === 'deauth') {
+ console.error('\n✗ This computer is no longer connected to a valid machine.')
+ console.error(' Open the machine page, copy a fresh connect token, then run: harness join <token>')
+ process.exit(1)
+ }
+}
+
+/** Download + sha256-verify + canary the manifest's cli.js/notify.mjs, then atomically swap them into
+ * the installed CLI dir (dropping the .prev backups on success). The freshly-written cli.js is what the
+ * NEXT spawned daemon (`node cli.js __run`) executes — so staging here = "update, then run the new build".
+ * Runs in the short-lived CLI process, distinct from the daemon's own background `startSelfUpdater`. */
+async function downloadCanaryStage(entry: UpdateEntry, dir: string, log: (m: string) => void): Promise<boolean> {
+ const cliBuf = await downloadVerified(entry.cli)
+ const notifyBuf = await downloadVerified(entry.notify)
+ if (!canary(cliBuf, dir)) { log(` ✗ the new build failed its self-check — keeping v${VERSION}`); return false }
+ stage(dir, cliBuf, notifyBuf)
+ confirmUpdate(dir) // canary passed + bytes already verified ⇒ drop the .prev backups
+ return true
+}
+
+/** Fetch the manifest and, if a strictly-newer build exists, stage it (see downloadCanaryStage). Returns
+ * the staged version, or null when nothing was staged — already current, a dev/repo or update-disabled
+ * build, or ANY fetch/verify/canary failure (all swallowed: an update hiccup must never block `join`). */
+async function stageLatestBundle(log: (m: string) => void): Promise<string | null> {
+ if (SCRIPT_PATH.endsWith('.ts') || env.ADAPTER_UPDATE_DISABLE) return null // dev/repo run never touches the installed bundle
+ const dir = resolve(env.ADAPTER_CLI_DIR)
+ try {
+ const entry = await fetchManifest(env.ADAPTER_UPDATE_URL, env.ADAPTER_UPDATE_KEY)
+ if (!entry || !semverGt(entry.version, VERSION)) return null
+ log(`▸ newer build available — updating v${VERSION} → v${entry.version}…`)
+ return (await downloadCanaryStage(entry, dir, log)) ? entry.version : null
+ } catch (e) {
+ log(` (update check skipped: ${e instanceof Error ? e.message : String(e)})`)
+ return null
+ }
+}
+
+/** `harness update` — force the self-update NOW instead of waiting for the daemon's
+ * background poll. Checks the manifest; if a newer build exists it stops any running daemon first (so
+ * its poller can't race our staging), swaps in the new bytes, then relaunches on them. No-op on a
+ * dev/repo build, and leaves the daemon running-on-the-old-build untouched when already up to date. */
+async function updateCommand(): Promise<void> {
+ if (SCRIPT_PATH.endsWith('.ts')) {
+ console.log('This is a dev/repo build (running from source) — `harness update` is a no-op. Rebuild the bundle instead.')
+ process.exit(0)
+ }
+ console.log(`▸ Checking for updates… (current v${VERSION})`)
+ let entry: UpdateEntry | null = null
+ try { entry = await fetchManifest(env.ADAPTER_UPDATE_URL, env.ADAPTER_UPDATE_KEY) }
+ catch (e) { console.error(`✗ Could not reach the update manifest: ${e instanceof Error ? e.message : e}`); process.exit(1) }
+ if (!entry || !semverGt(entry.version, VERSION)) {
+ console.log(`✓ Already on the latest version (v${VERSION}).`)
+ process.exit(0)
+ }
+
+ // A newer build exists. Stop the running daemon FIRST so its own background updater can't race our
+ // staging on the .prev/.tmp files, then swap the bytes and bring it back up on the new build.
+ const running = readPid()
+ const wasRunning = !!(running && isAlive(running))
+ const relaunch = async (): Promise<void> => {
+ const t = readSavedToken()
+ if (!t) { console.log(' (no saved credential — run `harness join <token>` to connect on the new build.)'); process.exit(0) }
+ await new Promise((r) => setTimeout(r, 1000)) // grace for the backend to release the one-machine claim
+ await launch(t, false) // spawns a fresh daemon on the new bytes, prints status, and exits
+ }
+ if (wasRunning) { console.log(' stopping the running adapter…'); await stopDaemonProcess() }
+
+ console.log(`▸ Updating v${VERSION} → v${entry.version}…`)
+ let ok = false
+ try { ok = await downloadCanaryStage(entry, resolve(env.ADAPTER_CLI_DIR), (m) => console.log(m)) }
+ catch (e) { console.error(`✗ Update failed: ${e instanceof Error ? e.message : e}`); ok = false }
+ if (!ok) {
+ if (wasRunning) await relaunch() // staging failed → bring the OLD build back so `update` never leaves it down
+ process.exit(1)
+ }
+ console.log(` ✓ installed v${entry.version}`)
+ if (wasRunning) { await relaunch(); return }
+ console.log(`✓ Updated to v${entry.version}. Run \`harness join <token>\` to connect.`)
+ process.exit(0)
+}
+
+/** `adapter unjoin` — leave the machine: delete the binding on the backend (self-authorized by the
+ * agent's own key) and clear local creds; stop the daemon if it's running. */
+async function unjoin(): Promise<void> {
+ const token = readSavedToken()
+ if (!token) { console.log('This computer has not joined (no saved credential).'); process.exit(0) }
+ try {
+ await postJson('/api/machines/leave', {}, { 'x-api-key': token })
+ console.log('Left the machine on the backend.')
+ } catch (e) {
+ // Best-effort: even if the binding was already gone (or the backend is down), clear locally.
+ console.warn(`(backend leave failed: ${e instanceof Error ? e.message : e} — clearing locally anyway)`)
+ }
+ const pid = readPid()
+ if (pid && isAlive(pid)) { try { process.kill(pid, 'SIGTERM') } catch { /* ignore */ } }
+ rmSync(PID_FILE, { force: true })
+ rmSync(TOKEN_FILE, { force: true })
+ rmSync(MACHINE_NAME_FILE, { force: true })
+ console.log('This computer left the machine. Copy a token from the machine page, then run `harness join <token>` to connect again.')
+ process.exit(0)
+}
+
+async function projectFrame(s: RegisteredSession, selectedModel: string | null): Promise<Record<string, unknown>> {
+ const st = s.transcriptPath ? await stat(s.transcriptPath).catch(() => null) : null
+ return {
+ id: s.agentId,
+ userId: '',
+ name: projectDisplayName(s),
+ status: 'active',
+ createdAt: new Date(s.registeredAt).toISOString(),
+ updatedAt: new Date(st?.mtimeMs ?? s.updatedAt).toISOString(),
+ tmuxPane: s.tmuxPane,
+ engine: s.engine,
+ selectedModel,
+ }
+}
+
+/** 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)
+ if (!st) return 0
+ const birth = st.birthtimeMs || st.ctimeMs || st.mtimeMs
+ return Number.isFinite(birth) ? birth : 0
+}
+
+/** The daemon body: the actual long-running adapter (hooks + watcher + reaper + backend socket). */
+async function runForeground(token: string): Promise<void> {
+ installTimestampedConsole() // daemon-only: every machine.log line gets a wall-clock timestamp
+ const startedAt = Date.now()
+
+ // Claim the pid file for OURSELVES, first thing. It used to be written by whoever spawned us — the
+ // update-restart's parent, after supervising the handover — so a parent that died mid-handover (a
+ // `harness stop` landing in that window is enough) left a daemon nothing could manage: `status` said
+ // stopped, `stop` had no pid to signal, and `join` walked into "port already in use" against the very
+ // daemon it could not see. A process that is running is the only honest author of its own pid.
+ try { writeFileSync(PID_FILE, String(process.pid) + '\n') } catch { /* best effort */ }
+
+ // Last-resort net: a stray throw in ANY long-lived callback (a malformed JSONL line, a hostile backend
+ // frame, a timer) must NEVER take the daemon down — there is no supervisor. Log it and keep running.
+ // (Startup errors still fail loudly: they reject the runForeground promise → onError → exit, not these.)
+ process.on('unhandledRejection', (reason) => {
+ console.error('[fatal-guard] unhandledRejection:', reason instanceof Error ? (reason.stack ?? reason.message) : reason)
+ })
+ process.on('uncaughtException', (err) => {
+ console.error('[fatal-guard] uncaughtException:', err instanceof Error ? (err.stack ?? err.message) : err)
+ })
+
+ registry.load()
+ // Sessions on disk have no launcher socket yet. A daemon restart (self-update swaps the daemon out
+ // from under running agents) tears down every socket, and each surviving launcher reconnects within
+ // ~1s — so give them a grace window before deciding they are gone. Anything still unclaimed after it
+ // belongs to a launcher that really died (or a machine that rebooted).
+ setTimeout(() => {
+ for (const session of registry.list()) {
+ if (launcherSessions.has(session.agentId)) continue
+ console.log(`[machine] ${sid(session.agentId)} never reconnected — dropping ${sid(session.sessionId || session.agentId)}`)
+ if (session.sessionId) forgetSession(session.sessionId, { force: true })
+ else registry.removeAgent(session.agentId)
+ }
+ }, MACHINE_RECONNECT_GRACE_MS).unref?.()
+ // Nothing is probed here, on purpose.
+ //
+ // This used to verify every persisted session against `tmux` + `ps` and delete the ones that did not
+ // answer — at the one moment when that evidence is worth least. No launcher has reconnected yet (the
+ // hook server is not even listening), and a daemon in the middle of booting is exactly when those
+ // probes time out: pools warming, dozens of `ps` calls, 3s timeouts. `validateSessionRuntime` collapses
+ // "gone" and "the probe failed" into one `false`, so a slow machine deleted live agents from disk, and
+ // their launchers then reconnected to a daemon that had forgotten them. That is the "stop, start again,
+ // my agents are missing" report — 0 sessions registered on a boot whose registry held them.
+ //
+ // The authority is the launcher socket, and the grace above asks it. Anything really dead is dropped
+ // 15s later by that pass, or by the reaper afterwards; nothing is dropped on a guess.
+ // 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()
+ syncSummaryPoolSessions(sessions)
+ setVoiceRouterSessions(sessions)
+ }
+ syncRecapPool()
+ const runtimeProfiles = new RuntimeProfileManager()
+ // NB: hooks are installed AFTER the hook server binds (below), with the port it actually got — the
+ // server may fall back to a free port if env.PORT is taken, and the hooks must point at the real one.
+
+ const syncSession = (s: RegisteredSession, opts: { device?: boolean } = {}): void => {
+ void projectFrame(s, runtimeProfiles.selectedModel(s))
+ .then((project) => {
+ const frame = { type: 'agent_synced', payload: { agent: project } }
+ backendRef?.send(frame)
+ if (opts.device !== false) backendRef?.sendCommander(frame)
+ })
+ .catch((err) => console.error('[cli] announceSession failed:', err instanceof Error ? err.message : err))
+ }
+ const announceRename = (s: RegisteredSession, opts: { device?: boolean } = {}): void => {
+ const name = projectDisplayName(s)
+ backendRef?.send({ type: 'agent_renamed', payload: { agentId: s.agentId, name, engine: s.engine } })
+ if (opts.device !== false) backendRef?.sendCommander({ type: 'agent_renamed', payload: { agentId: s.agentId, name, engine: s.engine } })
+ }
+ // New sessions, runtime-profile changes, reconnects and periodic reconciliation refresh both web
+ // projects and device tiles from the same authoritative selectedModel snapshot.
+ /**
+ * `device: false` announces to the WEB only.
+ *
+ * The device rebuilds its entire tile list when it sees an agent id it does not know
+ * (`ui_request_agent_reload` → `agents_list` → re-anchor), which yanks the user off whatever tile they
+ * were on — observed as the screen jumping to Settings when a new `harness <engine>` opened a pane. An
+ * agent with no session bound yet has nothing to show there anyway, so the device hears about it once,
+ * when it binds — exactly one reload per agent, as before. The web upserts by id and does not move.
+ */
+ const announceSession = (s: RegisteredSession, opts: { device?: boolean } = {}): void => {
+ syncSession(s, opts)
+ announceRename(s, opts)
+ if (opts.device !== false) announcedToDevice.add(s.agentId)
+ }
+
+ /**
+ * Announce an agent to the device EXACTLY ONCE, and early.
+ *
+ * The device has no "agent created" frame: any id it does not recognise makes it drop the frame and pull
+ * the whole list again (`commander_client.c:656`, deliberate — inventing tiles from frames is what made
+ * the list drift). So every new agent costs one full reload, and where that reload lands matters:
+ * - twice per launch (open AND bind) yanked the view mid-use — the second one arrived while the user was
+ * already on the new tile;
+ * - only at bind meant the first message's cards were emitted before the device knew the agent, and were
+ * dropped — the user saw nothing for their first prompt.
+ * Once, at open, is what the device did historically: the reload happens while the pane is still empty,
+ * and by the time anyone types, the agent is known.
+ */
+ const announceToDeviceOnce = (s: RegisteredSession): void => {
+ if (announcedToDevice.has(s.agentId)) {
+ announceSession(s, { device: false }) // web still upserts; the device already knows this id
+ announceRename(s) // …and a known id can be renamed without a reload
+ return
+ }
+ announceSession(s)
+ }
+ /** Agent ids the device has been told about — see announceToDeviceOnce. */
+ const announcedToDevice = new Set<string>()
+
+ /**
+ * Messages sent to an agent whose engine has not opened a session yet, held until it does.
+ *
+ * An agent exists from the moment its launcher does, so the user can address it while the engine is
+ * still starting — or still sitting on a startup gate (claude's bypass-permissions warning, devin's
+ * trust prompt). Typing into that is worse than useless: the text answers the PROMPT, no turn ever
+ * starts, and neither the web nor the device has anything to show. Hold it, and submit once the session
+ * binds — the agent's queue already belongs to the pane, not the session.
+ */
+ const pendingBeforeBind = new Map<string, string[]>()
+
+ const syncPaneTitles = async (): Promise<void> => {
+ const titles = await listPaneTitles()
+ if (titles.size === 0) return
+ for (const session of registry.list()) {
+ const title = titles.get(session.tmuxPane)
+ if (!title) continue
+ const before = projectDisplayName(session)
+ const updated = registry.updateTitle(session.sessionId, title)
+ if (!updated) continue
+ const after = projectDisplayName(updated)
+ if (after !== before) {
+ syncSession(updated)
+ announceRename(updated)
+ }
+ }
+ }
+ let backendRef: BackendSocket | undefined
+ let fullReconcile: (announceDevice?: boolean) => Promise<void> = async () => {}
+
+ const backend = new BackendSocket(token, (connected) => {
+ if (!connected) return
+ const sessions = registry.list()
+ 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)
+ })
+ }, computerId())
+ backendRef = backend
+
+ // Per-session web turn-lifecycle state; the device mirror keeps its own state + recap.
+ const turnStates = new Map<string, TurnState>()
+ const codexNormalizers = new Map<string, CodexNormalizer>()
+ const cursorNormalizers = new Map<string, CursorNormalizer>()
+ const opencodeReaders = new Map<string, OpencodeReader>()
+ const piNormalizers = new Map<string, PiNormalizer>()
+ const hermesReaders = new Map<string, HermesReader>()
+ const devinReaders = new Map<string, DevinReader>()
+ const commandcodeNormalizers = new Map<string, CommandCodeNormalizer>()
+ const watcher = new Watcher()
+ const queuedSessionEvents: Array<{
+ sessionId: string
+ events: ReturnType<CursorNormalizer['ingest']>
+ }> = []
+ // Hook registration can race the rest of daemon initialization immediately after the localhost
+ // server binds. Queue those first records until input/mirror/heartbeat dependencies are ready.
+ let emitSessionEvents = (
+ sessionId: string,
+ events: ReturnType<CursorNormalizer['ingest']>,
+ ): void => {
+ if (events.length) queuedSessionEvents.push({ sessionId, events })
+ }
+ /**
+ * A turn died inside the engine instead of finishing. Neither devin nor commandcode has a StopFailure
+ * hook, so nothing else would tell the clients: the web would sit on the typing indicator and the
+ * device tile would stay "Working…". Surface the failure to both; the CALLER closes the turn (the devin
+ * reader and the commandcode normalizer each own their own turn state).
+ */
+ const announceTurnAborted = (
+ sessionId: string,
+ engine: string,
+ message: string,
+ deviceMessage = message,
+ ): void => {
+ console.log(`[turn] ${sid(sessionId)} aborted by ${engine} error · ${preview(message)}`)
+ backend.send({ type: 'error', agentId: agentIdFor(sessionId), dbSessionId: sessionId, payload: { message } })
+ backend.sendCommander({
+ type: 'commander_event',
+ agentId: agentIdFor(sessionId),
+ dbSessionId: sessionId,
+ payload: { kind: 'error', text: deviceErrorText(deviceMessage, engine) },
+ })
+ }
+ const cursorDiscovery = new CursorTranscriptDiscovery(env.CURSOR_HOME, (sessionId, transcriptPath) => {
+ const existing = registry.bySession(sessionId)
+ if (!existing || existing.engine !== 'cursor' || existing.transcriptPath === transcriptPath) return
+ const result = registry.register({
+ engine: 'cursor',
+ sessionId,
+ transcriptPath,
+ cwd: existing.cwd ?? undefined,
+ source: existing.source ?? undefined,
+ tmuxPane: existing.tmuxPane,
+ title: existing.title ?? undefined,
+ model: existing.model ?? undefined,
+ cliVersion: existing.cliVersion ?? undefined,
+ processIdentity: existing.processIdentity ?? undefined,
+ hookEvent: 'TranscriptDiscovered',
+ })
+ if (!result) return
+ void attachSession(result.entry, false, true).then((attached) => {
+ if (!attached) return
+ syncRecapPool()
+ syncSession(result.entry)
+ }).catch((err) => {
+ console.error('[cursor-discovery] attach failed:', err instanceof Error ? err.message : err)
+ })
+ })
+
+ const attachSession = async (
+ session: RegisteredSession,
+ reset = false,
+ replayCursorFromStart = false,
+ /**
+ * Tail the transcript from byte 0 instead of from its current end.
+ *
+ * The watcher normally starts at the end, because a session is registered the moment the engine
+ * starts and the file is empty — end and start are the same place. That stops being true when an
+ * agent exists BEFORE its session: the user types their first message in the terminal, THAT is what
+ * makes the engine open a session, and by the time the hook binds it the prompt (and the first of the
+ * answer) is already on disk. Starting at the end skipped it, so the web showed neither the message
+ * nor the response. Only ever set for a session that was born after its agent — a resumed one keeps
+ * tailing from the end, since its history belongs to `session_get`, not to the live stream.
+ */
+ replayFromStart = false,
+ ): Promise<boolean> => {
+ if (!await validateSessionRuntime(session)) return false
+ if (!reset && (
+ turnStates.has(session.sessionId)
+ || codexNormalizers.has(session.sessionId)
+ || cursorNormalizers.has(session.sessionId)
+ || opencodeReaders.has(session.sessionId)
+ || piNormalizers.has(session.sessionId)
+ || hermesReaders.has(session.sessionId)
+ || devinReaders.has(session.sessionId)
+ || commandcodeNormalizers.has(session.sessionId)
+ )) {
+ if (session.transcriptPath) {
+ await watcher.addSession(
+ { ...session, transcriptPath: session.transcriptPath },
+ { fromStart: replayFromStart || (session.engine === 'cursor' && replayCursorFromStart) },
+ )
+ }
+ 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)}`)
+ return true
+ }
+ const lines = session.transcriptPath ? await tailFile(session.transcriptPath, Infinity) : []
+ const initialCursorEvents: ReturnType<CursorNormalizer['ingest']> = []
+ // Folding the transcript in below is deliberately silent — old turns must never replay live. But
+ // when the history ENDS mid-turn the turn is still running, and dropping its `turn_started` costs
+ // the whole turn: CommanderMirror.onTurnEnded returns early while turnOpen is false, so the close
+ // that follows produces no recap and no `done`. Keep the last start and replay exactly that one.
+ const historyEvents: LiveEvent[] = []
+ let historyTurnOpen = false
+ runtimeProfiles.hydrate(session, lines)
+ await runtimeProfiles.ingestConfig(session, true)
+ if (session.engine === 'codex') {
+ const normalizer = new CodexNormalizer('live')
+ // Hydrate state silently; never replay history live — except a turn left open, below.
+ for (const line of lines) historyEvents.push(...normalizer.ingest(line))
+ historyTurnOpen = normalizer.turnOpen
+ codexNormalizers.set(session.sessionId, normalizer)
+ } else if (session.engine === 'cursor') {
+ const normalizer = new CursorNormalizer('live', session.sessionId)
+ for (const line of lines) {
+ const events = normalizer.ingest(line)
+ if (replayCursorFromStart) initialCursorEvents.push(...events)
+ else historyEvents.push(...events)
+ }
+ historyTurnOpen = !replayCursorFromStart && normalizer.turnOpen
+ cursorNormalizers.set(session.sessionId, normalizer)
+ const capture = await captureTmuxPane(session.tmuxPane, 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
+ // streams new activity into emitSessionEvents (the same funnel the file engines use).
+ const reader = new OpencodeReader({
+ dbPath: OPENCODE_DB,
+ sessionId: session.sessionId,
+ onEvents: (events) => emitSessionEvents(session.sessionId, events),
+ onFatal: (err) => console.warn(`[opencode] ${sid(session.sessionId)} ${err.message}`),
+ })
+ opencodeReaders.set(session.sessionId, reader)
+ await reader.start()
+ } else if (session.engine === 'pi') {
+ const normalizer = new PiNormalizer('live')
+ // Hydrate state silently; never replay history live — except a turn left open, below.
+ for (const line of lines) historyEvents.push(...normalizer.ingest(line))
+ historyTurnOpen = normalizer.turnOpen
+ piNormalizers.set(session.sessionId, normalizer)
+ } else if (session.engine === 'hermes') {
+ // Hermes has no transcript file — poll its SQLite store, like opencode.
+ const reader = new HermesReader({
+ dbPath: HERMES_DB,
+ sessionId: session.sessionId,
+ onEvents: (events) => emitSessionEvents(session.sessionId, events),
+ onFatal: (err) => console.warn(`[hermes] ${sid(session.sessionId)} ${err.message}`),
+ })
+ hermesReaders.set(session.sessionId, reader)
+ await reader.start()
+ } else if (session.engine === 'devin') {
+ // Devin has no transcript file either — poll its SQLite store, like hermes/opencode.
+ const reader = new DevinReader({
+ dbPath: DEVIN_DB,
+ devinHome: env.DEVIN_HOME,
+ sessionId: session.sessionId,
+ onEvents: (events) => emitSessionEvents(session.sessionId, events),
+ // Devin has no StopFailure: a turn that dies on a provider error writes no assistant row and
+ // fires no Stop hook, so surface the failure and close the turn ourselves — otherwise the web
+ // sits on the typing indicator forever.
+ onTurnAborted: (message) => {
+ announceTurnAborted(session.sessionId, 'devin', message)
+ emitSessionEvents(session.sessionId, [{ type: 'turn_ended', payload: {} }])
+ },
+ onFatal: (err) => console.warn(`[devin] ${sid(session.sessionId)} ${err.message}`),
+ })
+ devinReaders.set(session.sessionId, reader)
+ 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)
+ if (devinPane) runtimeProfiles.ingestPane(session, devinPane, true)
+ } else if (session.engine === 'commandcode') {
+ const normalizer = new CommandCodeNormalizer('live')
+ // Hydrate state silently; never replay history live — except a turn left open, below.
+ for (const line of lines) historyEvents.push(...normalizer.ingest(line))
+ historyTurnOpen = normalizer.turnOpen
+ commandcodeNormalizers.set(session.sessionId, normalizer)
+ } else {
+ const state = newTurnState()
+ for (const line of lines) historyEvents.push(...lineToEvents(line, state))
+ historyTurnOpen = state.turnOpen
+ turnStates.set(session.sessionId, state)
+ }
+ if (session.transcriptPath) {
+ await watcher.addSession({ ...session, transcriptPath: session.transcriptPath })
+ } else if (session.engine === 'cursor') {
+ await cursorDiscovery.add(session.sessionId)
+ }
+ if (initialCursorEvents.length) emitSessionEvents(session.sessionId, initialCursorEvents)
+ console.log(`[agent] ${sid(session.agentId)} attached · engine=${session.engine} · pane=${session.tmuxPane} · 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.
+ if (historyTurnOpen) {
+ const opened = historyEvents.findLast((event) => event.type === 'turn_started')
+ if (opened) {
+ console.log(`[agent] ${sid(session.agentId)} resumed the turn already open at attach`)
+ emitSessionEvents(session.sessionId, [opened])
+ }
+ }
+ // Watch this pane for a question from ATTACH, not only from the next turn_started.
+ //
+ // A turn-scoped start assumes the agent exists before its turn does, and for some engines it does not:
+ // OpenCode registers itself when its FIRST message creates the session, i.e. the turn is already
+ // running by the time the daemon knows the agent — so its question opened and nothing announced it
+ // (measured: the dialog sat on the pane, the device saw nothing). Command Code has the mirror problem,
+ // asking AFTER the turn ends. The watcher is idempotent, no-ops without a device, and dies with the
+ // session, so starting it early costs nothing.
+ if (pollsQuestions(session.engine)) questionWatcher.start(session.sessionId)
+ return true
+ }
+ // 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.
+ const questions = new AskQuestionController({
+ getSession: (id) => registry.resolve(id),
+ capture: captureTmuxPane,
+ sendText: sendToTmux,
+ sendKey: sendKeyToTmux,
+ })
+ // 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
+ // mid-question the screen showed a finished summary while the user was still being asked. Keep the tile
+ // visibly working for as long as the exchange lasts. The device's own busy-timeout watchdog bounds this,
+ // so an abandoned question cannot pin the tile forever.
+ const showAwaitingAnswer = (sessionId: string): void => {
+ backend.sendCommander({
+ type: 'commander_event',
+ agentId: agentIdFor(sessionId),
+ dbSessionId: sessionId,
+ payload: { kind: 'processing', text: 'Waiting for your answer' },
+ })
+ }
+ backend.onQuestionAnswer = (payload) => {
+ // Hold the working state across the gap too: the CLI needs a moment to move to the next question, and
+ // that gap is exactly where the stale recap used to flash back.
+ const target = payload.sessionId || payload.agentId
+ if (typeof target === 'string' && target) showAwaitingAnswer(target)
+ void questions.answer(payload)
+ }
+ const questionWatcher = new QuestionWatcher({
+ getSession: (id) => registry.resolve(id),
+ capture: captureTmuxPane,
+ hasDevice: () => backend.hasCommander(),
+ isDriving: (sessionId) => questions.isDriving(sessionId),
+ onQuestion: (sessionId, requestId, shaped) => {
+ questions.remember(requestId, sessionId)
+ showAwaitingAnswer(sessionId)
+ backend.sendCommander({
+ type: 'commander_question',
+ agentId: agentIdFor(sessionId),
+ dbSessionId: sessionId,
+ payload: { requestId, questions: shaped },
+ })
+ console.log(`[question] ${sid(sessionId)} asking the user · "${preview(shaped[0]?.q ?? '')}" · req=${requestId}`)
+ },
+ })
+
+ const mirror = new CommanderMirror({
+ send: (frame) => backend.sendCommander(frame),
+ sendWeb: (frame) => backend.send(frame), // turn_summary_pending / turn_summary → web indicator
+ hasDevice: () => backend.hasCommander(), // device-gate the LLM recap (mirror node)
+ active: () => backend.hasActiveCommander(), // stream live cards only to the actively-rendered machine
+ summarize: (text, signal, userMessage, sessionId) =>
+ summarizeTurnText(text, signal, userMessage, sessionId ? registry.bySession(sessionId)?.engine ?? 'claude' : 'claude'),
+ nameFor: (sessionId) => { const s = registry.bySession(sessionId); return s ? projectDisplayName(s) : undefined },
+ agentIdFor: (sessionId) => registry.bySession(sessionId)?.agentId,
+ readLastTurn: async (sessionId) => {
+ const s = registry.bySession(sessionId)
+ if (!s) return null
+ if (s.engine === 'opencode') return lastOpencodeTurnText(await readOpencodeMessages(OPENCODE_DB, sessionId))
+ if (s.engine === 'hermes') return lastHermesTurnText(await readHermesMessages(HERMES_DB, sessionId))
+ if (s.engine === 'devin') return lastDevinTurnText(await readDevinMessages(DEVIN_DB, sessionId))
+ if (!s.transcriptPath) return null
+ const lines = await tailFile(s.transcriptPath, Infinity)
+ if (s.engine === 'codex') return lastCodexTurnText(lines)
+ if (s.engine === 'cursor') return lastCursorTurnText(lines)
+ if (s.engine === 'pi') return lastPiTurnText(lines)
+ if (s.engine === 'commandcode') return lastCommandCodeTurnText(lines)
+ return lastTurnTextFromRawLines(lines)
+ },
+ dataDir: env.ADAPTER_DATA_DIR,
+ recapForce: env.RECAP_FORCE,
+ })
+ backend.recentProvider = (sessionId, n) => mirror.recent(sessionId, 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),
+ })
+ /**
+ * Engine session id → the agent that owns it. The event stream speaks in ENGINE session ids while
+ * anything the user addresses (input queue, control lock, every outbound frame) belongs to the AGENT,
+ * which outlives the session it is currently bound to.
+ */
+ const agentIdFor = (sessionId: string): string => registry.bySession(sessionId)?.agentId ?? sessionId
+
+ backend.runtimeModelsProvider = (sessionId) => {
+ if (!sessionId) return runtimeProfiles.modelsForSessions(registry.list())
+ const session = registry.resolve(sessionId)
+ return session ? runtimeProfiles.modelsForSession(session) : Promise.resolve([])
+ }
+ backend.runtimeProfileProvider = (session) => runtimeProfiles.selectedModel(session)
+ backend.onRuntimeProfileUpdate = (sessionId, selectedModel) => runtimeController.setProfile(sessionId, selectedModel)
+ runtimeProfiles.onChanged = (sessionId) => {
+ const session = registry.resolve(sessionId)
+ if (session) syncSession(session)
+ }
+
+ // Turn heartbeat (5s): pushes `turn_heartbeat` to the web while the turn is open (keeps its 10s
+ // turn-watchdog armed through a quiet stretch — a long tool, thinking with no new JSONL line), AND fans a
+ // busy heartbeat to the device via mirror.heartbeat() so the device's busy tile stays fresh. Unlike the
+ // web send, the device fan-out spans the WHOLE busy window — the turn AND the trailing summarize (up to
+ // the 60s one-shot timeout) — because the device clears busy only on a live terminal and has a
+ // busy-timeout watchdog that would otherwise cut a long "Summarizing…". So the timer self-cancels only
+ // once BOTH the turn is closed and mirror.heartbeat() reports idle (turn done + summary done). Mirrors the
+ // the hosted runtime brain (TURN_HEARTBEAT_MS=5000), per-session, one timer per session.
+ const TURN_HEARTBEAT_MS = 5000
+ const heartbeats = new Map<string, NodeJS.Timeout>()
+ const turnStartedAt = new Map<string, number>() // sessionId → turn_started wall clock, for [turn] duration
+ const stopHeartbeat = (sessionId: string): void => {
+ const t = heartbeats.get(sessionId)
+ if (t) { clearInterval(t); heartbeats.delete(sessionId) }
+ }
+ const startHeartbeat = (sessionId: string): void => {
+ stopHeartbeat(sessionId) // restart → guarantee a single timer per session
+ const timer = setInterval(() => {
+ if (!registry.has(sessionId)) { stopHeartbeat(sessionId); return }
+ const turnOpen =
+ turnStates.get(sessionId)?.turnOpen
+ ?? codexNormalizers.get(sessionId)?.turnOpen
+ ?? cursorNormalizers.get(sessionId)?.turnOpen
+ ?? opencodeReaders.get(sessionId)?.turnOpen
+ ?? piNormalizers.get(sessionId)?.turnOpen
+ ?? hermesReaders.get(sessionId)?.turnOpen
+ ?? devinReaders.get(sessionId)?.turnOpen
+ ?? commandcodeNormalizers.get(sessionId)?.turnOpen
+ // Device: keep the busy tile alive through the turn AND the summarize window. Returns false when idle.
+ const deviceBusy = mirror.heartbeat(sessionId)
+ // Web: unchanged — heartbeat only while the turn itself is open (summarizing uses turn_summary_pending).
+ if (turnOpen) backend.send({ type: 'turn_heartbeat', dbSessionId: sessionId, payload: { sessionId } })
+ // Self-cancel only once the turn is closed AND the summarize is done (no more device heartbeat needed).
+ if (!turnOpen && !deviceBusy) stopHeartbeat(sessionId)
+ }, TURN_HEARTBEAT_MS)
+ heartbeats.set(sessionId, timer)
+ }
+
+ emitSessionEvents = (sessionId: string, events: ReturnType<CursorNormalizer['ingest']>): void => {
+ if (!events.length || !registry.has(sessionId)) return
+ for (const event of events) {
+ backend.send({ ...event, dbSessionId: sessionId })
+ if (event.type === 'turn_started') {
+ turnStartedAt.set(sessionId, Date.now())
+ console.log(`[turn] ${sid(sessionId)} started · engine=${registry.bySession(sessionId)?.engine ?? 'claude'} · "${preview(event.payload.userMessage)}"`)
+ input.onTurnStarted(agentIdFor(sessionId), event.payload.userMessage)
+ startHeartbeat(sessionId)
+ questionWatcher.start(sessionId) // Claude opens its dialog INSIDE a turn
+ } else if (event.type === 'turn_ended') {
+ const startedAt = turnStartedAt.get(sessionId)
+ turnStartedAt.delete(sessionId)
+ // Say when a turn was KILLED. The log previously showed an interrupt as a fresh `[turn] started
+ // "[Request interrupted by user]"`, which read like a new prompt and hid the bug for weeks.
+ console.log(
+ `[turn] ${sid(sessionId)} ended${event.payload.aborted ? ' · aborted (interrupted)' : ''}` +
+ `${startedAt ? ` · ${Date.now() - startedAt}ms` : ''}`,
+ )
+ input.onTurnEnded(agentIdFor(sessionId))
+ // Command Code asks AFTER the turn: `ask_user_question` ends the turn (its Stop hook fires), the
+ // dialog goes up, and the answer opens a NEW turn. Stopping the watcher here is what left the
+ // terminal sitting on a question the device never showed. Its watcher runs off the session, not
+ // the turn — see the attach path — so leave it alone.
+ if (registry.bySession(sessionId)?.engine !== 'commandcode') questionWatcher.stop(sessionId)
+ // Do NOT stop the heartbeat here: the turn is closed but the device summarize is just starting
+ // (mirror sets summarizing=true in the mirror.ingest below). The timer keeps fanning "Summarizing…"
+ // to the device and self-cancels once mirror.heartbeat() reports idle (summary done).
+ }
+ }
+ mirror.ingest(events, sessionId)
+ }
+ for (const queued of queuedSessionEvents.splice(0)) emitSessionEvents(queued.sessionId, queued.events)
+ const cursorSubagents = new CursorSubagentManager(env.CURSOR_HOME, emitSessionEvents)
+ const cursorTaskHooks = new CursorTaskHookQueue({
+ drainTranscript: (sessionId) => watcher.pollSession(sessionId),
+ emit: emitSessionEvents,
+ register: (sessionId, hook, normalizer) => cursorSubagents.register(sessionId, hook, normalizer),
+ isActive: (sessionId) => registry.bySession(sessionId)?.engine === 'cursor',
+ onError: (sessionId, error) => {
+ console.error(`[cursor] Task hook queue failed (${sessionId}):`, error instanceof Error ? error.message : error)
+ },
+ })
+ const onCursorTaskStart = (sessionId: string, toolUseId: string, toolInput: unknown): void => {
+ const session = registry.resolve(sessionId)
+ if (!session || session.engine !== 'cursor') return
+ let normalizer = cursorNormalizers.get(sessionId)
+ if (!normalizer) {
+ normalizer = new CursorNormalizer('live', sessionId)
+ cursorNormalizers.set(sessionId, normalizer)
+ }
+ cursorTaskHooks.enqueue(sessionId, { toolUseId, input: toolInput }, normalizer)
+ }
+
+ /**
+ * Drop a session everywhere: registry, web tab, device tile, recap/turn state.
+ *
+ * **A live launcher vetoes this.** The rule the whole design rests on is that an agent exists exactly as
+ * long as its launcher's socket is open (see launcherSessions.ts) — so anything that concludes a session
+ * is dead from weaker evidence (a `ps` probe that timed out, a SessionEnd hook, a stale pane id) must
+ * lose to that socket. Before this guard the reaper could evict an agent whose launcher was demonstrably
+ * connected, and nothing would ever bring it back.
+ *
+ * `force` is for the cases that outrank the socket: the launcher itself closed, the user deleted the
+ * agent, or the session is being REPLACED by a newer one from the same launcher (a `/clear` rotation).
+ */
+ const forgetSession = (id: string, opts: { force?: boolean; keepAgent?: boolean } = {}): void => {
+ // Addressable by either id: callers hold an engine session id (hooks, reaper) or an agent id (the
+ // launcher closing, a delete from the web).
+ const doomed = registry.resolve(id)
+ const sessionId = doomed?.sessionId || id
+ if (!opts.force && doomed && launcherSessions.has(doomed.launcherId)) {
+ console.log(`[agent] ${sid(doomed.agentId)} kept — its launcher is still connected`)
+ return
+ }
+ // `keepAgent`: a ROTATION releases the session's parse/watch state but the AGENT stays — it is the
+ // launcher, still running in the same pane. Removing it here is what used to close the user's tab and
+ // reopen it at the end of the strip on every `/clear`.
+ console.log(opts.keepAgent
+ ? `[agent] ${sid(doomed?.agentId ?? sessionId)} released session ${sid(sessionId)}`
+ : `[agent] ${sid(doomed?.agentId ?? sessionId)} forgotten`)
+ if (opts.keepAgent) registry.remove(sessionId)
+ else if (doomed) registry.removeAgent(doomed.agentId)
+ else registry.remove(sessionId)
+ syncRecapPool()
+ turnStates.delete(sessionId)
+ turnStartedAt.delete(sessionId)
+ codexNormalizers.delete(sessionId)
+ cursorNormalizers.delete(sessionId)
+ opencodeReaders.get(sessionId)?.stop()
+ opencodeReaders.delete(sessionId)
+ piNormalizers.delete(sessionId)
+ hermesReaders.get(sessionId)?.stop()
+ hermesReaders.delete(sessionId)
+ devinReaders.get(sessionId)?.stop()
+ devinReaders.delete(sessionId)
+ commandcodeNormalizers.delete(sessionId)
+ cursorDiscovery.remove(sessionId)
+ cursorSubagents.forget(sessionId)
+ void removeCursorPendingTasks(env.ADAPTER_DATA_DIR, sessionId)
+ runtimeProfiles.forget(sessionId)
+ void watcher.removeSession(sessionId)
+ stopHeartbeat(sessionId)
+ input.forget(doomed?.agentId ?? sessionId)
+ mirror.forget(sessionId) // aborts any in-flight recap + clears busy; KEEPS the persisted summary
+ if (doomed) pendingBeforeBind.delete(doomed.agentId)
+ if (opts.keepAgent) return
+ if (doomed) announcedToDevice.delete(doomed.agentId)
+ backend.send({ type: 'agent_deleted', payload: { agentId: doomed?.agentId ?? sessionId } }) // web tab
+ backend.sendCommander({ type: 'agent_deleted', payload: { agentId: doomed?.agentId ?? sessionId } })
+ }
+
+ /**
+ * Adopt agents that were RESUMED into a pane — the one launch that announces nothing.
+ *
+ * An engine's SessionStart hook fires for a NEW session. Resume an old one and no hook comes, so the
+ * session exists in the pane, the user sees it working, and the daemon lists nothing. Verified on
+ * 2026-08-03 with seven agent panes and five tiles: a cursor, an opencode and a hermes pane, each
+ * resumed hours earlier, were invisible until this ran.
+ *
+ * The live launcher is what makes adoption safe. It supplies the launcherId — mandatory since a
+ * session's lifetime is bound to a launcher socket (registry.register returns null without one, which
+ * is exactly why the cursor-only version of this loop had silently registered nothing since) — and its
+ * presence is the proof that the pane belongs to machine at all, rather than a bare CLI someone ran.
+ */
+ let tmuxResumeDiscoveryInFlight: Promise<void> | null = null
+ /** The whole bind pass: tmux-resume discovery first (it names the session outright), then the
+ * process-and-store probe for whatever is still unbound. */
+ const reconcileBindings = (): Promise<void> => adoptResumedSessions()
+
+ const adoptResumedSessions = (): Promise<void> => {
+ if (tmuxResumeDiscoveryInFlight) return tmuxResumeDiscoveryInFlight
+ tmuxResumeDiscoveryInFlight = (async () => {
+ for (const candidate of await discoverTmuxResumes()) {
+ if (registry.has(candidate.sessionId)) continue
+ // Just deleted: the engine is still winding down, and adopting it here would put the tile back.
+ if (isRecentlyDeleted(candidate.sessionId)) continue
+ const launcher = launcherSessions.byPane(candidate.tmuxPane)
+ if (!launcher || launcher.engine !== candidate.engine) continue
+ // Cursor is tailed from a transcript file, so an entry without one would attach to nothing. The
+ // other engines here are read from their own stores by session id.
+ const transcriptPath = candidate.engine === 'cursor'
+ ? await findCursorTranscript(env.CURSOR_HOME, candidate.sessionId) ?? undefined
+ : undefined
+ if (candidate.engine === 'cursor' && !transcriptPath) continue
+ const result = registry.register({
+ engine: candidate.engine,
+ sessionId: candidate.sessionId,
+ launcherId: launcher.launcherId,
+ transcriptPath,
+ cwd: candidate.cwd,
+ source: 'tmux-resume',
+ tmuxPane: candidate.tmuxPane,
+ processIdentity: candidate.processIdentity,
+ hookEvent: 'TmuxResumeDiscovery',
+ })
+ if (!result || !result.isNew) continue
+ if (result.evicted) forgetSession(result.evicted, { force: true })
+ if (!await attachSession(result.entry)) {
+ registry.remove(result.entry.sessionId)
+ continue
+ }
+ syncRecapPool()
+ announceToDeviceOnce(result.entry)
+ console.log(
+ `[resume-discovery] adopted ${candidate.engine} session ${sid(result.entry.sessionId)} on ${result.entry.tmuxPane}`,
+ )
+ }
+ await repairOrphanLaunchers()
+ })().finally(() => { tmuxResumeDiscoveryInFlight = null })
+ return tmuxResumeDiscoveryInFlight
+ }
+
+ /**
+ * A launcher is connected but the daemon holds no agent for it — put the mapping back.
+ *
+ * This is the other half of "an agent exists while its launcher's socket is open". The launcher upholds
+ * its side (same machine id, reconnects forever), but its frame carries no SESSION id — only the
+ * engine's hook ever supplied that, and it fires once. So any daemon that lost the mapping kept a
+ * connected launcher with nothing behind it, invisible until the user typed. Seen on 2026-08-03: three
+ * launchers reconnected with their original ids and not one came back.
+ *
+ * `findLiveSession` asks the engine's own store and refuses to guess between two candidates, so the
+ * worst case is staying invisible one more turn — never binding an agent to someone else's transcript.
+ */
+ const lastRepairAttempt = new Map<string, number>()
+ /**
+ * Bind the agents that have no engine session yet.
+ *
+ * Driven by the AGENTS rather than by the launchers: an agent exists from the moment its launcher
+ * opened, so "who still needs a session?" is a property of the registry, not something to re-derive
+ * from sockets each tick. Resuming an engine reports no new session id, so without this pass a resumed
+ * agent would sit unbound forever.
+ */
+ const repairOrphanLaunchers = async (): Promise<void> => {
+ for (const agent of registry.unbound()) {
+ const launcher = launcherSessions.get(agent.agentId)
+ if (!launcher) continue
+ // An engine we cannot resolve (or one still starting) would otherwise be re-scanned every tick.
+ const attemptedAt = lastRepairAttempt.get(agent.agentId) ?? 0
+ if (Date.now() - attemptedAt < REPAIR_RETRY_MS) continue
+ lastRepairAttempt.set(agent.agentId, Date.now())
+ const cwd = agent.cwd ?? launcher.cwd
+ if (!cwd) continue
+ const identity = await resolvePaneEngineProcess(agent.tmuxPane, agent.engine)
+ if (!identity) continue
+ const startedAtMs = Date.parse(identity.startMarker)
+ if (!Number.isFinite(startedAtMs)) continue
+ // `bornOnly`: this agent has never had a session, so only accept one this engine CREATED. Taking a
+ // merely-recently-written transcript handed the new agent the previous run's conversation — exit the
+ // launcher, start it again in the same pane, and the fresh tab opened full of old messages.
+ const found = await findLiveSession(agent.engine, cwd, startedAtMs, { bornOnly: true })
+ if (!found || registry.has(found.sessionId) || isRecentlyDeleted(found.sessionId)) continue
+ const result = registry.register({
+ engine: agent.engine,
+ sessionId: found.sessionId,
+ launcherId: agent.agentId,
+ transcriptPath: found.transcriptPath,
+ cwd,
+ source: 'launcher-repair',
+ tmuxPane: agent.tmuxPane,
+ processIdentity: identity,
+ hookEvent: 'LauncherRepair',
+ })
+ if (!result || !result.isNew) continue
+ if (result.evicted) forgetSession(result.evicted, { force: true })
+ if (!await attachSession(result.entry)) {
+ registry.remove(result.entry.sessionId)
+ continue
+ }
+ lastRepairAttempt.delete(agent.agentId)
+ syncRecapPool()
+ announceSession(result.entry)
+ console.log(
+ `[repair] ${sid(agent.agentId)} had no session — bound ${agent.engine} session `
+ + `${sid(result.entry.sessionId)} on ${result.entry.tmuxPane}`,
+ )
+ }
+ }
+
+ // SessionEnd = the claude session is over → remove it from the list, EVEN if the tmux pane is still
+ // alive (the user exited claude with Ctrl+D / Ctrl+C×2 and is back at the shell — claude isn't
+ // running there anymore). A later `claude --resume` fires SessionStart and adds it back.
+ // The one exception is `/clear`, which rotates in place: a fresh SessionStart for the SAME pane
+ // follows immediately and replaces this session via pane-dedup, so we keep it to avoid a flicker.
+ const onSessionEnd = (sessionId: string, reason: string | undefined): void => {
+ // SessionEnd hooks are computer-global. Never let a standalone/non-tmux Claude session (or a stale
+ // callback for an already-evicted id) manufacture a device `done` card through forgetSession().
+ if (reason === 'clear' || !registry.has(sessionId)) return
+ void (async () => {
+ await new Promise((resolve) => setTimeout(resolve, 2000))
+ const session = registry.resolve(sessionId)
+ if (!session) return
+ if (await validateSessionRuntime(session)) return
+ forgetSession(sessionId)
+ })().catch((err) => console.error('[hooks] SessionEnd runtime check failed:', err instanceof Error ? err.message : err))
+ }
+
+ // Hook callbacks → registry → announce live to web + device (tab/tile add), drop on end.
+ const { server: hookServer, port: hookPort } = await startHookServer(env.PORT, {
+ // The `harness <engine>` wrapper exited — authoritative end, so its tile drops now instead of when
+ // the reaper next notices the launcher is gone.
+ onLauncherClosed: (launcherId) => {
+ // The launcher IS the agent, bound or not — one call, and an agent that never got as far as
+ // reporting a session still goes away with the pane it was running in.
+ forgetSession(launcherId, { force: true })
+ },
+ // …and the reverse. A launcher opening is the only signal that a RESUMED agent exists, since its
+ // engine fires no SessionStart. Closing dropped the session immediately; re-creating it used to wait
+ // for the periodic scan, or — before adoption existed at all — never happened.
+ //
+ // Delayed on purpose: the launcher is still waiting on the ack we just sent before it spawns the
+ // engine, so right now the pane holds only the launcher process. Adopting at this instant would
+ // record the LAUNCHER's pid as the session's process identity, and the reaper compares pid + start
+ // time — the moment the engine appeared it would read as "process changed under pane" and evict a
+ // live session. The periodic scan remains the backstop if this one is early anyway.
+ onLauncherOpened: (launcher) => {
+ // The agent IS the launcher: it exists from the moment `harness <engine>` runs, before the engine
+ // has picked a session. Binding that session comes later (onRegistered / the reconcile sweep) —
+ // which is also what makes a RESUMED session work, since resuming reports no new session id.
+ const opened = registry.openAgent({
+ agentId: launcher.launcherId,
+ engine: launcher.engine,
+ tmuxPane: launcher.tmuxPane,
+ cwd: launcher.cwd ?? null,
+ })
+ if (opened?.evicted) console.log(`[agent] ${sid(launcher.launcherId)} took pane ${launcher.tmuxPane} from ${sid(opened.evicted)}`)
+ if (opened?.isNew) {
+ console.log(`[agent] ${sid(launcher.launcherId)} opened · engine=${launcher.engine} · pane=${launcher.tmuxPane}`)
+ announceSession(opened.entry)
+ }
+ const timer = setTimeout(() => {
+ void reconcileBindings().catch((err) => {
+ console.error('[resume-discovery] bind on launcher open failed:', err instanceof Error ? err.message : err)
+ })
+ }, ENGINE_SPAWN_GRACE_MS)
+ timer.unref?.()
+ },
+ onRegistered: async (entry, meta) => {
+ // A ROTATION, not a replacement: `/clear` (claude) and `/new` (opencode) end one session id and
+ // start another in the same pane under the same launcher. That is ONE agent whose session changed —
+ // so the agent, its tab, its place in the list and its name all stay, and only the mapping moves.
+ if (meta.rebound) {
+ registry.inheritName(meta.rebound, entry.sessionId)
+ mirror.inheritSummary(meta.rebound, entry.sessionId)
+ forgetSession(meta.rebound, { force: true, keepAgent: true }) // release the old session's state
+ // The web keys its whole turn lifecycle on `dbSessionId === currentSessionId`, so a pointer at the
+ // dead session would swallow every event of the new one. Drop it first, then hand over the new id.
+ backend.send({ type: 'session_reset', payload: { staleSessionId: meta.rebound } })
+ console.log(`[agent] ${sid(entry.agentId)} rebound ${sid(meta.rebound)} → ${sid(entry.sessionId)}`)
+ } else if (meta.evicted) {
+ // A different agent held this pane and is gone.
+ forgetSession(meta.evicted, { force: true })
+ }
+ const reset = meta.isNew || (entry.engine !== 'cursor' && meta.hookEvent === 'SessionStart')
+ // Was this session BORN under an agent that was already open? Then whatever is on disk is this
+ // turn — the user's first message, typed in the terminal, which is what created the session — and
+ // the stream has to start at byte 0 to carry it. A resume (transcript older than the agent) keeps
+ // tailing from the end; its history is `session_get`'s job.
+ const bornAfterAgent = meta.isNew && !meta.rebound && entry.boundAt !== null
+ && entry.boundAt - entry.registeredAt > 0
+ && !!entry.transcriptPath
+ && await statBirthMs(entry.transcriptPath) >= entry.registeredAt
+ void attachSession(entry, reset, entry.engine === 'cursor', bornAfterAgent).then((attached) => {
+ if (!attached) return
+ syncRecapPool()
+ if (!meta.isNew) return
+ // A name the user set BEFORE this agent had a session was stored under the agent id — which is
+ // minted fresh on every launch. Move it onto the session id, where names live: that is what makes
+ // it come back on a `--resume`, and what stops it dying with the launcher.
+ registry.inheritName(entry.agentId, entry.sessionId)
+ announceToDeviceOnce(entry) // upsert the agent; skip re-announce on catch-hook re-register
+ // EVERY bind announces its session — the first one as much as a rotation. An agent that opened
+ // without one answers `sessions_list` with nothing, so the web holds no `currentSessionId` and
+ // silently drops the whole first turn; this is what hands it the id its events will carry.
+ backend.send({
+ type: 'session_synced',
+ payload: {
+ sessionId: entry.sessionId,
+ agentId: entry.agentId,
+ title: projectDisplayName(entry),
+ createdAt: new Date(entry.boundAt ?? Date.now()).toISOString(),
+ },
+ })
+ const held = pendingBeforeBind.get(entry.agentId)
+ if (held?.length) {
+ pendingBeforeBind.delete(entry.agentId)
+ console.log(`[msg] ${sid(entry.agentId)} flushing ${held.length} message(s) held before bind`)
+ for (const text of held) input.submit(entry.agentId, text)
+ }
+ })
+ },
+ onSessionEnd,
+ // Command Code's PreToolUse — the one live "a turn is running" signal this engine has. Without it the
+ // adapter only learned of a turn from Stop, and emitted turn_started+turn_ended in the same
+ // millisecond, so the device tile jumped from idle straight to the recap with no working state.
+ onTurnStart: ({ sessionId }) => {
+ const session = registry.resolve(sessionId)
+ if (!session || session.engine !== 'commandcode') return
+ const normalizer = commandcodeNormalizers.get(sessionId)
+ if (!normalizer) return
+ emitSessionEvents(sessionId, normalizer.openTurn()) // no-op after the turn's first tool call
+ },
+ onToolStart: ({ sessionId, toolUseId, toolName, input: toolInput }) => {
+ if (toolName === 'Task') onCursorTaskStart(sessionId, toolUseId, toolInput)
+ },
+ onTurnStop: ({ sessionId, status }) => {
+ const session = registry.resolve(sessionId)
+ if (!session) return
+ if (session.engine === 'cursor') {
+ void (async () => {
+ await cursorTaskHooks.wait(sessionId)
+ await watcher.pollSession(sessionId)
+ const normalizer = cursorNormalizers.get(sessionId)
+ if (!normalizer) return
+ cursorSubagents.closeParent(sessionId, status === 'error')
+ const closing = normalizer.closeTurn()
+ emitSessionEvents(sessionId, closing)
+ // Cursor can fail a turn BEFORE it writes anything to the transcript — observed as a Stop hook
+ // with status=error 2.4s after beforeSubmitPrompt, with no transcript file discovered and no
+ // rows to read. The normalizer never opened a turn, so closeTurn() returns nothing, so nothing
+ // reaches the device: the tile just sits on the previous recap forever while the user waits.
+ //
+ // Every other engine already routes its failures through announceTurnAborted (codex, devin,
+ // commandcode); cursor was the one that stayed silent. Announce only when the close produced no
+ // events — if there WAS output, the `done` event above already tells the device the turn ended.
+ if (status === 'error' && closing.length === 0) {
+ announceTurnAborted(sessionId, 'cursor', 'Cursor ended the turn with an error before producing any output')
+ }
+ setTimeout(() => void removeCursorPendingTasks(env.ADAPTER_DATA_DIR, sessionId), 2_500)
+ })().catch((err) => {
+ console.error('[cursor] stop hook failed:', err instanceof Error ? err.message : err)
+ })
+ return
+ }
+ // claude: authoritative turn-close from the Stop/StopFailure hook. Drain any un-read JSONL FIRST
+ // (may emit the real turn_ended → st.turnOpen already false); only force-close if still open. A
+ // later real end_turn line is then a no-op (lineToEvents guards on state.turnOpen). This closes
+ // the B1/B2 cases (max_tokens/refusal/API-error/wedged tool) the JSONL parse would otherwise miss.
+ // Command Code has no UserPromptSubmit and commits records per turn, so Stop is its authoritative
+ // close: drain the transcript first (the natural close usually wins), then force-close what's left.
+ if (session.engine === 'commandcode') {
+ void (async () => {
+ await watcher.pollSession(sessionId)
+ const normalizer = commandcodeNormalizers.get(sessionId)
+ if (!normalizer?.turnOpen) return
+ await new Promise((r) => setTimeout(r, STOP_HOOK_GRACE_MS))
+ await watcher.pollSession(sessionId)
+ if (!normalizer.turnOpen) return
+ normalizer.closeTurn()
+ console.log(`[turn] ${sid(sessionId)} force-closed by Stop hook (after grace)`)
+ emitSessionEvents(sessionId, [{ type: 'turn_ended', payload: {} }])
+ })().catch((err) => {
+ console.error('[hooks] commandcode stop hook failed:', err instanceof Error ? err.message : err)
+ })
+ return
+ }
+ // Devin: same deal, except the un-read history is in SQLite rather than a file, so the drain is the
+ // reader's own poll. Its rows only land once the model round-trip commits, so the grace matters.
+ if (session.engine === 'devin') {
+ void (async () => {
+ const reader = devinReaders.get(sessionId)
+ if (!reader?.turnOpen) return
+ await new Promise((r) => setTimeout(r, STOP_HOOK_GRACE_MS))
+ if (!reader.turnOpen) return
+ reader.closeTurn()
+ console.log(`[turn] ${sid(sessionId)} force-closed by Stop hook (after grace)`)
+ emitSessionEvents(sessionId, [{ type: 'turn_ended', payload: {} }])
+ })().catch((err) => {
+ console.error('[hooks] devin stop hook failed:', err instanceof Error ? err.message : err)
+ })
+ return
+ }
+ if (session.engine !== 'claude') return
+ void (async () => {
+ await watcher.pollSession(sessionId)
+ // A Stop hook is the one precise "the engine stopped writing" signal we get. When the mirror is
+ // HOLDING a turn-end for finished async sub-agents, this is what tells it the wrap-up message is
+ // on disk — without it the recap fires on its settle timer and can beat claude's closing summary
+ // to the punch (measured: recap at 10:18:41, wrap-up written at 10:18:44).
+ mirror.noteEngineStopped(sessionId)
+ if (!turnStates.get(sessionId)?.turnOpen) return // natural JSONL close already won → nothing to do
+ // Still open: the transcript may just be lagging the Stop hook. Wait, re-poll, and only force-close
+ // if it STILL hasn't closed — a genuinely wedged turn, whose assistant text is on disk by now.
+ await new Promise((r) => setTimeout(r, STOP_HOOK_GRACE_MS))
+ await watcher.pollSession(sessionId)
+ const st = turnStates.get(sessionId)
+ if (st?.turnOpen) {
+ st.turnOpen = false
+ st.pendingTools.clear()
+ console.log(`[turn] ${sid(sessionId)} force-closed by ${status === 'error' ? 'StopFailure' : 'Stop'} hook (after grace)`)
+ emitSessionEvents(sessionId, [{ type: 'turn_ended', payload: {} }])
+ }
+ })().catch((err) => {
+ console.error('[hooks] claude stop hook failed:', err instanceof Error ? err.message : err)
+ })
+ },
+ // `harness pair <code>` → run CPace toward the waiting browser; map the result to an HTTP outcome.
+ onPair: async (code) => {
+ const r = await backend.pair(code)
+ if (r.ok) return { status: 200, body: { label: r.label, fingerprint: r.fingerprint } }
+ const codeMap: Record<string, number> = {
+ NO_INTENT: 409, EXPIRED: 409, CODE_MISMATCH: 403, BACKEND_DOWN: 503,
+ RATE_LIMITED: 429, BUSY: 409, TIMEOUT: 504,
+ }
+ return { status: codeMap[r.error] ?? 400, body: { error: r.error } }
+ },
+ onSetupLink: () => {
+ const r = backend.createSetupToken()
+ return { status: 200, body: { url: setupBrowserLink(backend.machineId, r.token), expiresAt: r.expiresAt, fingerprint: r.fingerprint } }
+ },
+ onListPairs: () => ({ status: 200, body: { pairs: backend.listPairs() } }),
+ onRevoke: (id) => {
+ const r = backend.revoke(id)
+ if (r.ok) return { status: 200, body: { label: r.label, fingerprint: r.fingerprint } }
+ return { status: r.error === 'AMBIGUOUS' ? 409 : 404, body: { error: r.error } }
+ },
+ onRevokeAll: () => ({ status: 200, body: backend.revokeAll() }),
+ // Local dashboard (GET /api/status): adapter health + computer fingerprint + local pairings. It
+ // deliberately does NOT expose chat/transcripts — those live in the cloud web (WEB_URL/commander).
+ onStatus: () => ({
+ machineId: backend.machineId,
+ version: VERSION,
+ backendUrl: env.BACKEND_WS_URL,
+ webUrl: env.WEB_URL,
+ connected: backend.isConnected(),
+ deviceTransportConnected: backend.hasCommander(),
+ deviceE2eeConnected: backend.deviceE2eeConnected(),
+ uptimeSec: Math.round((Date.now() - startedAt) / 1000),
+ fingerprint: backend.e2eeFingerprint(),
+ config: { watching: 'tmux Claude + Codex + Cursor + OpenCode + Pi + Hermes + Command Code + Devin sessions', 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 })),
+ pairs: backend.listPairs(),
+ pending: backend.pendingPair(),
+ }),
+ onLogs: () => {
+ try { return readFileSync(LOG_FILE, 'utf-8').split('\n').slice(-120).join('\n') } catch { return '' }
+ },
+ onStop: () => { setTimeout(() => process.kill(process.pid, 'SIGTERM'), 50) }, // let the 200 flush first
+ })
+ // Install both CLI hooks with the port the local server actually bound.
+ if (!env.DISABLE_HOOK_INSTALL) {
+ installSessionHooks(hookPort)
+ installCodexHooks(hookPort)
+ installCursorHooks(hookPort)
+ installOpencodePlugin(hookPort)
+ installPiExtension(hookPort)
+ installHermesHooks(hookPort)
+ installDevinHooks(hookPort)
+ installCommandCodeHooks(hookPort)
+ }
+ backend.setDashboardPort(hookPort) // surfaced to the web (e2e_status) so it can link here to approve
+ console.log(`[cli] local dashboard → http://127.0.0.1:${hookPort}`)
+
+ // JSONL watcher → normalize each appended line → stream up. ONE lineToEvents pass feeds BOTH
+ // audiences: web (send, ServerEvents) and device (mirror.ingest → curated commander_event cards).
+ watcher.on('line', (evt: LineEvent) => {
+ // 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
+ const session = registry.bySession(evt.sessionId)
+ if (!session || session.engine !== evt.engine) return
+ runtimeProfiles.ingest(session, evt.text)
+ let events
+ if (session.engine === 'codex') {
+ let normalizer = codexNormalizers.get(evt.sessionId)
+ if (!normalizer) { normalizer = new CodexNormalizer('live'); codexNormalizers.set(evt.sessionId, normalizer) }
+ events = normalizer.ingest(evt.text)
+ // Codex rides its failure ON task_complete, so the turn closes by itself — but with no text and
+ // no reason, which reads as "the agent answered nothing". Announce the reason ahead of the
+ // turn_ended that `events` carries.
+ const taskError = codexTaskError(evt.text)
+ if (taskError !== null) announceTurnAborted(evt.sessionId, 'codex', taskError)
+ } else if (session.engine === 'cursor') {
+ let normalizer = cursorNormalizers.get(evt.sessionId)
+ if (!normalizer) {
+ normalizer = new CursorNormalizer('live', evt.sessionId)
+ cursorNormalizers.set(evt.sessionId, normalizer)
+ }
+ events = normalizer.ingest(evt.text)
+ } else if (session.engine === 'pi') {
+ let normalizer = piNormalizers.get(evt.sessionId)
+ if (!normalizer) { normalizer = new PiNormalizer('live'); piNormalizers.set(evt.sessionId, normalizer) }
+ events = normalizer.ingest(evt.text)
+ } else if (session.engine === 'commandcode') {
+ let normalizer = commandcodeNormalizers.get(evt.sessionId)
+ if (!normalizer) { normalizer = new CommandCodeNormalizer('live'); commandcodeNormalizers.set(evt.sessionId, normalizer) }
+ events = normalizer.ingest(evt.text)
+ // Command Code fires no Stop hook for a failed turn: this record IS the notification. `ingest`
+ // already closed the turn (its turn_ended is in `events`, emitted just below) — announce the
+ // reason first so the web/device show the error ahead of the turn closing.
+ const runError = commandCodeRunError(evt.text)
+ if (runError !== null) {
+ announceTurnAborted(evt.sessionId, 'commandcode', runError, commandCodeRunErrorSummary(runError))
+ }
+ } else {
+ let st = turnStates.get(evt.sessionId)
+ if (!st) { st = newTurnState(); turnStates.set(evt.sessionId, st) }
+ events = lineToEvents(evt.text, st)
+ }
+ emitSessionEvents(evt.sessionId, events)
+ } catch (err) {
+ console.error(`[cli] line handler error (session ${evt.sessionId}):`, err instanceof Error ? err.message : err)
+ }
+ })
+ for (const session of registry.list()) {
+ // An UNBOUND agent has no transcript to attach to yet — its launcher is alive (or the 15s sweep above
+ // will drop it) and the reconcile pass 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)
+ else {
+ input.setTurnOpen(
+ session.agentId,
+ turnStates.get(session.sessionId)?.turnOpen
+ ?? codexNormalizers.get(session.sessionId)?.turnOpen
+ ?? cursorNormalizers.get(session.sessionId)?.turnOpen
+ ?? opencodeReaders.get(session.sessionId)?.turnOpen
+ ?? piNormalizers.get(session.sessionId)?.turnOpen
+ ?? hermesReaders.get(session.sessionId)?.turnOpen
+ ?? devinReaders.get(session.sessionId)?.turnOpen
+ ?? commandcodeNormalizers.get(session.sessionId)?.turnOpen
+ ?? false,
+ )
+ }
+ }
+ watcher.start()
+ await cursorDiscovery.start()
+ await reconcileBindings()
+ const tmuxResumeDiscoveryTimer = setInterval(() => {
+ void reconcileBindings().catch((err) => {
+ console.error('[resume-discovery] tmux resume scan failed:', err instanceof Error ? err.message : err)
+ })
+ }, env.TMUX_REAP_INTERVAL_MS)
+ for (const task of await loadCursorPendingTasks(env.ADAPTER_DATA_DIR)) {
+ onCursorTaskStart(task.sessionId, task.toolUseId, task.input)
+ }
+
+ // Reconciliation is deliberately full: drain every transcript to EOF, inspect each live pane, then
+ // publish every session even when Model/Effort did not change. Reconnect runs the same path, while
+ // JSONL watcher events still provide immediate local-to-web updates between these safety passes.
+ let reconcileInFlight: Promise<void> | null = null
+ let reconcileNeedsDeviceAnnouncement = false
+ fullReconcile = (announceDevice = false): Promise<void> => {
+ reconcileNeedsDeviceAnnouncement ||= announceDevice
+ if (reconcileInFlight) return reconcileInFlight
+ reconcileInFlight = (async () => {
+ await runtimeProfiles.withoutChangeEvents(async () => {
+ 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)
+ if (capture) runtimeProfiles.ingestPane(session, capture, true)
+ }))
+ })
+ await syncPaneTitles()
+ const includeDevice = reconcileNeedsDeviceAnnouncement
+ reconcileNeedsDeviceAnnouncement = false
+ for (const session of registry.list()) {
+ if (includeDevice) announceSession(session)
+ else syncSession(session)
+ }
+ })().finally(() => { reconcileInFlight = null })
+ return reconcileInFlight
+ }
+ // Command Code keeps its reasoning level in a config FILE — nothing in the transcript, the pane or the
+ // session header announces a change — so without a tick of its own the chip showed a level up to five
+ // minutes stale, and never caught an effort the user changed in the CLI. Costs a small JSON read per
+ // Command Code session; ingestConfig only emits a change event when the value actually moved.
+ const COMMANDCODE_CONFIG_POLL_MS = 10_000
+ setInterval(() => {
+ for (const session of registry.list()) {
+ if (session.engine !== 'commandcode') continue
+ void runtimeProfiles.ingestConfig(session).catch(() => undefined)
+ }
+ }, COMMANDCODE_CONFIG_POLL_MS)
+
+ // Some engines announce a model change nowhere: no transcript row, no config file, no hook — the new
+ // model is simply drawn into the pane footer. The 5-minute reconcile was the only reader, so switching
+ // model in the terminal took up to five minutes to reach the device.
+ //
+ // devin — the footer is the ONLY source; nothing else ever reports the model.
+ // cursor — the transcript carries the model but never the reasoning level, and the level only exists
+ // in the footer. Without this poll a Cursor session picks up its effort once at attach and
+ // then never again.
+ //
+ // Read just the footer, and only while such a session exists. NOT silent: a real change has to push to
+ // the device, which is the whole point.
+ const PANE_POLLED_ENGINES = new Set(['devin', 'cursor'])
+ const PANE_POLL_MS = 15_000
+ setInterval(() => {
+ for (const session of registry.list()) {
+ if (!PANE_POLLED_ENGINES.has(session.engine)) continue
+ void captureTmuxPane(session.tmuxPane, 60)
+ .then((capture) => { if (capture) runtimeProfiles.ingestPane(session, capture) })
+ .catch(() => undefined)
+ }
+ }, PANE_POLL_MS)
+
+ const RUNTIME_RECONCILE_MS = 5 * 60_000
+ const runtimeReconcileTimer = setInterval(() => {
+ void fullReconcile().catch((err) => {
+ console.error('[runtime-profile] periodic reconcile failed:', err instanceof Error ? err.message : err)
+ })
+ }, 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)
+ })
+ }, PANE_TITLE_SYNC_MS)
+
+ // A device joined mid-turn (count rise or join generation; no adapter heartbeat) → replay live state.
+ backend.onCommanderJoin = () => { mirror.replayAll(); questionWatcher.reset() } // re-announce an open question
+ backend.onCommanderPresenceChanged = (connected) => {
+ setSummaryPoolDeviceConnected(connected)
+ setVoiceRouterDeviceConnected(connected) // warm the voice-router worker while a device is connected
+ }
+
+ // Web cancel (C-c) interrupts the turn — claude writes no end_turn line to close it, so stop the
+ // heartbeat and mark the turn closed here (mirrors the hosted runtime stopping its heartbeat on cancel). We do
+ // NOT emit turn_ended: the web clears its own dots on cancel, and a turn_ended would fire a device
+ // recap for a killed turn. The next real prompt reopens a fresh turn.
+ backend.onCancel = (id) => {
+ const record = registry.resolve(id)
+ const sessionId = record?.sessionId ?? id
+ const st = turnStates.get(sessionId)
+ if (st) st.turnOpen = false
+ codexNormalizers.get(sessionId)?.closeTurn()
+ cursorNormalizers.get(sessionId)?.closeTurn()
+ opencodeReaders.get(sessionId)?.closeTurn()
+ piNormalizers.get(sessionId)?.closeTurn()
+ hermesReaders.get(sessionId)?.closeTurn()
+ devinReaders.get(sessionId)?.closeTurn()
+ commandcodeNormalizers.get(sessionId)?.closeTurn()
+ cursorSubagents.forget(sessionId)
+ input.cancel(record?.agentId ?? sessionId)
+ stopHeartbeat(sessionId)
+ questionWatcher.stop(sessionId)
+ mirror.cancel(sessionId) // close the device's "Working…" tile (bare done, no recap) — a cancel emits no turn_ended
+ }
+
+ /**
+ * Web or device deleted an agent (`agent_delete`): end the AGENT, not the user's window.
+ *
+ * This used to `tmux kill-pane`, which took the pane down — and with it the window, and the session if
+ * that pane was the last one. The pane is the user's; only the launcher and its engine belong to us. So
+ * the launcher is asked to shut its child down, and the daemon verifies afterwards (some launchers in
+ * the wild are too old to know the frame — see terminateDeletedAgent).
+ *
+ * `registry.remove` + `mirror.forget` keep the recap AND the agent-name override for a later resume.
+ */
+ backend.onDeleteAgent = (sessionId) => {
+ const s = registry.resolve(sessionId) // BEFORE forgetSession — that removes it from the registry
+ // The engine outlives this call by a second or two now, and its catch hook fires on every turn
+ // boundary. Without the tombstone that hook re-registers the session and the tile comes straight back.
+ markDeleted(sessionId)
+ const launcher = s ? launcherSessions.get(s.launcherId) : undefined
+ if (launcher) {
+ try { launcher.socket.send(JSON.stringify({ t: 'exit', reason: 'deleted' })) } catch { /* the fallback covers it */ }
+ }
+ forgetSession(sessionId, { force: true })
+ if (!s) return
+ void terminateDeletedAgent(s, {
+ isAlive: validateSessionRuntime,
+ kill: (pid, signal) => process.kill(pid, signal),
+ sleep: (ms) => new Promise((resolve) => { const t = setTimeout(resolve, ms); t.unref?.() }),
+ log: (message) => console.log(message),
+ }).then((outcome) => {
+ console.log(`[delete] ${sid(sessionId)} ${s.engine} · ${outcome}`)
+ // Provably gone ⇒ nothing left that could re-register, so stop blocking the id early.
+ if (outcome !== 'failed') clearDeleted(sessionId)
+ }).catch((err) => {
+ console.error('[delete] fallback failed:', err instanceof Error ? err.message : err)
+ })
+ }
+
+ backend.onMessage = (id, content) => {
+ const record = registry.resolve(id)
+ const sessionId = record?.sessionId ?? id
+ const engine = record?.engine ?? 'claude'
+ // The backend prepends `/goal ` or `/loop ` without knowing the engine (on the routed path it has
+ // not picked an agent yet when the mode is chosen). This is the one place that always knows, so the
+ // per-engine adaptation happens here — an unknown slash command would otherwise land as a visible
+ // 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)} recv · engine=${engine} · len=${adapted.length} · "${preview(adapted)}"`)
+ if (record && !record.sessionId) {
+ const held = pendingBeforeBind.get(record.agentId) ?? []
+ held.push(adapted)
+ pendingBeforeBind.set(record.agentId, held)
+ console.log(`[msg] ${sid(record.agentId)} held · agent not started yet (${held.length} queued)`)
+ return
+ }
+ input.submit(record?.agentId ?? sessionId, adapted)
+ }
+
+ // Hard-killed panes (SessionEnd never fired) → reaper drops them.
+ const reaper = startTmuxReaper(env.TMUX_REAP_INTERVAL_MS, forgetSession)
+
+ // Keep the log file under its cap. This daemon writes it through an inherited stdout fd, so a size
+ // check on a timer is the only place that can see it grow — `prepareLogFile` at spawn time alone
+ // would let a long-lived, chatty daemon run unbounded between restarts.
+ const logTrimTimer = setInterval(() => {
+ if (trimLogFile(LOG_FILE)) console.log(`[log] ${tildify(LOG_FILE)} hit its size cap — dropped the oldest half`)
+ }, LOG_CHECK_INTERVAL_MS)
+ logTrimTimer.unref?.() // never hold the event loop open for log upkeep
+
+ // No machine reaper: the launcher's WebSocket is the liveness signal, so a dead launcher (clean exit,
+ // SIGKILL, or a closed terminal window) is noticed the instant its socket closes — see
+ // hookServer.ts `attachLauncherWs` → onLauncherClosed below.
+
+
+ backend.connect()
+ console.log(`[cli] dialing ${env.BACKEND_WS_URL}/api/adapter-ws · watching registered Claude + Codex + Cursor tmux sessions`)
+
+ // ── self-update: poll GCS for a newer bundle → verify+swap → restart IMMEDIATELY (supervised rollback) ──
+ //
+ // The restart used to wait for the computer to go idle. That wait was unbounded, and "idle" is a set of
+ // latches — open turn, settling composer, awaited submit, control lock, recap in flight — so ONE latch
+ // left stuck deferred the restart forever. Seen on 2026-07-31: 0.0.26 staged, then eight minutes of
+ // "deferring restart — sessions still processing" with the daemon otherwise silent. A daemon that
+ // quietly never updates is the exact failure this updater exists to prevent, so the wait is gone
+ // (owner call, 2026-07-31): staged means restart now.
+ //
+ // The cost is real and accepted: a turn streaming at that moment loses the rest of its events, and its
+ // clients see no turn_end for it until the new daemon re-attaches the session and the next turn runs.
+ let updater: Poller | null = null
+ let restarting = false
+
+ // Hand off to a freshly-spawned daemon running the just-swapped cli.js, then SUPERVISE it and roll
+ // back to the .prev bytes if it fails to come up. NOT launch() — that refuses while a daemon is alive.
+ const restartForUpdate = async (newVersion: string): Promise<void> => {
+ if (restarting) return
+ restarting = true
+ // FIRST, before any teardown: tell every pane why its agent is about to be cut off. The restart no
+ // longer waits for idle, so a turn may be streaming right now and the person watching it deserves a
+ // reason. Bounded and non-throwing (see notifyAll), so it can neither stall nor abort the restart —
+ // and deliberately not placed further down, where a later reordering of teardown could silently drop it.
+ await launcherSessions.notifyAll({
+ t: 'notice',
+ level: 'warn',
+ durationMs: 8_000,
+ text: `harness is updating (${VERSION} → ${newVersion}) — restarting now, this agent reconnects on its own`,
+ })
+ console.log(`[update] applying ${VERSION} → ${newVersion} — restarting daemon`)
+ registry.flush()
+ updater?.stop()
+ clearInterval(reaper)
+ clearInterval(logTrimTimer)
+ clearInterval(runtimeReconcileTimer)
+ clearInterval(tmuxResumeDiscoveryTimer)
+ clearInterval(paneTitleSyncTimer)
+ questionWatcher.stopAll()
+ for (const t of heartbeats.values()) clearInterval(t)
+ heartbeats.clear()
+ cursorSubagents.stop()
+ for (const r of opencodeReaders.values()) r.stop()
+ for (const r of hermesReaders.values()) r.stop()
+ for (const r of devinReaders.values()) r.stop()
+ await cursorDiscovery.stop()
+ await watcher.stop()
+ // Fully release the FIXED hook port BEFORE the child binds (no fallback → EADDRINUSE otherwise).
+ ;(hookServer as unknown as { closeAllConnections?: () => void }).closeAllConnections?.()
+ // Release the FIXED port so the child can bind, but do NOT wait for the callback and do NOT tear the
+ // launcher sockets down. Two reasons, both learned the hard way:
+ // - close() only calls back once EVERY connection has ended, and a launcher's upgraded WebSocket
+ // never ends on its own. Awaiting it wedged the restart forever with the port already shut.
+ // - terminating those sockets instead reads to the daemon as "the launcher is gone", which forgets
+ // every session and persists an EMPTY registry, so the new daemon comes up owning nothing.
+ // close() releases the listening handle synchronously; the sockets die with the process moments later.
+ hookServer.close()
+ shutdownSummaryPool()
+ shutdownVoiceRouter()
+ await backend.stop() // graceful WS close → releases the Redis machine-owner claim
+ await new Promise((r) => setTimeout(r, 1000)) // grace before the same-machine reclaim
+
+ const spawnDaemon = (extraEnv: Record<string, string>): ReturnType<typeof spawn> => {
+ prepareLogFile(LOG_FILE, LEGACY_LOG_FILE) // before the fd + the sinceOffset below, so both see one size
+ const fd = openSync(LOG_FILE, 'a')
+ const c = spawn(process.execPath, [SCRIPT_PATH, '__run'], {
+ detached: true, env: { ...process.env, ADAPTER_TOKEN: token, ...extraEnv }, stdio: ['ignore', fd, fd],
+ })
+ // A spawn failure (e.g. EMFILE) emits 'error' on the child; with no listener that is an
+ // uncaughtException. Catch it so a failed update-restart can't take the old daemon down.
+ c.on('error', (e) => console.error('[update] daemon spawn error:', e instanceof Error ? e.message : e))
+ return c
+ }
+
+ const sinceOffset = existsSync(LOG_FILE) ? statSync(LOG_FILE).size : 0
+ const child = spawnDaemon({ ADAPTER_UPDATED_TO: newVersion })
+ let childExited = false
+ child.on('exit', () => { childExited = true })
+
+ // KEEP on connected/unreachable/busy (new build RAN); ROLL BACK only on an early exit or a `fatal`
+ // (bad bundle / can't bind). unreachable = backend transient, not a bad build → don't bounce.
+ const ready = await waitForReady(sinceOffset, 30_000)
+ if (!childExited && ready.state !== 'fatal') {
+ try { writeFileSync(PID_FILE, String(child.pid) + '\n') } catch { /* ignore */ }
+ child.unref()
+ confirmUpdate(env.ADAPTER_CLI_DIR) // drop the .prev backups
+ console.log(`[update] now running ${newVersion} (pid ${child.pid})`)
+ process.exit(0)
+ }
+ console.error(`[update] new build failed to start (${childExited ? 'exited' : ready.state}) — rolling back`)
+ try { if (child.pid) process.kill(child.pid, 'SIGKILL') } catch { /* ignore */ }
+ restoreUpdate(env.ADAPTER_CLI_DIR) // restore .prev → cli.js/notify.mjs
+ const good = spawnDaemon({})
+ try { writeFileSync(PID_FILE, String(good.pid) + '\n') } catch { /* ignore */ }
+ good.unref()
+ process.exit(0)
+ }
+
+ // Staged → restart, right now. `restartForUpdate` already latches on `restarting`, so a second call
+ // (e.g. the poller staging again before teardown finishes) is a no-op rather than two daemons.
+ const applyUpdate = (version: string): void => {
+ // If the restart handoff itself throws/rejects (I/O fault during teardown), don't let it become an
+ // unhandledRejection — log, un-latch `restarting`, and stay on the current build until the next poll.
+ void restartForUpdate(version).catch((err) => {
+ console.error('[update] restart failed — staying on current build:', err instanceof Error ? err.message : err)
+ restarting = false
+ })
+ }
+
+ // Self-update ONLY manages the INSTALLED copy (`~/.harness/cli/cli.js`). A dev/repo run — `tsx`
+ // (`npm run dev`) OR `node dist/cli.js` from the checkout — must NEVER self-update: it would swap
+ // the published bundle into ~/.harness/cli and restart, hijacking the version you're developing.
+ // Match by inode so symlinks/realpath don't fool it; fall back to a path compare.
+ const installedCli = join(env.ADAPTER_CLI_DIR, 'cli.js')
+ let isInstalledCopy = SCRIPT_PATH === installedCli
+ try { isInstalledCopy = statSync(SCRIPT_PATH).ino === statSync(installedCli).ino } catch { /* keep path compare */ }
+ if (isInstalledCopy && !env.ADAPTER_UPDATE_DISABLE) {
+ updater = startSelfUpdater({
+ currentVersion: VERSION,
+ url: env.ADAPTER_UPDATE_URL,
+ key: env.ADAPTER_UPDATE_KEY,
+ dir: env.ADAPTER_CLI_DIR,
+ intervalMs: env.ADAPTER_UPDATE_CHECK_MS,
+ onStaged: (v) => applyUpdate(v),
+ })
+ console.log(`[update] self-update on · v${VERSION} · every ${Math.round(env.ADAPTER_UPDATE_CHECK_MS / 1000)}s`)
+ } else if (!env.ADAPTER_UPDATE_DISABLE) {
+ console.log(`[update] self-update off · running a dev/repo build (v${VERSION}), not the installed copy`)
+ }
+
+ const shutdown = async (signal: string): Promise<void> => {
+ console.log(`\n[cli] ${signal} — shutting down`)
+ updater?.stop()
+ clearInterval(reaper)
+ clearInterval(logTrimTimer)
+ clearInterval(runtimeReconcileTimer)
+ clearInterval(tmuxResumeDiscoveryTimer)
+ clearInterval(paneTitleSyncTimer)
+ questionWatcher.stopAll()
+ for (const t of heartbeats.values()) clearInterval(t)
+ heartbeats.clear()
+ cursorSubagents.stop()
+ for (const r of opencodeReaders.values()) r.stop()
+ for (const r of hermesReaders.values()) r.stop()
+ for (const r of devinReaders.values()) r.stop()
+ await cursorDiscovery.stop()
+ await watcher.stop()
+ hookServer.close()
+ shutdownSummaryPool()
+ shutdownVoiceRouter()
+ await backend.stop()
+ try { if (readPid() === process.pid) rmSync(PID_FILE, { force: true }) } catch { /* ignore */ }
+ process.exit(0)
+ }
+ process.on('SIGINT', () => void shutdown('SIGINT'))
+ process.on('SIGTERM', () => void shutdown('SIGTERM'))
+ process.on('exit', () => { shutdownSummaryPool(); shutdownVoiceRouter() })
+
+ // This machine was deleted/revoked (from the web, or a 401 on reconnect) → clear the saved credential
+ // and shut down. The user reconnects by copying a fresh token from the machine page.
+ backend.onRevoked = () => {
+ console.log('[cli] this computer was removed from the machine — clearing credentials and stopping')
+ try { rmSync(TOKEN_FILE, { force: true }) } catch { /* ignore */ }
+ void shutdown('revoked')
+ }
+
+ // Mirror the machine's display name to disk so `harness status` (a separate process) can print it.
+ backend.onMachineMeta = (name) => {
+ try {
+ if (name) writeFileSync(MACHINE_NAME_FILE, name + '\n')
+ else rmSync(MACHINE_NAME_FILE, { force: true })
+ } catch { /* best effort */ }
+ }
+
+ // This machine is already connected from ANOTHER machine (HTTP 409). The credential is valid — it's
+ // just in use elsewhere — so KEEP the token and stop (no retry loop, no token prompt). The
+ // '[backend] machine busy' marker is what the detached parent's waitForReady() greps for.
+ backend.onBusy = () => {
+ console.log('[backend] machine busy — this machine is already connected from another computer; stopping')
+ void shutdown('busy')
+ }
+}
+
+// ── info block ───────────────────────────────────────────────────────────────────────────────────
+
+/**
+ * The version of the daemon that is ACTUALLY running, asked of the daemon itself.
+ *
+ * `VERSION` is a constant baked into whichever bundle is doing the printing, and that is not always the
+ * one running: `harness update` downloads a new build, spawns it, and then prints this block — all from
+ * the OLD process — so the block announced the version it was replacing (`✓ installed v0.0.22` followed
+ * by `version v0.0.20`). Every other row here is a fact about the daemon (pid, sessions, dashboard); this
+ * makes the version one too. Falls back to the local constant when the daemon cannot be reached, which is
+ * exactly the case where the printing process IS the only build there is.
+ */
+async function runningDaemonVersion(): Promise<string> {
+ try {
+ const res = await fetch(`http://127.0.0.1:${daemonPort()}/api/status`, {
+ signal: AbortSignal.timeout(1_500),
+ })
+ if (!res.ok) return VERSION
+ const body: unknown = await res.json()
+ const version = (body as { version?: unknown } | null)?.version
+ return typeof version === 'string' && version ? version : VERSION
+ } catch {
+ return VERSION
+ }
+}
+
+// `status` is a definitive state — `launch` only prints this after "[backend] connected" (so it's
+// "● connected", never a one-shot never-updating "connecting…"); `status` prints running/stopped.
+function printInfoBlock(opts: {
+ status: string; pid: number; token: string; sessions: number; version: string
+}): void {
+ const link = `${env.WEB_URL.replace(/\/$/, '')}/machine/${agentIdFromToken(opts.token)}`
+ const row = (k: string, v: string): string => ` ${k.padEnd(10)} ${v}`
+ const rule = ' ' + '─'.repeat(37)
+ console.log('')
+ console.log(' machine · remote machine connected')
+ console.log(rule)
+ console.log(row('status', opts.status))
+ // Display name mirrored from the backend by the daemon (machine_meta) — only shown when named.
+ const machineName = ((): string => {
+ try { return readFileSync(MACHINE_NAME_FILE, 'utf-8').trim() } catch { return '' }
+ })()
+ if (machineName) console.log(row('machine', machineName))
+ console.log(row('version', `v${opts.version}`))
+ console.log(row('backend', env.BACKEND_WS_URL))
+ console.log(row('watching', tildify(env.CLAUDE_PROJECTS_DIR)))
+ console.log(row('agents', `${opts.sessions} running`))
+ console.log(row('pid', String(opts.pid)))
+ console.log(row('logs', tildify(LOG_FILE)))
+ console.log(row('dashboard', `http://127.0.0.1:${daemonPort()}`))
+ console.log(rule)
+ console.log(' ▸ Open in your browser to chat with this computer:')
+ console.log(` ${link}`)
+ console.log(' ▸ Set up a browser:')
+ console.log(' harness browser-link')
+ console.log(' running in background · stop with: harness stop')
+ console.log('')
+}
+
+// 'fatal' = misconfig; retrying is pointless → kill the daemon + error out.
+// 'unreachable' = transient (backend deploying / 5xx / slow / not up yet) → the daemon keeps retrying
+// in the background and connects on its own, so DON'T kill it — just report the state.
+// 'deauth' = the saved credential is invalid/revoked (401/403) → clear it and ask for a fresh token.
+// 'busy' = this machine is already connected from another computer (409) → keep token, stop, inform.
+interface ReadyResult { state: 'connected' | 'deauth' | 'fatal' | 'unreachable' | 'busy'; detail?: string }
+
+/** Classify a backend connection error from the log tail: a human reason + fatal (won't self-heal) vs
+ * transient (will), and `deauth` for 401/403 (the token is no longer valid). null = no signal yet. */
+function connectFailure(tail: string): { detail: string; fatal: boolean; deauth?: boolean; busy?: boolean } | null {
+ // The daemon logs this marker when the backend rejected us with 409 (machine held by another computer).
+ if (tail.includes('[backend] machine busy')) {
+ return { detail: 'this machine is already connected from another computer', fatal: true, busy: true }
+ }
+ // The daemon couldn't bind the (fixed) hook port → another adapter is almost certainly already
+ // running. Fatal: don't sit on "retrying"; tell the user how to find/stop the other one.
+ if (/EADDRINUSE|already in use/.test(tail)) {
+ return { detail: `hook port ${env.PORT} is already in use — is another machine daemon running? (harness stop, or lsof -ti :${env.PORT} | xargs kill)`, fatal: true }
+ }
+ const m = tail.match(/Unexpected server response: (\d+)/)
+ if (m) {
+ const code = Number(m[1])
+ // 401/403 = this computer's machine was deleted/revoked (or a bad token) → deauth: clear + re-join.
+ // 409 = one machine per machine: already connected from another computer → busy (keep token, stop).
+ // 404 = wrong backend / route not deployed → misconfig (fatal, don't wipe the token).
+ // 5xx (esp. 502/503/504) = gateway up but the app is deploying/restarting → transient, keep retrying.
+ if (code === 409) return { detail: 'this machine is already connected from another computer', fatal: true, busy: true }
+ const deauth = code === 401 || code === 403
+ return { detail: `backend returned HTTP ${code}`, fatal: deauth || code === 404, deauth }
+ }
+ if (/ENOTFOUND|EAI_AGAIN|getaddrinfo/.test(tail)) return { detail: 'host not found (DNS)', fatal: true }
+ if (/certificate|CERT_|self-signed/i.test(tail)) return { detail: 'TLS certificate error', fatal: true }
+ if (/ECONNREFUSED/.test(tail)) return { detail: 'connection refused', fatal: false } // backend not up yet → retry
+ // A 1006 close with no HTTP code — generic "couldn't reach it right now"; transient.
+ if (/disconnected \(close 1006\)/.test(tail)) return { detail: 'cannot reach backend', fatal: false }
+ return null
+}
+
+/** Poll the log until the adapter connects, hits a FATAL error, or the window ends. Transient errors
+ * don't short-circuit — the connection may recover within the window (e.g. a 502 during a deploy). */
+async function waitForReady(sinceOffset: number, timeoutMs = 8000): Promise<ReadyResult> {
+ const deadline = Date.now() + timeoutMs
+ let lastTransient: string | undefined
+ while (Date.now() < deadline) {
+ let tail = ''
+ // Slice the raw BYTES from sinceOffset (a Buffer byte length) THEN decode. The log is full of
+ // multi-byte glyphs (→ · ─ ● …), so decoding first and slicing the STRING by that byte count
+ // overshoots (byte length > char length) and returns "" — the classic false "no connection".
+ try { tail = readFileSync(LOG_FILE).subarray(sinceOffset).toString('utf-8') } catch { /* not yet */ }
+ if (tail.includes('[backend] connected')) return { state: 'connected' }
+ const fail = connectFailure(tail)
+ if (fail?.busy) return { state: 'busy', detail: fail.detail }
+ if (fail?.deauth) return { state: 'deauth', detail: fail.detail }
+ if (fail?.fatal) return { state: 'fatal', detail: fail.detail }
+ if (fail) lastTransient = fail.detail // remember, but keep waiting — it may connect on a retry
+ await new Promise((r) => setTimeout(r, 250))
+ }
+ return { state: 'unreachable', detail: lastTransient ?? `no connection within ${timeoutMs / 1000}s` }
+}
+
+// ── launcher / stop / status ───────────────────────────────────────────────────────────────────
+
+/** Daemonize (or run inline) + print the info block. Returns 'deauth' when the saved credential was
+ * rejected (401/403) so the caller (`joinCommand`) can ask for a fresh token; otherwise it exits. */
+async function launch(token: string, foreground: boolean): Promise<'deauth' | void> {
+ // Foreground mode (supervisor) OR dev/tsx (can't cleanly spawn a .ts detached) → run inline. A 401/403
+ // there is handled by backendSocket.onRevoked (clears token + shuts down); no token prompt inline.
+ if (foreground || SCRIPT_PATH.endsWith('.ts')) {
+ if (!foreground) console.log('[cli] dev mode — running in the foreground (Ctrl-C to stop)')
+ await runForeground(token)
+ return
+ }
+
+ const running = readPid()
+ if (running && isAlive(running)) {
+ console.log(`machine already running (pid ${running}) — it auto-reconnects.`)
+ console.log(' check: harness status · stop: harness stop')
+ process.exit(0)
+ }
+
+ mkdirSync(env.ADAPTER_DATA_DIR, { recursive: true })
+ prepareLogFile(LOG_FILE, LEGACY_LOG_FILE) // adopt an older name + enforce the cap before we tail from here
+ const logOffset = existsSync(LOG_FILE) ? readFileSync(LOG_FILE).length : 0
+ const logFd = openSync(LOG_FILE, 'a')
+ const child = spawn(process.execPath, [SCRIPT_PATH, '__run'], {
+ detached: true,
+ env: { ...process.env, ADAPTER_TOKEN: token },
+ stdio: ['ignore', logFd, logFd],
+ })
+ writeFileSync(PID_FILE, String(child.pid) + '\n')
+ child.unref()
+
+ const ready = await waitForReady(logOffset, CONNECT_WAIT_MS)
+
+ // DEAUTH (401/403): the saved credential is no longer valid — this computer was removed from the machine
+ // (or the token is stale). Wipe it, stop the daemon, and signal the caller to ask for a fresh token.
+ if (ready.state === 'deauth') {
+ try { if (child.pid) process.kill(child.pid, 'SIGTERM') } catch { /* ignore */ }
+ rmSync(PID_FILE, { force: true })
+ rmSync(TOKEN_FILE, { force: true })
+ return 'deauth' // caller decides what to say (saved-token vs. explicit-token error)
+ }
+
+ // BUSY (409): one machine per machine — this machine is already connected from another computer. The
+ // credential is valid, just in use elsewhere, so KEEP the token; stop the daemon and inform (not a
+ // failure, not a retry loop). The user stops the other machine first, then runs `harness join` here.
+ if (ready.state === 'busy') {
+ try { if (child.pid) process.kill(child.pid, 'SIGTERM') } catch { /* ignore */ }
+ rmSync(PID_FILE, { force: true })
+ // NB: TOKEN_FILE is intentionally NOT removed — the credential is valid.
+ console.log('\n ℹ This machine is already connected from another computer.')
+ console.log(' Only one machine per machine — stop the adapter on that machine first,')
+ console.log(' then run `harness join` here again.')
+ process.exit(0)
+ }
+
+ // FATAL misconfig (wrong route → 404, DNS, TLS): retrying is pointless → kill the daemon and say what
+ // to fix. (Not 401/403 — those are handled as deauth above.)
+ if (ready.state === 'fatal') {
+ try { if (child.pid) process.kill(child.pid, 'SIGTERM') } catch { /* ignore */ }
+ rmSync(PID_FILE, { force: true })
+ // A hook-port clash isn't a backend problem — it's a duplicate/leftover adapter. Report it as such.
+ if (ready.detail?.startsWith('hook port')) {
+ console.error(`\n✗ ${ready.detail}`)
+ console.error(` logs ${tildify(LOG_FILE)}`)
+ } else {
+ console.error(`\n✗ Could not connect to the backend: ${ready.detail}`)
+ console.error(` backend ${env.BACKEND_WS_URL}`)
+ console.error(` logs ${tildify(LOG_FILE)}`)
+ console.error(' If this computer was removed from your machine, copy a fresh token and run: harness join <token>')
+ }
+ process.exit(1)
+ }
+
+ // Not connected YET, but transient (backend deploying / 5xx / slow / not up). The daemon is alive and
+ // retries with backoff — it will connect on its own — so leave it running and say so plainly (never a
+ // meaningless one-shot "connecting…"). The user runs `harness join` once, not on a babysitting loop.
+ if (ready.state === 'unreachable') {
+ // Lead with the RUNNING state (+ pid), not the error — the daemon IS started and self-retrying, so
+ // seeing a pid / "harness stop" later isn't a surprise. This is not a failure; it reconnects itself.
+ console.log(`\n● adapter started · running in the background · pid ${child.pid}`)
+ console.log(` Not connected yet — ${ready.detail}. It keeps retrying and connects on its own`)
+ console.log(' when the backend is reachable — no need to re-run.')
+ console.log(` backend ${env.BACKEND_WS_URL}`)
+ console.log(` status harness status · stop harness stop · logs ${tildify(LOG_FILE)}`)
+ process.exit(0) // daemon stays alive
+ }
+
+ registry.load()
+ printInfoBlock({
+ status: '● connected',
+ pid: child.pid ?? 0,
+ token,
+ sessions: registry.list().length,
+ version: await runningDaemonVersion(),
+ })
+ process.exit(0)
+}
+
+async function stopDaemonProcess(): Promise<{ pid: number | null; stopped: boolean }> {
+ const pid = readPid()
+ if (!pid || !isAlive(pid)) {
+ rmSync(PID_FILE, { force: true })
+ return { pid: null, stopped: false }
+ }
+ try { process.kill(pid, 'SIGTERM') } catch { /* already gone */ }
+ const deadline = Date.now() + 3000
+ while (Date.now() < deadline && isAlive(pid)) await new Promise((r) => setTimeout(r, 150))
+ if (isAlive(pid)) { try { process.kill(pid, 'SIGKILL') } catch { /* ignore */ } }
+ rmSync(PID_FILE, { force: true })
+ return { pid, stopped: true }
+}
+
+/** `harness stop` — SIGTERM the background adapter, SIGKILL if it lingers. */
+async function stop(): Promise<void> {
+ const r = await stopDaemonProcess()
+ if (!r.pid) {
+ console.log('machine is not running.')
+ process.exit(0)
+ }
+ console.log(`machine stopped (pid ${r.pid}).`)
+ process.exit(0)
+}
+
+function clearAdapterState(): void {
+ const dataDir = resolve(env.ADAPTER_DATA_DIR)
+ const cliDir = resolve(env.ADAPTER_CLI_DIR)
+ const rmStateFiles = (dir: string): void => {
+ for (const name of [
+ 'token',
+ 'adapter.pid',
+ 'machine.log',
+ 'adapter.log', // pre-rename name — still cleared so a reset leaves nothing behind
+ 'computer-id',
+ 'machine-name',
+ 'registry.json',
+ 'registry-boot',
+ 'agent-names.json',
+ 'summaries.json',
+ 'summary-scratch',
+ 'e2e',
+ ]) {
+ rmSync(join(dir, name), { recursive: true, force: true })
+ }
+ }
+ if (dataDir === cliDir) rmStateFiles(dataDir)
+ else rmSync(dataDir, { recursive: true, force: true })
+ rmStateFiles(cliDir)
+}
+
+/** `adapter reset` — stop the daemon and clear local state so the next join starts fresh. */
+async function resetCommand(): Promise<void> {
+ const r = await stopDaemonProcess()
+ clearAdapterState()
+ console.log(`\n ✓ Cleared local machine CLI state at ${tildify(env.ADAPTER_DATA_DIR)}.`)
+ if (r.pid) console.log(` Stopped adapter process ${r.pid}.`)
+ if (env.ADAPTER_TOKEN) console.log(' Note: ADAPTER_TOKEN is still set in the environment and will override disk state.')
+ console.log('\n Start again with: harness join <token>\n')
+ process.exit(0)
+}
+
+/** Call the running daemon's localhost control API. Exits with a friendly message if it's not up. */
+async function daemonCall(method: 'GET' | 'POST', path: string, body?: unknown): Promise<{ res: Response; json: Record<string, unknown> }> {
+ const url = `http://127.0.0.1:${daemonPort()}${path}`
+ let res: Response
+ try {
+ const headers: Record<string, string> = { 'x-adapter-local': '1' } // passes the dashboard CSRF gate
+ if (body) headers['content-type'] = 'application/json'
+ res = await fetch(url, { method, headers, body: body ? JSON.stringify(body) : undefined })
+ } catch {
+ console.error('\n ✗ The adapter is not running on this computer.')
+ console.error(' Start it first: harness join\n')
+ process.exit(1)
+ }
+ const json = (await res.json().catch(() => ({}))) as Record<string, unknown>
+ return { res, json }
+}
+
+/** `harness pair <code>` — send a browser/device pairing code to the running daemon (localhost). */
+async function pairCommand(code: string | undefined): Promise<void> {
+ if (!code) { console.error('Usage: harness pair <code> (the code is shown on the browser or device)'); process.exit(1) }
+ const { res, json } = await daemonCall('POST', '/api/pair', { code })
+ const body = json as { label?: string; fingerprint?: string; error?: string }
+ if (res.ok) {
+ console.log(`\n ✓ Paired “${body.label ?? 'browser'}”`)
+ console.log(` fingerprint ${body.fingerprint ?? '?'} — verify it matches the browser\n`)
+ process.exit(0)
+ }
+ const messages: Record<string, string> = {
+ NO_INTENT: 'No browser or device is waiting to pair.',
+ EXPIRED: 'That code expired. Use the fresh code shown on the browser or device.',
+ CODE_MISMATCH: 'That code didn’t match. Use the fresh code shown on the browser or device.',
+ BACKEND_DOWN: 'The adapter can’t reach the backend right now. Try again shortly.',
+ RATE_LIMITED: 'Too many attempts. Wait a minute and try again.',
+ BUSY: 'A pairing is already in progress.',
+ TIMEOUT: 'The browser or device didn’t respond in time. Try again.',
+ CANCELLED: 'Pairing was cancelled on the browser or device.',
+ PAIRING_UNAVAILABLE: 'This adapter build does not support E2EE pairing.',
+ }
+ console.error(`\n ✗ ${messages[body.error ?? ''] ?? `Pairing failed (${body.error ?? res.status}).`}\n`)
+ process.exit(1)
+}
+
+/** `adapter browser-link` — print a one-time browser setup link for the current machine. */
+async function browserLinkCommand(): Promise<void> {
+ const token = readSavedToken()
+ if (!token) { console.error('\n ✗ This computer is not joined. Run: harness join <token>\n'); process.exit(1) }
+ const agentId = agentIdFromToken(token)
+ let url = ''
+ try {
+ const res = await fetch(`http://127.0.0.1:${daemonPort()}/api/e2ee/setup-link`, {
+ method: 'POST',
+ headers: { 'x-adapter-local': '1' },
+ })
+ if (res.ok) {
+ const body = (await res.json().catch(() => null)) as { url?: unknown; expiresAt?: unknown; fingerprint?: unknown } | null
+ if (typeof body?.url === 'string') url = body.url
+ }
+ } catch { /* fall back to disk-backed token below */ }
+ if (!url) {
+ const setup = createSetupToken(agentId)
+ url = setupBrowserLink(agentId, setup.token)
+ }
+ console.log('\n Browser setup link (valid for 7 days):\n')
+ console.log(` ${url}\n`)
+ if (!readPid()) console.log(' Start the adapter with `harness join` if the browser cannot connect.\n')
+ process.exit(0)
+}
+
+/** `harness pairings` — list the browsers paired for end-to-end encryption. */
+async function pairingsCommand(): Promise<void> {
+ const { res, json } = await daemonCall('GET', '/api/pairs')
+ if (!res.ok) { console.error(`\n ✗ Could not list pairings (${json.error ?? res.status}).\n`); process.exit(1) }
+ const pairs = (json.pairs ?? []) as Array<{ fingerprint: string; label: string; pairedAt: number; online: boolean }>
+ if (!pairs.length) { console.log('\n No browsers paired yet.\n Open the agent page in a browser to get a pairing code.\n'); process.exit(0) }
+ console.log('\n Paired clients (end-to-end encrypted):\n')
+ pairs.forEach((p, i) => {
+ const when = new Date(p.pairedAt).toISOString().slice(0, 16).replace('T', ' ')
+ console.log(` ${String(i + 1).padStart(2)}. ${p.fingerprint} ${p.online ? '● online ' : '○ offline'} ${p.label} (paired ${when})`)
+ })
+ console.log('\n Unpair one: harness unpair <#|fingerprint> · Unpair all: harness unpair --all\n')
+ process.exit(0)
+}
+
+/** `harness unpair <#|fingerprint>` / `harness unpair --all` — revoke browser pairing(s). */
+async function unpairCommand(id: string | undefined, all: boolean): Promise<void> {
+ if (all) {
+ const { res, json } = await daemonCall('POST', '/api/revoke-all')
+ if (!res.ok) { console.error(`\n ✗ Unpair-all failed (${json.error ?? res.status}).\n`); process.exit(1) }
+ const count = Number(json.count ?? 0)
+ console.log(`\n ✓ Unpaired ${count} browser${count === 1 ? '' : 's'}. Any open ones drop to the pairing screen.\n`)
+ process.exit(0)
+ }
+ if (!id) { console.error('Usage: harness unpair <#|fingerprint> | harness unpair --all (see: harness pairings)'); process.exit(1) }
+ const { res, json } = await daemonCall('POST', '/api/revoke', { id })
+ if (res.ok) {
+ console.log(`\n ✓ Unpaired “${json.label ?? 'browser'}” ${json.fingerprint ?? ''}`)
+ console.log(' If that browser is open, it drops to the pairing screen; otherwise it will on next open.\n')
+ process.exit(0)
+ }
+ const msg = json.error === 'AMBIGUOUS'
+ ? 'That fingerprint prefix matches more than one browser — use more characters or the list number.'
+ : json.error === 'NOT_FOUND' ? 'No paired client matches that id. Run: harness pairings'
+ : `Unpair failed (${json.error ?? res.status}).`
+ console.error(`\n ✗ ${msg}\n`)
+ process.exit(1)
+}
+
+/** `harness status` — print the info block with the current running state. */
+async function status(): Promise<void> {
+ const pid = readPid()
+ const alive = pid != null && isAlive(pid)
+ let token = env.ADAPTER_TOKEN ?? ''
+ if (!token) { try { token = readFileSync(TOKEN_FILE, 'utf-8').trim() } catch { /* none */ } }
+ if (!token) { console.log('machine: not joined. Run: harness join <token>'); process.exit(0) }
+ registry.load()
+ printInfoBlock({
+ status: alive ? '● running' : '○ stopped',
+ pid: pid ?? 0,
+ token,
+ sessions: registry.list().length,
+ // A stopped daemon answers nothing, so this falls back to the local build — which is what will run.
+ version: alive ? await runningDaemonVersion() : VERSION,
+ })
+ process.exit(0)
+}
+
+// ── arg parse ──────────────────────────────────────────────────────────────────────────────────
+const [, , cmd, ...rest] = process.argv
+const flags = rest.filter((a) => a.startsWith('-'))
+const args = rest.filter((a) => !a.startsWith('-'))
+const foreground = flags.includes('--foreground') || flags.includes('-f')
+
+if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') usage()
+if (cmd === 'version' || cmd === '--version' || cmd === '-v') { console.log(VERSION); process.exit(0) }
+
+const onError = (err: unknown): never => {
+ console.error('Failed to start adapter:', err)
+ process.exit(1)
+}
+
+switch (cmd) {
+ case 'join':
+ joinCommand(foreground, args[0]).catch(onError)
+ break
+ case 'unjoin':
+ unjoin().catch(onError)
+ break
+ // `start` is superseded by `join` (saved reconnect / `join <token>`). Kept as a deprecated
+ // alias so muscle memory / old scripts don't break — including the old `start <token>` form.
+ case 'start':
+ console.error('(note: "harness start" is now "harness join")')
+ joinCommand(foreground, args[0]).catch(onError)
+ break
+ case '__run': { // internal: the detached daemon child runs the adapter inline (token via env)
+ const t = readSavedToken()
+ if (!t) onError(new Error('no credential for __run'))
+ else runForeground(t).catch(onError)
+ break
+ }
+ case 'pair':
+ pairCommand(args[0]).catch(onError)
+ break
+ case 'browser-link':
+ browserLinkCommand().catch(onError)
+ break
+ case 'e2ee-link':
+ console.error('(note: "harness e2ee-link" is deprecated — use "harness browser-link")')
+ browserLinkCommand().catch(onError)
+ break
+ case 'pairings':
+ pairingsCommand().catch(onError)
+ break
+ case 'unpair':
+ unpairCommand(args[0], flags.includes('--all') || flags.includes('-a')).catch(onError)
+ break
+ // Hidden deprecated aliases (superseded by pairings / unpair) — kept so early scripts don't break.
+ case 'pairs':
+ case 'list-pairs':
+ console.error(`(note: "${cmd}" is deprecated — use "harness pairings")`)
+ pairingsCommand().catch(onError)
+ break
+ case 'revoke':
+ console.error('(note: "revoke" is deprecated — use "harness unpair <#|fingerprint>")')
+ unpairCommand(args[0], false).catch(onError)
+ break
+ case 'revoke-all':
+ console.error('(note: "revoke-all" is deprecated — use "harness unpair --all")')
+ unpairCommand(undefined, true).catch(onError)
+ break
+ case 'stop':
+ stop().catch(onError)
+ break
+ case 'reset':
+ resetCommand().catch(onError)
+ break
+ case 'status':
+ status().catch(onError)
+ break
+ case 'update':
+ updateCommand().catch(onError)
+ break
+ default:
+ // `harness <engine> [args…]` — wrap an agent CLI in this tmux pane. Everything after the engine
+ // name is forwarded VERBATIM, so we read raw argv here instead of the `flags`/`args` split above:
+ // that split strips every `-`-prefixed token anywhere in argv and would eat the engine's own
+ // `--resume` / `--model`.
+ // Accept the engine's own id OR any name its CLI actually installs (`harness cmd` = Command Code).
+ const engine = resolveEngine(cmd)
+ if (engine) {
+ launchEngine(engine, process.argv.slice(3)).catch(onError)
+ break
+ }
+ console.error(`Unknown command: ${cmd}`)
+ usage()
+}
diff --git a/cli/src/config/env.ts b/cli/src/config/env.ts
new file mode 100644
index 000000000..f08284d05
--- /dev/null
+++ b/cli/src/config/env.ts
@@ -0,0 +1,210 @@
+import 'dotenv/config'
+import { existsSync, mkdirSync, readdirSync, renameSync, rmSync } from 'fs'
+import { homedir } from 'os'
+import { join } from 'path'
+import { z } from 'zod'
+
+// 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.
+const adapterCliDir = join(homedir(), '.harness', 'cli')
+const adapterDataDir = join(adapterCliDir, 'data')
+
+// ── One-time adoption of adapter state written under an older name ────────────────────────────────
+//
+// Two accidents from the machine rename, with different resolutions:
+//
+// 1. A released build resolved the root as `~/.machine/cli` instead of `~/.harness/cli`. Anyone who
+// ran it has been LIVING there since — that tree holds their current token, tmux registry and
+// E2EE pairings, while `~/.harness` is frozen at whatever it was when they upgraded. So the data
+// dir is FORCE-MOVED across: `~/.machine` wins outright. Anything else would silently roll those
+// users back to a stale token and an empty session registry.
+// 2. Files INSIDE the data dir were renamed (machine-id → computer-id, harness-name → machine-name,
+// harness.log → machine.log). Within one tree there is nothing to arbitrate, so those only fire
+// when the new name is still free — and they run first, so the force-move above still wins.
+//
+// `renameSync` preserves the inode, so a daemon still holding an fd on the old path keeps writing
+// into the same file under its new name.
+
+/** Move `legacy` → `current` only when `current` is free (in-tree rename). */
+function adoptPath(current: string, legacy: string): boolean {
+ try {
+ if (existsSync(current) || !existsSync(legacy)) return false
+ renameSync(legacy, current)
+ return true
+ } catch {
+ return false // best-effort: a failed adoption must never stop the CLI from starting
+ }
+}
+
+/** Move `legacy` → `current`, replacing whatever is there. Used only for the ~/.machine data dir. */
+function forceMove(current: string, legacy: string): boolean {
+ try {
+ rmSync(current, { recursive: true, force: true })
+ renameSync(legacy, current)
+ return true
+ } catch {
+ return false
+ }
+}
+
+function migrateLegacyAdapterState(): void {
+ // Only for the default location. An explicit ADAPTER_DATA_DIR (tests, custom installs) is the
+ // caller's business and must not be reshaped underneath them.
+ if (process.env.ADAPTER_DATA_DIR) return
+
+ let moved = 0
+
+ // In-tree renames first, so a machine that never saw the ~/.machine build still lands on the new
+ // names. The force-move below overrides these where both exist.
+ for (const [current, legacy] of [
+ ['computer-id', 'machine-id'],
+ ['machine-name', 'harness-name'],
+ ['machine.log', 'harness.log'],
+ ]) {
+ if (adoptPath(join(adapterDataDir, current), join(adapterDataDir, legacy))) moved++
+ }
+
+ const strayDataDir = join(homedir(), '.machine', 'cli', 'data')
+ if (existsSync(strayDataDir)) {
+ mkdirSync(adapterDataDir, { recursive: true })
+ for (const entry of readdirSync(strayDataDir)) {
+ if (forceMove(join(adapterDataDir, entry), join(strayDataDir, entry))) moved++
+ }
+ // Whole stray tree goes: its cli.js/notify.mjs are only a bundle copy the launcher never runs
+ // (it execs ~/.harness/cli/cli.js) and the next self-update rewrites them.
+ try {
+ rmSync(join(homedir(), '.machine'), { recursive: true, force: true })
+ } catch { /* ignore */ }
+ console.warn(`[machine] moved adapter state from ~/.machine/cli/data into ${adapterDataDir}`)
+ } else if (moved) {
+ console.warn(`[machine] renamed ${moved} pre-rename file(s) in ${adapterDataDir}`)
+ }
+}
+
+migrateLegacyAdapterState()
+
+const envSchema = z.object({
+ NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
+ // Localhost port the SessionStart/SessionEnd hook callbacks POST to (hook/notify.mjs). A quiet FIXED
+ // value (below the OS ephemeral range, outside the project's 80xx/8100-8999/9001-9999 ranges). No
+ // free-port fallback — if it's taken, the adapter reports it (another adapter is likely running).
+ PORT: z.string().default('18473').transform(Number),
+ // The backend the CLI dials (`/api/adapter-ws`). Local dev: ws://localhost:8090.
+ BACKEND_WS_URL: z.string().default('wss://harness-api.autonomous.ai'),
+ // Web app base URL — used to print the agent's chat link on `adapter start`. Local: http://localhost:3000.
+ WEB_URL: z.string().default('https://harness.autonomous.ai'),
+ // Connect token (the agent apiKey). Usually passed as `adapter start <token>` and persisted to
+ // ${ADAPTER_DATA_DIR}/token; this env var overrides both.
+ ADAPTER_TOKEN: z.string().optional(),
+ // Where Claude Code writes its per-session JSONL transcripts.
+ CLAUDE_PROJECTS_DIR: z.string().default(join(homedir(), '.claude', 'projects')),
+ // Codex state root. Only hook-registered rollout files beneath <CODEX_HOME>/sessions are exposed.
+ CODEX_HOME: z.string().default(join(homedir(), '.codex')),
+ // Cursor state root. Interactive transcripts live below <CURSOR_HOME>/projects and local
+ // subagent linkage metadata lives below <CURSOR_HOME>/chats.
+ CURSOR_HOME: z.string().default(join(homedir(), '.cursor')),
+ // OpenCode state root — the SQLite store lives at <OPENCODE_DATA_DIR>/opencode.db (honors
+ // XDG_DATA_HOME). Sessions are polled from that DB (no per-session transcript file).
+ OPENCODE_DATA_DIR: z
+ .string()
+ .default(join(process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share'), 'opencode')),
+ // OpenCode plugin dir the adapter drops its discovery plugin into (honors XDG_CONFIG_HOME).
+ OPENCODE_PLUGIN_DIR: z
+ .string()
+ .default(join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'opencode', 'plugin')),
+ // Pi state root. Session transcripts live under <PI_HOME>/agent/sessions/--<mangled-cwd>--/*.jsonl and
+ // the adapter's discovery extension is installed into <PI_HOME>/agent/extensions.
+ PI_HOME: z.string().default(join(homedir(), '.pi')),
+ // Hermes state root — the SQLite store is <HERMES_HOME>/state.db and the shell hooks the adapter
+ // installs live in <HERMES_HOME>/config.yaml (+ shell-hooks-allowlist.json).
+ HERMES_HOME: z.string().default(join(homedir(), '.hermes')),
+ // Command Code state root — transcripts live under <COMMANDCODE_HOME>/projects/<cwd-slug>/<id>.jsonl
+ // and the adapter installs its shell hooks into <COMMANDCODE_HOME>/settings.json.
+ COMMANDCODE_HOME: z.string().default(join(homedir(), '.commandcode')),
+ // Devin CLI state root — history is the SQLite store <DEVIN_HOME>/sessions.db (WAL, no transcript file
+ // unless the user passes --export) and <DEVIN_HOME>/session_locks/<id>.lock holds the owning PID.
+ DEVIN_HOME: z.string().default(join(homedir(), '.local', 'share', 'devin', 'cli')),
+ // Devin's user-level config, where the adapter merges its hooks under a "hooks" key. Devin reads
+ // Claude's hook schema verbatim, so the installed block is shaped exactly like ~/.claude/settings.json.
+ DEVIN_CONFIG_PATH: z.string().default(join(homedir(), '.config', 'devin', 'config.json')),
+ // Where the tmux-session registry + connect token are persisted.
+ ADAPTER_DATA_DIR: z.string().default(adapterDataDir),
+ // Set to 'true' to skip auto-installing the SessionStart/SessionEnd hooks into
+ // ~/.claude/settings.json on startup.
+ DISABLE_HOOK_INSTALL: z.string().default('false').transform((v) => v === 'true'),
+ // 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).
+ CLAUDE_PATH: z.string().optional(),
+ // Path to the Cursor Agent CLI for Cursor recap one-shots (else `agent` is resolved from PATH).
+ CURSOR_PATH: z.string().optional(),
+ // Path to the `opencode` CLI for OpenCode recap one-shots (else `opencode` is resolved from PATH).
+ OPENCODE_PATH: z.string().optional(),
+ // Path to the `pi` CLI for Pi recap one-shots (else `pi` is resolved from PATH).
+ PI_PATH: z.string().optional(),
+ // Path to the `hermes` CLI for Hermes recap one-shots (else `hermes` is resolved from PATH).
+ HERMES_PATH: z.string().optional(),
+ // Path to the `commandcode` CLI for Command Code recap one-shots (else resolved from PATH).
+ COMMANDCODE_PATH: z.string().optional(),
+ // Path to the `devin` CLI for Devin recap one-shots (else `devin` is resolved from PATH).
+ DEVIN_PATH: z.string().optional(),
+ // Model for the device turn-recap one-shot.
+ SUMMARY_MODEL: z.string().default('sonnet'),
+ // Balanced Codex counterpart used only for recap workers; never inherits the interactive CLI model.
+ CODEX_SUMMARY_MODEL: z.string().default('gpt-5.5'),
+ // Cursor's Auto model keeps recap availability aligned with the user's Cursor account.
+ CURSOR_SUMMARY_MODEL: z.string().default('auto'),
+ // OpenCode recap model (`provider/model`). Empty → use the user's opencode config default model.
+ OPENCODE_SUMMARY_MODEL: z.string().default(''),
+ // Pi recap model (`provider/model` or a model pattern). Empty → use the user's pi config default.
+ PI_SUMMARY_MODEL: z.string().default(''),
+ // Hermes recap model. Empty → use the user's ~/.hermes/config.yaml default (keeps their provider).
+ HERMES_SUMMARY_MODEL: z.string().default(''),
+ // Command Code recap model. Empty → use the user's own account default.
+ COMMANDCODE_SUMMARY_MODEL: z.string().default(''),
+ // Devin recap model. Empty → use the user's own account default (their plan decides what is available).
+ DEVIN_SUMMARY_MODEL: z.string().default(''),
+ // Shared recap reasoning level for Claude and Codex. Cursor effort is part of its model identifier.
+ SUMMARY_EFFORT: z.enum(['low', 'medium', 'high']).default('low'),
+ // Model for the voice router one-shot classifier (Overview voice → pick the agent). Small/fast by default.
+ VOICE_ROUTE_MODEL: z.string().default('haiku'),
+ // Test override: run the recap even with no device connected (mirrors node isRecapForced()).
+ RECAP_FORCE: z.string().default('false').transform((v) => v === 'true'),
+
+ // ── self-update (the daemon polls a GCS manifest and swaps its own bundle) ──────────────────────
+ // Manifest URL (same GCS bucket + metadata.json shape as the device OTA; key = ADAPTER_UPDATE_KEY).
+ ADAPTER_UPDATE_URL: z
+ .string()
+ .default('https://storage.googleapis.com/s3-autonomous-upgrade-3/harness/cli/metadata.json'),
+ ADAPTER_UPDATE_KEY: z.string().default('cli'),
+ // How often the daemon checks for a newer build (ms). The poll is a tiny no-cache metadata fetch;
+ // the artifact is downloaded only when the manifest version is strictly newer.
+ ADAPTER_UPDATE_CHECK_MS: z.string().default('60000').transform(Number),
+ // Set 'true' to disable self-update entirely.
+ ADAPTER_UPDATE_DISABLE: z.string().default('false').transform((v) => v === 'true'),
+ // Install dir holding the packaged cli.js + notify.mjs that the self-updater swaps in place.
+ ADAPTER_CLI_DIR: z.string().default(adapterCliDir),
+})
+
+export type Env = z.infer<typeof envSchema>
+
+function validateEnv(): Env {
+ const parsed = envSchema.safeParse(process.env)
+
+ if (!parsed.success) {
+ console.error('Invalid environment variables:', parsed.error.flatten().fieldErrors)
+ process.exit(1)
+ }
+
+ const data = parsed.data
+ // Pair WEB_URL to the backend's environment. The `join` link is served by the WEB app that talks to
+ // the SAME backend the adapter dials — so a code created on a LOCAL backend must be confirmed on the
+ // LOCAL web. If WEB_URL wasn't set explicitly and BACKEND_WS_URL is loopback, default WEB_URL to the
+ // local web (:3000) instead of prod — otherwise the printed link points at prod, which can't see it.
+ if (!process.env.WEB_URL && /^wss?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/.test(data.BACKEND_WS_URL)) {
+ data.WEB_URL = 'http://localhost:3000'
+ }
+ return data
+}
+
+export const env = validateEnv()
diff --git a/cli/src/engines/codex/normalizer.spec.ts b/cli/src/engines/codex/normalizer.spec.ts
new file mode 100644
index 000000000..6fbf1ac83
--- /dev/null
+++ b/cli/src/engines/codex/normalizer.spec.ts
@@ -0,0 +1,451 @@
+import { describe, expect, it, vi } from 'vitest'
+import { CodexNormalizer, codexMessagesToEvents, codexTaskError, lastCodexTurnText, windowCodexLines } from './normalizer.js'
+import type { CodexSubagentResolver } from './subagent.js'
+
+const line = (type: string, payload: Record<string, unknown>) => JSON.stringify({ type, payload })
+
+describe('Codex rollout normalizer', () => {
+ const fixture = [
+ line('session_meta', { id: 'codex-1', cli_version: '0.144.4', cwd: '/tmp/work' }),
+ line('event_msg', { type: 'task_started', turn_id: 'turn-1' }),
+ line('event_msg', { type: 'user_message', message: 'Change the API' }),
+ line('response_item', { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'duplicate' }] }),
+ line('response_item', { type: 'function_call', call_id: 'call-1', name: 'exec_command', arguments: '{"cmd":"npm test"}' }),
+ line('response_item', { type: 'function_call_output', call_id: 'call-1', output: 'tests passed' }),
+ line('event_msg', { type: 'agent_message', message: 'The API is updated.' }),
+ line('event_msg', { type: 'task_complete', turn_id: 'turn-1' }),
+ ]
+
+ it('emits one live lifecycle and never duplicates response_item assistant text', () => {
+ const normalizer = new CodexNormalizer('live')
+ const events = fixture.flatMap((raw) => normalizer.ingest(raw))
+ expect(events.map((event) => event.type)).toEqual([
+ 'turn_started', 'tool_start', 'tool_end', 'text_delta', 'turn_ended',
+ ])
+ expect(events.find((event) => event.type === 'text_delta')?.payload).toEqual({ content: 'The API is updated.' })
+ expect(events.find((event) => event.type === 'tool_start')?.payload).toEqual({
+ id: 'call-1',
+ tool: 'Bash',
+ input: { command: 'npm test' },
+ })
+ expect(normalizer.turnOpen).toBe(false)
+ })
+
+ it('replays user/tool/assistant events and appends done', () => {
+ const events = codexMessagesToEvents(fixture)
+ expect(events[0]).toEqual({ type: 'user_message', payload: { content: 'Change the API' } })
+ expect(events.at(-1)).toEqual({ type: 'done', payload: { result: 'success' } })
+ })
+
+ it('deduplicates the compacted + token_count + context_compacted sequence', () => {
+ const records = [
+ line('compacted', { message: 'hidden' }),
+ line('event_msg', { type: 'token_count', info: { total_token_usage: {} } }),
+ line('event_msg', { type: 'context_compacted' }),
+ ]
+ const normalizer = new CodexNormalizer('live')
+ const events = records.flatMap((raw) => normalizer.ingest(raw))
+ expect(events.map((event) => event.type)).toEqual(['context_compact'])
+ expect(codexMessagesToEvents(records).filter((event) => event.type === 'context_compact')).toHaveLength(1)
+ })
+
+ it('does not crash when a tool search result has no output field', () => {
+ const normalizer = new CodexNormalizer('live')
+ const events = [
+ line('response_item', { type: 'tool_search_call', call_id: 'search-1' }),
+ line('response_item', { type: 'tool_search_output', call_id: 'search-1', tools: [] }),
+ ].flatMap((raw) => normalizer.ingest(raw))
+
+ expect(events).toEqual([
+ { type: 'tool_start', payload: { id: 'search-1', tool: 'tool_search', input: {} } },
+ { type: 'tool_end', payload: { id: 'search-1', tool: 'tool_search', output: '', isError: false, summary: 'tool_search completed' } },
+ ])
+ })
+
+ it('unwraps custom exec web calls into WebSearch cards', () => {
+ const normalizer = new CodexNormalizer('live')
+ const events = [
+ line('response_item', {
+ type: 'custom_tool_call',
+ call_id: 'web-1',
+ name: 'exec',
+ input: 'const r = await tools.web__run({search_query:[{q:"BTC current price"}]}); text(r)',
+ }),
+ line('response_item', {
+ type: 'custom_tool_call_output',
+ call_id: 'web-1',
+ output: [{ type: 'input_text', text: 'Search results' }],
+ }),
+ ].flatMap((raw) => normalizer.ingest(raw))
+
+ expect(events).toEqual([
+ { type: 'tool_start', payload: { id: 'web-1', tool: 'WebSearch', input: { query: 'BTC current price' } } },
+ { type: 'tool_end', payload: { id: 'web-1', tool: 'WebSearch', output: 'Search results', isError: false, summary: 'Search results' } },
+ ])
+ })
+
+ it('normalizes update_plan and hides internal deferred-tool discovery', () => {
+ const normalizer = new CodexNormalizer('live')
+ const events = [
+ line('response_item', {
+ type: 'custom_tool_call',
+ call_id: 'discover-1',
+ name: 'exec',
+ input: 'text(ALL_TOOLS.map(x => x.name).filter(n => /todo/i.test(n)).join("\\n"))',
+ }),
+ line('response_item', { type: 'custom_tool_call_output', call_id: 'discover-1', output: 'update_plan' }),
+ line('response_item', {
+ type: 'custom_tool_call',
+ call_id: 'plan-1',
+ name: 'exec',
+ input: 'const r = await tools.update_plan({plan:[{step:"Research BTC",status:"completed"},{step:"Write report",status:"in_progress"}]}); text(r)',
+ }),
+ line('response_item', { type: 'custom_tool_call_output', call_id: 'plan-1', output: 'Plan updated' }),
+ ].flatMap((raw) => normalizer.ingest(raw))
+
+ expect(events).toEqual([
+ {
+ type: 'tool_start',
+ payload: {
+ id: 'plan-1',
+ tool: 'TodoWrite',
+ input: {
+ todos: [
+ { content: 'Research BTC', status: 'completed' },
+ { content: 'Write report', status: 'in_progress' },
+ ],
+ },
+ },
+ },
+ { type: 'tool_end', payload: { id: 'plan-1', tool: 'TodoWrite', output: 'Plan updated', isError: false, summary: 'Plan updated' } },
+ ])
+ })
+
+ it('extracts the final user/assistant turn and uses stable line cursors', () => {
+ expect(lastCodexTurnText(fixture)).toEqual({ userMessage: 'Change the API', assistantText: 'The API is updated.' })
+ const window = windowCodexLines([...fixture, ...fixture], { limit: 4 })
+ expect(window.oldestCursor).toMatch(/^codex:\d+$/)
+ expect(window.hasMore).toBe(true)
+ })
+
+ it('maps Codex orchestration to a Task tree and deduplicates completion notifications', () => {
+ const resolver: CodexSubagentResolver = () => ({
+ events: [
+ { type: 'tool_start', payload: { id: 'child-call', tool: 'Bash', input: { command: 'rg TODO' } } },
+ { type: 'tool_end', payload: { id: 'child-call', tool: 'Bash', output: 'done', isError: false, summary: 'done' } },
+ ],
+ agentType: 'explorer',
+ totalToolUseCount: 1,
+ totalTokens: 321,
+ totalDurationMs: 1_500,
+ })
+ const resolveSubagent = vi.fn(resolver)
+ const childId = '019f35c1-8017-7391-beb4-06a01ceda2bd'
+ const orchestration = [
+ line('event_msg', { type: 'user_message', message: 'Inspect the code' }),
+ line('response_item', {
+ type: 'function_call',
+ call_id: 'spawn-1',
+ name: 'spawn_agent',
+ arguments: JSON.stringify({ agent_type: 'explorer', message: 'description="API audit". Inspect the API.' }),
+ }),
+ line('response_item', {
+ type: 'function_call_output',
+ call_id: 'spawn-1',
+ output: JSON.stringify({ agent_id: childId, nickname: 'Curie' }),
+ }),
+ line('response_item', {
+ type: 'function_call',
+ call_id: 'wait-1',
+ name: 'wait_agent',
+ arguments: JSON.stringify({ targets: [childId] }),
+ }),
+ line('response_item', {
+ type: 'function_call_output',
+ call_id: 'wait-1',
+ output: JSON.stringify({ status: { [childId]: { completed: 'API audit complete' } } }),
+ }),
+ line('response_item', {
+ type: 'message',
+ role: 'user',
+ content: [{
+ type: 'input_text',
+ text: `<subagent_notification>\n${JSON.stringify({ agent_path: childId, status: { completed: 'API audit complete' } })}\n</subagent_notification>`,
+ }],
+ }),
+ line('event_msg', { type: 'task_complete' }),
+ ]
+
+ const normalizer = new CodexNormalizer('live', resolveSubagent)
+ const events = orchestration.flatMap((raw) => normalizer.ingest(raw))
+
+ expect(events.map((event) => event.type)).toEqual([
+ 'turn_started',
+ 'tool_start',
+ 'tool_start',
+ 'tool_end',
+ 'tool_end',
+ 'turn_ended',
+ ])
+ expect(events[1]).toEqual({
+ type: 'tool_start',
+ payload: {
+ id: 'spawn-1',
+ tool: 'Task',
+ input: {
+ subagent_type: 'explorer',
+ name: 'Curie',
+ title: 'API audit',
+ description: 'Inspect the API.',
+ },
+ },
+ })
+ expect(events[2]).toEqual({
+ type: 'tool_start',
+ payload: {
+ id: 'child-call',
+ tool: 'Bash',
+ input: { command: 'rg TODO' },
+ parentToolUseId: 'spawn-1',
+ },
+ })
+ expect(events[3].payload).toMatchObject({ parentToolUseId: 'spawn-1' })
+ expect(events[4].payload).toMatchObject({
+ id: 'spawn-1',
+ tool: 'Task',
+ isError: false,
+ subagent: {
+ agentId: childId,
+ agentType: 'explorer',
+ totalToolUseCount: 1,
+ totalTokens: 321,
+ totalDurationMs: 1_500,
+ },
+ })
+ expect(resolveSubagent).toHaveBeenCalledOnce()
+ expect(resolveSubagent).toHaveBeenCalledWith(childId)
+ expect(events.some((event) => event.type === 'tool_start' && ['spawn_agent', 'wait_agent'].includes(event.payload.tool))).toBe(false)
+ })
+
+ it('closes a Task with an error when Codex rejects the spawn', () => {
+ const normalizer = new CodexNormalizer('live', () => null)
+ const events = [
+ line('response_item', {
+ type: 'function_call',
+ call_id: 'spawn-failed',
+ name: 'spawn_agent',
+ arguments: JSON.stringify({ agent_type: 'worker', message: 'Do the work' }),
+ }),
+ line('response_item', {
+ type: 'function_call_output',
+ call_id: 'spawn-failed',
+ output: 'Provide either message or items, but not both',
+ }),
+ ].flatMap((raw) => normalizer.ingest(raw))
+
+ expect(events.map((event) => event.type)).toEqual(['tool_start', 'tool_end'])
+ expect(events[1].payload).toMatchObject({ id: 'spawn-failed', tool: 'Task', isError: true })
+ })
+
+ it('uses the same Task tree contract for transcript replay', () => {
+ const childId = '019f35c1-8017-7391-beb4-06a01ceda2bd'
+ const resolveSubagent: CodexSubagentResolver = () => ({
+ events: [],
+ agentType: 'worker',
+ totalToolUseCount: 0,
+ totalTokens: 10,
+ totalDurationMs: 25,
+ })
+ const events = codexMessagesToEvents([
+ line('response_item', { type: 'function_call', call_id: 'spawn-replay', name: 'spawn_agent', arguments: '{"agent_type":"worker","message":"Build it"}' }),
+ line('response_item', { type: 'function_call_output', call_id: 'spawn-replay', output: JSON.stringify({ agent_id: childId }) }),
+ line('response_item', { type: 'message', role: 'user', content: [{ type: 'input_text', text: `<subagent_notification>\n${JSON.stringify({ agent_path: childId, status: { completed: 'Built' } })}\n</subagent_notification>` }] }),
+ ], resolveSubagent)
+
+ expect(events.map((event) => event.type)).toEqual(['tool_start', 'tool_end', 'done'])
+ expect(events[0].payload).toMatchObject({ tool: 'Task' })
+ expect(events[1].payload).toMatchObject({ tool: 'Task', subagent: { agentId: childId } })
+ })
+
+ it('keeps parallel Task ordering identical between live watch and F5 replay', () => {
+ const prompt = 'Run three echo agents in parallel'
+ const childIds = [
+ '019f8dae-e306-7b13-8b19-04e381787092',
+ '019f8dae-e592-7823-9ebf-64940ee02c5d',
+ '019f8dae-e5f4-7c11-90d1-600854063b2c',
+ ]
+ const fixture = [
+ line('event_msg', { type: 'user_message', message: prompt }),
+ line('event_msg', { type: 'agent_message', message: 'Launching three agents.' }),
+ ...childIds.flatMap((childId, index) => [
+ line('response_item', {
+ type: 'function_call',
+ call_id: `spawn-${index + 1}`,
+ name: 'spawn_agent',
+ arguments: JSON.stringify({
+ agent_type: 'worker',
+ message: `description="echo ${index + 1}". Run echo ${index + 1}.`,
+ }),
+ }),
+ line('response_item', {
+ type: 'function_call_output',
+ call_id: `spawn-${index + 1}`,
+ output: JSON.stringify({ agent_id: childId }),
+ }),
+ ]),
+ line('response_item', {
+ type: 'function_call',
+ call_id: 'wait-all',
+ name: 'wait_agent',
+ arguments: JSON.stringify({ targets: childIds }),
+ }),
+ line('response_item', {
+ type: 'function_call_output',
+ call_id: 'wait-all',
+ output: JSON.stringify({
+ status: Object.fromEntries(childIds.map((childId, index) => [
+ childId,
+ { completed: String(index + 1) },
+ ])),
+ }),
+ }),
+ line('event_msg', { type: 'agent_message', message: 'All three agents completed.' }),
+ line('event_msg', { type: 'task_complete' }),
+ ]
+ const resolver: CodexSubagentResolver = (childId) => ({
+ events: [{
+ type: 'tool_start',
+ payload: { id: `bash-${childId}`, tool: 'Bash', input: { command: 'echo' } },
+ }, {
+ type: 'tool_end',
+ payload: {
+ id: `bash-${childId}`,
+ tool: 'Bash',
+ output: 'done',
+ isError: false,
+ summary: 'done',
+ },
+ }],
+ agentType: 'worker',
+ totalToolUseCount: 1,
+ totalTokens: 10,
+ totalDurationMs: 20,
+ })
+ const liveNormalizer = new CodexNormalizer('live', resolver)
+ const liveEvents = fixture.flatMap((raw) => liveNormalizer.ingest(raw))
+ const replayEvents = codexMessagesToEvents(fixture, resolver)
+ const visualOrder = (events: typeof liveEvents) => events.flatMap((event) => {
+ if (event.type === 'turn_started') return [`user:${event.payload.userMessage}`]
+ if (event.type === 'user_message') return [`user:${event.payload.content}`]
+ if (event.type === 'text_delta') return [`text:${event.payload.content}`]
+ if (event.type === 'tool_start' && event.payload.tool === 'Task') {
+ return [`task:${String((event.payload.input as { title?: string }).title ?? '')}`]
+ }
+ return []
+ })
+
+ expect(visualOrder(liveEvents)).toEqual(visualOrder(replayEvents))
+ expect(visualOrder(liveEvents)).toEqual([
+ `user:${prompt}`,
+ 'text:Launching three agents.',
+ 'task:echo 1',
+ 'task:echo 2',
+ 'task:echo 3',
+ 'text:All three agents completed.',
+ ])
+ })
+})
+
+describe('Codex `/goal` turns', () => {
+ // Shape taken verbatim from a real rollout (019f7ee1…): a `/goal x` submission emits NO
+ // `event_msg/user_message` at all — codex records it only as this injected context, and re-injects
+ // the identical block to drive each continuation turn.
+ const goalCtx = (objective: string) =>
+ line('response_item', {
+ type: 'message',
+ role: 'user',
+ content: [{
+ type: 'input_text',
+ text: `<codex_internal_context source="goal">\nContinue working toward the active thread goal.\n\n<objective>\n${objective}\n</objective>\n\nBudget:\n- Tokens used: 0\n</codex_internal_context>`,
+ }],
+ })
+ const fixture = [
+ line('event_msg', { type: 'task_started' }),
+ goalCtx('lay gia BTC'),
+ line('event_msg', { type: 'agent_message', message: 'done' }),
+ line('event_msg', { type: 'task_complete' }),
+ line('event_msg', { type: 'task_started' }),
+ goalCtx('lay gia BTC'),
+ line('event_msg', { type: 'agent_message', message: 'still going' }),
+ line('event_msg', { type: 'task_complete' }),
+ ]
+
+ it('opens a turn on the goal context, labelling the submission verbatim', () => {
+ const n = new CodexNormalizer('live')
+ const events = fixture.flatMap((l) => n.ingest(l))
+ const turns = events.filter((e) => e.type === 'turn_started' || e.type === 'turn_ended')
+
+ // `/goal <objective>` must reproduce the injected prompt exactly — SessionInputController
+ // fingerprints it, and a mismatch is what surfaced "The agent did not accept the message".
+ expect(turns).toEqual([
+ { type: 'turn_started', payload: { userMessage: '/goal lay gia BTC' } },
+ { type: 'turn_ended', payload: {} },
+ { type: 'turn_started', payload: { userMessage: 'Continuing goal: lay gia BTC' } },
+ { type: 'turn_ended', payload: {} },
+ ])
+ })
+
+ it('leads the recap with the goal instead of an empty prompt', () => {
+ expect(lastCodexTurnText(fixture)).toEqual({
+ userMessage: '/goal lay gia BTC',
+ assistantText: 'still going',
+ })
+ })
+
+ it('snaps a pagination window to the goal context', () => {
+ const w = windowCodexLines(fixture, { limit: 3 })
+
+ expect(w.window[0]).toBe(goalCtx('lay gia BTC'))
+ expect(w.hasMore).toBe(true)
+ })
+})
+
+describe('codex turn failure', () => {
+ // Verbatim from a real rollout: the turn ends, but with no agent message and the reason tucked into
+ // task_complete — which is why the web used to show a turn that finished having said nothing.
+ const TASK_COMPLETE_ERROR = JSON.stringify({
+ type: 'event_msg',
+ payload: {
+ type: 'task_complete',
+ turn_id: '019fb768-786b-7fd2-a6a2-be2dc690e580',
+ last_agent_message: null,
+ error: { message: "You've hit your usage limit. Visit https://chatgpt.com/codex/settings/usage to purchase more credits or try again at Aug 5th, 2026 11:09 AM." },
+ },
+ })
+
+ it('reads the reason a turn failed', () => {
+ expect(codexTaskError(TASK_COMPLETE_ERROR)).toMatch(/^You've hit your usage limit\./)
+ })
+
+ it('stays silent for a healthy turn, an interrupt, or anything else', () => {
+ const ok = JSON.stringify({
+ type: 'event_msg',
+ payload: { type: 'task_complete', turn_id: 't1', last_agent_message: 'done' },
+ })
+ expect(codexTaskError(ok)).toBeNull()
+ // A user interrupt is not a failure and carries no error of its own.
+ expect(codexTaskError(JSON.stringify({ type: 'event_msg', payload: { type: 'turn_aborted' } }))).toBeNull()
+ expect(codexTaskError(JSON.stringify({ type: 'event_msg', payload: { type: 'task_started' } }))).toBeNull()
+ expect(codexTaskError('not json')).toBeNull()
+ })
+
+ it('still ends the turn — the announcement is extra, not a replacement', () => {
+ const normalizer = new CodexNormalizer('live')
+ normalizer.ingest(JSON.stringify({ type: 'event_msg', payload: { type: 'user_message', message: 'Giá Ethereum mới nhất' } }))
+ expect(normalizer.turnOpen).toBe(true)
+
+ const events = normalizer.ingest(TASK_COMPLETE_ERROR)
+ expect(events.some((e) => e.type === 'turn_ended')).toBe(true)
+ expect(normalizer.turnOpen).toBe(false)
+ })
+})
diff --git a/cli/src/engines/codex/normalizer.ts b/cli/src/engines/codex/normalizer.ts
new file mode 100644
index 000000000..8826035c7
--- /dev/null
+++ b/cli/src/engines/codex/normalizer.ts
@@ -0,0 +1,605 @@
+import type { EngineNormalizer } from '../types.js'
+import type { LastTurnText, LiveEvent, SessionEvent } from '../../lib/normalize.js'
+import {
+ codexToolDescriptor,
+ isCodexInternalToolCall,
+ resolveCodexSubagent,
+ type CodexSubagentResolver,
+} from './subagent.js'
+
+type JsonObject = Record<string, unknown>
+
+const MAX_OUTPUT = 2_000
+const MAX_THINKING = 500
+const ORCHESTRATION_TOOLS = new Set([
+ 'spawn_agent',
+ 'wait_agent',
+ 'list_agents',
+ 'send_message',
+ 'followup_task',
+ 'interrupt_agent',
+ 'close_agent',
+ 'resume_agent',
+])
+
+interface TaskInput {
+ subagent_type: string
+ name?: string
+ title: string
+ description: string
+}
+
+interface SpawnState {
+ launcherId: string
+ input: TaskInput
+}
+
+interface ChildResult {
+ output: string
+ isError: boolean
+}
+
+function object(value: unknown): JsonObject | null {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+ ? value as JsonObject
+ : null
+}
+
+function string(value: unknown): string {
+ return typeof value === 'string' ? value : ''
+}
+
+function parse(line: string): JsonObject | null {
+ try { return object(JSON.parse(line)) } catch { return null }
+}
+
+function payload(raw: JsonObject): JsonObject | null {
+ const direct = object(raw.payload)
+ return object(direct?.item) ?? direct
+}
+
+function clip(value: string, limit: number): string {
+ return value.length > limit ? `${value.slice(0, limit)}\n…[truncated]` : value
+}
+
+function textContent(item: JsonObject): string {
+ const content = item.content
+ if (typeof content === 'string') return content
+ if (!Array.isArray(content)) return ''
+ return content
+ .map((part) => {
+ const p = object(part)
+ return p && (p.type === 'input_text' || p.type === 'output_text' || p.type === 'text') ? string(p.text) : ''
+ })
+ .filter(Boolean)
+ .join('')
+}
+
+function parseInput(value: unknown): unknown {
+ if (typeof value !== 'string') return value ?? {}
+ try { return JSON.parse(value) } catch { return value }
+}
+
+function outputText(value: unknown): string {
+ if (typeof value === 'string') return value
+ if (value == null) return ''
+ if (Array.isArray(value)) {
+ return value.map((part) => {
+ if (typeof part === 'string') return part
+ const p = object(part)
+ return p && typeof p.text === 'string' ? p.text : ''
+ }).filter(Boolean).join('')
+ }
+ try { return JSON.stringify(value) ?? '' } catch { return String(value) }
+}
+
+function parseObject(value: unknown): JsonObject | null {
+ const direct = object(value)
+ if (direct) return direct
+ if (typeof value !== 'string') return null
+ try { return object(JSON.parse(value)) } catch { return null }
+}
+
+function taskInput(value: unknown): TaskInput {
+ const args = object(parseInput(value)) ?? {}
+ const message = string(args.message) || string(args.prompt)
+ let title = string(args.title) || string(args.description)
+
+ if (!title && Array.isArray(args.items)) {
+ for (const entry of args.items) {
+ const item = object(entry)
+ const itemText = string(item?.text)
+ const match = /(?:^|\s)description\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s]+))/i.exec(itemText)
+ if (match) { title = match[1] || match[2] || match[3]; break }
+ }
+ }
+ if (!title && message) {
+ const match = /(?:^|\s)description\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s.]+))/i.exec(message)
+ if (match) title = match[1] || match[2] || match[3]
+ }
+ const description = message
+ .replace(/(?:^|\s)description\s*=\s*(?:"[^"]+"|'[^']+'|[^\s.]+)\.?\s*/i, '')
+ .trim()
+ || title
+ || 'Delegated task'
+ title ||= description.split(/[.\n]/)[0].trim().slice(0, 80) || 'Delegated task'
+
+ return {
+ subagent_type: string(args.agent_type) || string(args.subagent_type) || 'agent',
+ title,
+ description,
+ }
+}
+
+function childResults(value: unknown): Map<string, ChildResult> {
+ const result = new Map<string, ChildResult>()
+ const parsed = parseObject(value)
+ const states = object(parsed?.status) ?? object(parsed?.agents_states)
+ if (!states) return result
+
+ for (const [childId, rawState] of Object.entries(states)) {
+ const state = object(rawState)
+ if (!state) continue
+ if (typeof state.completed === 'string') {
+ result.set(childId, { output: state.completed, isError: false })
+ } else if (typeof state.failed === 'string') {
+ result.set(childId, { output: state.failed, isError: true })
+ } else if (state.status === 'completed' || state.status === 'failed') {
+ result.set(childId, {
+ output: string(state.message) || `Subagent ${state.status}`,
+ isError: state.status === 'failed',
+ })
+ }
+ }
+ return result
+}
+
+/**
+ * The failure message codex records when a turn dies, or null for anything else.
+ *
+ * Codex does close the turn on its own — the error rides ON the `task_complete` event rather than
+ * replacing it — so nothing hangs. What was lost is the REASON: the turn ended with
+ * `last_agent_message: null` and no text, so the web showed a turn that finished having said nothing:
+ *
+ * {"type":"event_msg","payload":{"type":"task_complete","turn_id":"019fb768-…",
+ * "last_agent_message":null,
+ * "error":{"message":"You've hit your usage limit. Visit https://chatgpt.com/codex/settings/usage
+ * to purchase more credits or try again at Aug 5th, 2026 11:09 AM."}}}
+ *
+ * Verified against a real rollout (codex 0.145). `turn_aborted` carries no error of its own — a user
+ * interrupt is not a failure — so only `task_complete` is read here.
+ */
+export function codexTaskError(rawLine: string): string | null {
+ const raw = parse(rawLine)
+ if (!raw || string(raw.type) !== 'event_msg') return null
+ const item = payload(raw)
+ if (!item || string(item.type) !== 'task_complete') return null
+ const message = string(object(item.error)?.message)
+ return message.trim() || null
+}
+
+/**
+ * `<codex_internal_context source="goal">…<objective>x</objective>…` → the objective.
+ *
+ * Codex records a `/goal x` submission ONLY as this injected `response_item` user message — it emits
+ * NO `event_msg/user_message` at all — and re-injects the same context at the head of every
+ * continuation turn the goal drives. Everything in this normalizer keys off `user_message`, so
+ * without this a goal session produced ZERO turn events: the adapter's submit-verify never saw the
+ * turn open and reported "The agent did not accept the message", and every autonomous turn after
+ * that was invisible to the web + device.
+ */
+function goalObjective(item: JsonObject): string | null {
+ if (string(item.role) !== 'user') return null
+ const content = Array.isArray(item.content) ? item.content : []
+ const text = content.map((part) => string(object(part)?.text)).filter(Boolean).join('\n')
+ if (!text.includes('<codex_internal_context source="goal">')) return null
+ return text.match(/<objective>\s*([\s\S]*?)\s*<\/objective>/)?.[1]?.trim() || null
+}
+
+function subagentNotification(item: JsonObject): { childId: string; result: ChildResult } | null {
+ if (item.role !== 'user') return null
+ const content = textContent(item)
+ const match = /<subagent_notification>\s*([\s\S]*?)\s*<\/subagent_notification>/.exec(content)
+ if (!match) return null
+ const parsed = parseObject(match[1])
+ const childId = string(parsed?.agent_path) || string(parsed?.agent_id)
+ const status = object(parsed?.status)
+ if (!childId || !status) return null
+ if (typeof status.completed === 'string') return { childId, result: { output: status.completed, isError: false } }
+ if (typeof status.failed === 'string') return { childId, result: { output: status.failed, isError: true } }
+ return null
+}
+
+function toolSummary(name: string, output: string, isError: boolean): string {
+ const first = output.split('\n').map((line) => line.trim()).find(Boolean) ?? ''
+ if (isError) return first ? `${name} failed: ${first}` : `${name} failed`
+ return first || `${name} completed`
+}
+
+function compactEvent(): LiveEvent {
+ return {
+ type: 'context_compact',
+ payload: { message: 'Context was compacted — the previous conversation has been summarized to free up space.' },
+ }
+}
+
+export class CodexNormalizer implements EngineNormalizer {
+ private open = false
+ private pendingTask = false
+ private toolNames = new Map<string, string>()
+ private rawToolNames = new Map<string, string>()
+ private hiddenToolCalls = new Set<string>()
+ private pendingSpawns = new Map<string, SpawnState>()
+ private childLaunchers = new Map<string, SpawnState>()
+ private pendingChildResults = new Map<string, ChildResult>()
+ private completedChildren = new Set<string>()
+ private thinkingCounter = 0
+ private compactJustEmitted = false
+ /** Objective of the active `/goal`, so its re-injection each turn isn't read as a new submission. */
+ private goalObjective: string | null = null
+
+ constructor(
+ private readonly mode: 'live' | 'replay',
+ private readonly resolveSubagent: CodexSubagentResolver = resolveCodexSubagent,
+ ) {}
+
+ get turnOpen(): boolean { return this.open }
+
+ closeTurn(): void { this.open = false; this.pendingTask = false }
+
+ ingest(line: string): LiveEvent[] {
+ const raw = parse(line)
+ if (!raw) return []
+ const topType = string(raw.type)
+ const item = payload(raw)
+ const type = string(item?.type)
+
+ if (topType === 'compacted') {
+ this.compactJustEmitted = true
+ return [compactEvent()]
+ }
+ if (topType === 'event_msg' && type === 'context_compacted') {
+ if (this.compactJustEmitted) { this.compactJustEmitted = false; return [] }
+ return [compactEvent()]
+ }
+ if (this.compactJustEmitted && topType === 'event_msg' && type === 'token_count') return []
+ this.compactJustEmitted = false
+ if (!item) return []
+
+ if (topType === 'event_msg') return this.eventMessage(type, item)
+ if (topType === 'response_item') return this.responseItem(type, item)
+ return []
+ }
+
+ finishReplay(): LiveEvent[] {
+ if (this.mode !== 'replay') return []
+ return [...this.completeOutstanding(false), { type: 'done', payload: { result: 'success' } }]
+ }
+
+ private eventMessage(type: string, item: JsonObject): LiveEvent[] {
+ if (type === 'task_started') {
+ this.pendingTask = true
+ return []
+ }
+
+ if (type === 'user_message') {
+ const message = string(item.message)
+ if (!message) return []
+ if (this.mode === 'replay') return [{ type: 'user_message', payload: { content: message } }]
+ const events: LiveEvent[] = []
+ if (this.open) events.push({ type: 'turn_ended', payload: {} })
+ this.pendingTask = false
+ this.open = true
+ events.push({ type: 'turn_started', payload: { userMessage: message } })
+ return events
+ }
+
+ if (type === 'agent_message') {
+ const message = string(item.message)
+ return message ? [{ type: 'text_delta', payload: { content: message } }] : []
+ }
+
+ if (type === 'task_complete' || type === 'turn_aborted') {
+ this.pendingTask = false
+ const events = this.completeOutstanding(type === 'turn_aborted')
+ if (!this.open || this.mode === 'replay') return events
+ this.open = false
+ return [...events, { type: 'turn_ended', payload: {} }]
+ }
+
+ return []
+ }
+
+ /**
+ * A goal-context injection opens a turn. The FIRST one is the user's actual `/goal x` submission —
+ * labelled `/goal <objective>` so it reproduces the injected prompt byte-for-byte and the adapter's
+ * submit-verify fingerprint matches. Codex re-injects the identical context to drive each
+ * continuation turn; those are labelled distinctly so they don't read as the user asking again.
+ */
+ private goalTurn(objective: string): LiveEvent[] {
+ const submission = this.goalObjective !== objective
+ this.goalObjective = objective
+ const userMessage = submission ? `/goal ${objective}` : `Continuing goal: ${objective}`
+ if (this.mode === 'replay') return [{ type: 'user_message', payload: { content: userMessage } }]
+ const events: LiveEvent[] = []
+ if (this.open) events.push({ type: 'turn_ended', payload: {} })
+ this.pendingTask = false
+ this.open = true
+ events.push({ type: 'turn_started', payload: { userMessage } })
+ return events
+ }
+
+ private responseItem(type: string, item: JsonObject): LiveEvent[] {
+ // event_msg user/agent messages are authoritative and are emitted once. The one exception is an
+ // internal subagent_notification, which closes the matching Task launcher and is never user text.
+ if (type === 'message') {
+ const objective = goalObjective(item)
+ if (objective) return this.goalTurn(objective)
+ const notification = subagentNotification(item)
+ return notification ? this.completeChild(notification.childId, notification.result) : []
+ }
+
+ if (type === 'reasoning') {
+ const summary = Array.isArray(item.summary)
+ ? item.summary.map((part) => string(object(part)?.text)).filter(Boolean).join('\n')
+ : string(item.summary)
+ if (!summary) return []
+ return [{
+ type: 'thinking_delta',
+ payload: { content: clip(summary, MAX_THINKING), thinkingId: `thinking-codex-${this.thinkingCounter++}` },
+ }]
+ }
+
+ if (type === 'function_call' || type === 'custom_tool_call' || type === 'tool_search_call') {
+ const id = string(item.call_id) || string(item.id)
+ const name = string(item.name) || (type === 'tool_search_call' ? 'tool_search' : 'tool')
+ if (!id) return []
+ if (isCodexInternalToolCall(name, item.arguments ?? item.input)) {
+ this.hiddenToolCalls.add(id)
+ return []
+ }
+ this.rawToolNames.set(id, name)
+
+ if (name === 'spawn_agent') {
+ const input = taskInput(item.arguments ?? item.input)
+ const spawn = { launcherId: id, input }
+ this.pendingSpawns.set(id, spawn)
+ this.toolNames.set(id, 'Task')
+ return []
+ }
+ if (ORCHESTRATION_TOOLS.has(name)) return []
+
+ const descriptor = codexToolDescriptor(name, item.arguments ?? item.input)
+ this.toolNames.set(id, descriptor.tool)
+ return [{ type: 'tool_start', payload: { id, tool: descriptor.tool, input: descriptor.input } }]
+ }
+
+ if (type === 'function_call_output' || type === 'custom_tool_call_output' || type === 'tool_search_output') {
+ const id = string(item.call_id) || string(item.id)
+ if (!id) return []
+ if (this.hiddenToolCalls.delete(id)) return []
+ const rawName = this.rawToolNames.get(id) || ''
+ this.rawToolNames.delete(id)
+ if (rawName === 'spawn_agent') return this.handleSpawnOutput(id, item)
+ if (ORCHESTRATION_TOOLS.has(rawName)) return this.completeFromStatus(item.output)
+
+ const name = this.toolNames.get(id) || 'tool'
+ this.toolNames.delete(id)
+ const rawOutput = outputText(item.output)
+ const isError = item.is_error === true || item.status === 'failed'
+ return [{
+ type: 'tool_end',
+ payload: {
+ id,
+ tool: name,
+ output: clip(rawOutput, MAX_OUTPUT),
+ isError,
+ summary: toolSummary(name, rawOutput, isError),
+ },
+ }]
+ }
+
+ return []
+ }
+
+ private handleSpawnOutput(id: string, item: JsonObject): LiveEvent[] {
+ const spawn = this.pendingSpawns.get(id)
+ if (!spawn) return []
+ this.toolNames.delete(id)
+ const parsed = parseObject(item.output)
+ const childId = string(parsed?.agent_id) || string(parsed?.thread_id)
+ if (childId) {
+ const nickname = string(parsed?.nickname) || string(parsed?.name)
+ if (nickname) spawn.input.name = nickname
+ this.pendingSpawns.delete(id)
+ this.childLaunchers.set(childId, spawn)
+ const events: LiveEvent[] = [{
+ type: 'tool_start',
+ payload: { id: spawn.launcherId, tool: 'Task', input: spawn.input },
+ }]
+ const pending = this.pendingChildResults.get(childId)
+ if (!pending) return events
+ this.pendingChildResults.delete(childId)
+ return [...events, ...this.completeChild(childId, pending)]
+ }
+
+ this.pendingSpawns.delete(id)
+ const output = outputText(item.output) || 'Subagent failed to start'
+ return [
+ { type: 'tool_start', payload: { id: spawn.launcherId, tool: 'Task', input: spawn.input } },
+ {
+ type: 'tool_end',
+ payload: {
+ id: spawn.launcherId,
+ tool: 'Task',
+ output: clip(output, MAX_OUTPUT),
+ isError: true,
+ summary: toolSummary('Task', output, true),
+ },
+ },
+ ]
+ }
+
+ private completeFromStatus(value: unknown): LiveEvent[] {
+ const events: LiveEvent[] = []
+ for (const [childId, result] of childResults(value)) events.push(...this.completeChild(childId, result))
+ return events
+ }
+
+ private completeChild(childId: string, result: ChildResult): LiveEvent[] {
+ if (this.completedChildren.has(childId)) return []
+ const spawn = this.childLaunchers.get(childId)
+ if (!spawn) {
+ this.pendingChildResults.set(childId, result)
+ return []
+ }
+
+ this.completedChildren.add(childId)
+ this.childLaunchers.delete(childId)
+ this.pendingChildResults.delete(childId)
+ let info: ReturnType<CodexSubagentResolver> = null
+ try { info = this.resolveSubagent(childId) } catch { /* close the Task even if history is unreadable */ }
+
+ const events: LiveEvent[] = []
+ for (const event of info?.events ?? []) {
+ if (event.type === 'tool_start') {
+ events.push({
+ type: 'tool_start',
+ payload: { ...event.payload, parentToolUseId: spawn.launcherId },
+ })
+ } else {
+ events.push({
+ type: 'tool_end',
+ payload: { ...event.payload, parentToolUseId: spawn.launcherId },
+ })
+ }
+ }
+ const output = result.output || (result.isError ? 'Subagent failed' : 'Subagent completed')
+ events.push({
+ type: 'tool_end',
+ payload: {
+ id: spawn.launcherId,
+ tool: 'Task',
+ output: clip(output, MAX_OUTPUT),
+ isError: result.isError,
+ summary: toolSummary('Task', output, result.isError),
+ subagent: {
+ agentId: childId,
+ agentType: info?.agentType ?? spawn.input.subagent_type,
+ totalToolUseCount: info?.totalToolUseCount ?? 0,
+ totalTokens: info?.totalTokens ?? 0,
+ totalDurationMs: info?.totalDurationMs ?? 0,
+ },
+ },
+ })
+ return events
+ }
+
+ private completeOutstanding(isError: boolean): LiveEvent[] {
+ const events: LiveEvent[] = []
+ for (const childId of [...this.childLaunchers.keys()]) {
+ events.push(...this.completeChild(childId, {
+ output: isError ? 'Subagent turn aborted' : 'Subagent completed',
+ isError,
+ }))
+ }
+ for (const [callId, spawn] of this.pendingSpawns) {
+ const output = isError ? 'Subagent turn aborted' : 'Subagent finished without an agent id'
+ events.push(
+ { type: 'tool_start', payload: { id: spawn.launcherId, tool: 'Task', input: spawn.input } },
+ {
+ type: 'tool_end',
+ payload: {
+ id: spawn.launcherId,
+ tool: 'Task',
+ output,
+ isError: true,
+ summary: toolSummary('Task', output, true),
+ },
+ },
+ )
+ this.pendingSpawns.delete(callId)
+ }
+ this.pendingChildResults.clear()
+ return events
+ }
+}
+
+export function codexMessagesToEvents(
+ rawLines: string[],
+ resolveSubagent: CodexSubagentResolver = resolveCodexSubagent,
+): SessionEvent[] {
+ const normalizer = new CodexNormalizer('replay', resolveSubagent)
+ const events: SessionEvent[] = []
+ for (const line of rawLines) events.push(...normalizer.ingest(line) as SessionEvent[])
+ events.push(...normalizer.finishReplay() as SessionEvent[])
+ return events
+}
+
+export function lastCodexTurnText(rawLines: string[]): LastTurnText | null {
+ let userMessage = ''
+ let assistantText = ''
+ for (const line of rawLines) {
+ const raw = parse(line)
+ if (!raw) continue
+ const item = payload(raw)
+ if (!item) continue
+ // A `/goal` turn has no `user_message` — its prompt lives in the injected goal context.
+ if (raw.type === 'response_item' && string(item.type) === 'message') {
+ const objective = goalObjective(item)
+ if (objective) { userMessage = `/goal ${objective}`; assistantText = '' }
+ continue
+ }
+ if (raw.type !== 'event_msg') continue
+ if (item.type === 'user_message') {
+ const message = string(item.message)
+ if (message) { userMessage = message; assistantText = '' }
+ } else if (item.type === 'agent_message') {
+ const message = string(item.message)
+ if (message) assistantText += `${assistantText ? '\n\n' : ''}${message}`
+ }
+ }
+ return assistantText ? { userMessage, assistantText } : null
+}
+
+export function windowCodexLines(
+ rawLines: string[],
+ opts: { limit: number; before?: string },
+): { window: string[]; hasMore: boolean; oldestCursor: string | null; staleCursor?: boolean } {
+ let endIndex = rawLines.length
+ if (opts.before) {
+ const match = /^codex:(\d+)$/.exec(opts.before)
+ if (!match) return { window: [], hasMore: false, oldestCursor: null, staleCursor: true }
+ endIndex = Number(match[1])
+ if (!Number.isSafeInteger(endIndex) || endIndex < 0 || endIndex > rawLines.length) {
+ return { window: [], hasMore: false, oldestCursor: null, staleCursor: true }
+ }
+ }
+
+ let start = Math.max(0, endIndex - opts.limit)
+ while (start > 0) {
+ const raw = parse(rawLines[start])
+ const item = raw ? payload(raw) : null
+ if (raw?.type === 'event_msg' && item?.type === 'user_message') break
+ // A goal turn starts on the injected goal context, not on a `user_message`.
+ if (raw?.type === 'response_item' && item && string(item.type) === 'message' && goalObjective(item)) break
+ start--
+ }
+ return {
+ window: rawLines.slice(start, endIndex),
+ hasMore: start > 0,
+ oldestCursor: `codex:${start}`,
+ }
+}
+
+export function codexSessionMeta(rawLines: string[]): { id: string; cwd: string; cliVersion: string } | null {
+ for (const line of rawLines) {
+ const raw = parse(line)
+ if (raw?.type !== 'session_meta') continue
+ const item = payload(raw)
+ if (!item) continue
+ const id = string(item.id) || string(item.session_id)
+ if (id) return { id, cwd: string(item.cwd), cliVersion: string(item.cli_version) }
+ }
+ return null
+}
diff --git a/cli/src/engines/codex/rollout.ts b/cli/src/engines/codex/rollout.ts
new file mode 100644
index 000000000..75fb80607
--- /dev/null
+++ b/cli/src/engines/codex/rollout.ts
@@ -0,0 +1,79 @@
+import { closeSync, existsSync, openSync, readSync, readdirSync } from 'fs'
+import { homedir } from 'os'
+import { join } from 'path'
+
+type JsonObject = Record<string, unknown>
+
+const MAX_WALK_ENTRIES = 5_000
+const MAX_META_BYTES = 128 * 1024
+const THREAD_ID_RE = /^[a-zA-Z0-9-]{8,128}$/
+const CODEX_SESSIONS_DIR = join(process.env.CODEX_HOME || join(homedir(), '.codex'), 'sessions')
+
+export interface CodexRolloutMeta {
+ id: string
+ isSubagent: boolean
+ parentThreadId: string | null
+ /** The directory the session was started in — the only field that identifies WHERE a rollout belongs. */
+ cwd: string | null
+}
+
+function object(value: unknown): JsonObject | null {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+ ? value as JsonObject
+ : null
+}
+
+/** Read only the first rollout record, which is Codex's session_meta line. */
+export function readCodexRolloutMeta(file: string): CodexRolloutMeta | null {
+ let fd: number | null = null
+ try {
+ fd = openSync(file, 'r')
+ const buffer = Buffer.alloc(MAX_META_BYTES)
+ const bytes = readSync(fd, buffer, 0, buffer.length, 0)
+ const firstLine = buffer.subarray(0, bytes).toString('utf8').split('\n').find((line) => line.trim())
+ if (!firstLine) return null
+ const record = object(JSON.parse(firstLine))
+ const payload = object(record?.payload)
+ if (record?.type !== 'session_meta' || !payload) return null
+ const source = object(payload.source)
+ const subagent = source?.subagent
+ const spawn = object(object(subagent)?.thread_spawn)
+ const parentThreadId = typeof spawn?.parent_thread_id === 'string' && spawn.parent_thread_id
+ ? spawn.parent_thread_id
+ : null
+ return {
+ id: typeof payload.id === 'string' ? payload.id : '',
+ isSubagent: subagent !== undefined && subagent !== null,
+ parentThreadId,
+ cwd: typeof payload.cwd === 'string' ? payload.cwd : null,
+ }
+ } catch {
+ return null
+ } finally {
+ if (fd !== null) {
+ try { closeSync(fd) } catch { /* best effort */ }
+ }
+ }
+}
+
+/** Find one rollout by thread id without scanning unbounded user history. */
+export function resolveCodexRollout(threadId: string, root = CODEX_SESSIONS_DIR): string | null {
+ if (!THREAD_ID_RE.test(threadId) || !existsSync(root)) return null
+ const stack = [root]
+ let visited = 0
+ while (stack.length && visited < MAX_WALK_ENTRIES) {
+ const dir = stack.pop()!
+ let names: string[]
+ try { names = readdirSync(dir) } catch { continue }
+ for (const name of names) {
+ if (++visited > MAX_WALK_ENTRIES) break
+ const full = join(dir, name)
+ if (name.endsWith('.jsonl')) {
+ if (name.includes(threadId)) return full
+ } else if (!name.includes('.')) {
+ stack.push(full)
+ }
+ }
+ }
+ return null
+}
diff --git a/cli/src/engines/codex/subagent.spec.ts b/cli/src/engines/codex/subagent.spec.ts
new file mode 100644
index 000000000..c48bbcad8
--- /dev/null
+++ b/cli/src/engines/codex/subagent.spec.ts
@@ -0,0 +1,74 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import { codexToolDescriptor, readChildRollout, resolveChildRollout } from './subagent.js'
+
+let root = ''
+
+const line = (timestamp: string, type: string, payload: Record<string, unknown>) => JSON.stringify({ timestamp, type, payload })
+
+describe('Codex child rollout reader', () => {
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'adapter-codex-child-'))
+ })
+
+ afterEach(() => {
+ rmSync(root, { recursive: true, force: true })
+ })
+
+ it('resolves a child rollout and converts its tools and aggregate stats', () => {
+ const childId = '019f35c1-8017-7391-beb4-06a01ceda2bd'
+ const dir = join(root, '2026', '07', '16')
+ mkdirSync(dir, { recursive: true })
+ const file = join(dir, `rollout-2026-07-16T12-00-00-${childId}.jsonl`)
+ writeFileSync(file, [
+ line('2026-07-16T12:00:00.000Z', 'session_meta', { id: childId, source: { subagent: 'explorer' } }),
+ line('2026-07-16T12:00:01.000Z', 'response_item', { type: 'function_call', call_id: 'call-1', name: 'exec_command', arguments: '{"cmd":"npm test"}' }),
+ line('2026-07-16T12:00:02.000Z', 'response_item', { type: 'function_call_output', call_id: 'call-1', output: 'passed' }),
+ line('2026-07-16T12:00:03.000Z', 'event_msg', { type: 'token_count', info: { total_token_usage: { total_tokens: 456 } } }),
+ ].join('\n'))
+
+ expect(resolveChildRollout(childId, root)).toBe(file)
+ expect(readChildRollout(file)).toEqual({
+ events: [
+ { type: 'tool_start', payload: { id: 'codex-child-call-1', tool: 'Bash', input: { command: 'npm test' } } },
+ { type: 'tool_end', payload: { id: 'codex-child-call-1', tool: 'Bash', output: 'passed', isError: false, summary: 'passed' } },
+ ],
+ agentType: 'explorer',
+ totalToolUseCount: 1,
+ totalTokens: 456,
+ totalDurationMs: 3_000,
+ })
+ })
+
+ it('rejects unsafe child ids before walking the filesystem', () => {
+ expect(resolveChildRollout('../../etc/passwd', root)).toBeNull()
+ })
+
+ it('extracts the inner tool and query from Codex custom exec wrappers', () => {
+ expect(codexToolDescriptor(
+ 'exec',
+ 'const r = await tools.web__run({search_query:[{q:"BTC USD current price"}]}); text(r)',
+ )).toEqual({ tool: 'WebSearch', input: { query: 'BTC USD current price' } })
+ expect(codexToolDescriptor(
+ 'exec',
+ 'const r = await tools.web__run({finance:[{ticker:"BTC",type:"crypto"}]}); text(r)',
+ )).toEqual({ tool: 'WebSearch', input: { query: '' } })
+ })
+
+ it('maps wrapped Codex plans to the Claude TodoWrite contract', () => {
+ expect(codexToolDescriptor(
+ 'exec',
+ 'const r = await tools.update_plan({plan:[{step:"Research","status":"completed"},{step:"Report","status":"in_progress"}]}); text(r)',
+ )).toEqual({
+ tool: 'TodoWrite',
+ input: {
+ todos: [
+ { content: 'Research', status: 'completed' },
+ { content: 'Report', status: 'in_progress' },
+ ],
+ },
+ })
+ })
+})
diff --git a/cli/src/engines/codex/subagent.ts b/cli/src/engines/codex/subagent.ts
new file mode 100644
index 000000000..321b16ef8
--- /dev/null
+++ b/cli/src/engines/codex/subagent.ts
@@ -0,0 +1,225 @@
+import { readFileSync } from 'fs'
+import type { SessionEvent } from '../../lib/normalize.js'
+import { resolveCodexRollout } from './rollout.js'
+
+type JsonObject = Record<string, unknown>
+
+export interface CodexSubagentInfo {
+ events: Array<Extract<SessionEvent, { type: 'tool_start' | 'tool_end' }>>
+ agentType: string
+ totalToolUseCount: number
+ totalTokens: number
+ totalDurationMs: number
+}
+
+export type CodexSubagentResolver = (threadId: string) => CodexSubagentInfo | null
+
+function object(value: unknown): JsonObject | null {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+ ? value as JsonObject
+ : null
+}
+
+function parseObject(value: unknown): JsonObject {
+ if (object(value)) return value as JsonObject
+ if (typeof value !== 'string') return {}
+ try { return object(JSON.parse(value)) ?? { raw: value } } catch { return { raw: value } }
+}
+
+function text(value: unknown): string {
+ if (typeof value === 'string') return value
+ if (Array.isArray(value)) {
+ return value.map((part) => {
+ if (typeof part === 'string') return part
+ const p = object(part)
+ return p && typeof p.text === 'string' ? p.text : ''
+ }).filter(Boolean).join('\n')
+ }
+ const obj = object(value)
+ if (obj && typeof obj.text === 'string') return obj.text
+ try { return JSON.stringify(value ?? '') } catch { return String(value ?? '') }
+}
+
+function commandText(args: JsonObject): string {
+ const value = args.cmd ?? args.command
+ if (typeof value === 'string') return value
+ if (Array.isArray(value)) return value.map(String).join(' ')
+ return text(value || args)
+}
+
+function jsStringProperty(source: string, key: string): string {
+ const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+ const match = new RegExp(`(?:\\b${escapedKey}\\b|["']${escapedKey}["'])\\s*:\\s*("(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*')`).exec(source)
+ if (!match) return ''
+ const quoted = match[1]
+ if (quoted.startsWith('"')) {
+ try { return JSON.parse(quoted) as string } catch { return quoted.slice(1, -1) }
+ }
+ return quoted.slice(1, -1).replace(/\\'/g, "'").replace(/\\\\/g, '\\')
+}
+
+function wrappedExecDescriptor(source: string): { tool: string; input: unknown } | null {
+ const match = /\btools\.([a-zA-Z0-9_$]+)\s*\(/.exec(source)
+ if (!match) return null
+ const wrappedTool = match[1]
+ switch (wrappedTool) {
+ case 'web__run':
+ return { tool: 'WebSearch', input: { query: jsStringProperty(source, 'q') } }
+ case 'exec_command':
+ return { tool: 'Bash', input: { command: jsStringProperty(source, 'cmd') || jsStringProperty(source, 'command') } }
+ case 'apply_patch':
+ return { tool: 'ApplyPatch', input: { patch: source } }
+ case 'update_plan': {
+ const todos = (source.match(/\{[^{}]*\}/g) ?? []).flatMap((entry) => {
+ const content = jsStringProperty(entry, 'step')
+ const status = jsStringProperty(entry, 'status')
+ return content ? [{ content, status: status || 'pending' }] : []
+ })
+ return { tool: 'TodoWrite', input: { todos } }
+ }
+ default:
+ return { tool: wrappedTool, input: { script: source } }
+ }
+}
+
+/** Codex may use exec only to inspect deferred tool metadata; this is not user-visible work. */
+export function isCodexInternalToolCall(name: string, rawInput: unknown): boolean {
+ return name === 'exec'
+ && typeof rawInput === 'string'
+ && /\bALL_TOOLS\b/.test(rawInput)
+ && !/\btools\.[a-zA-Z0-9_$]+\s*\(/.test(rawInput)
+}
+
+/** Codex rollout function name -> the existing Claude-style tool vocabulary used by web/device. */
+export function codexToolDescriptor(name: string, rawInput: unknown): { tool: string; input: unknown } {
+ if (name === 'exec' && typeof rawInput === 'string') {
+ const wrapped = wrappedExecDescriptor(rawInput)
+ if (wrapped) return wrapped
+ }
+ const args = parseObject(rawInput)
+ switch (name) {
+ case 'exec_command':
+ case 'shell':
+ case 'local_shell':
+ case 'unified_exec':
+ return { tool: 'Bash', input: { command: commandText(args) } }
+ case 'apply_patch':
+ return { tool: 'ApplyPatch', input: args }
+ case 'web_search':
+ case 'web':
+ return { tool: 'WebSearch', input: { query: typeof args.query === 'string' ? args.query : '' } }
+ case 'update_plan': {
+ // Codex's plan tool ≙ Claude's TodoWrite: {plan:[{status,step}]} → {todos:[{content,status}]}.
+ // Statuses are identical (pending|in_progress|completed), so the web TodoTracker consumes it as-is.
+ const plan = Array.isArray(args.plan) ? args.plan : []
+ const todos = plan.flatMap((entry) => {
+ const o = object(entry)
+ const content = typeof o?.step === 'string' ? o.step : ''
+ const status = typeof o?.status === 'string' ? o.status : 'pending'
+ return content ? [{ content, status }] : []
+ })
+ return { tool: 'TodoWrite', input: { todos } }
+ }
+ default:
+ return { tool: name || 'tool', input: object(rawInput) ? rawInput : (typeof rawInput === 'string' ? rawInput : args) }
+ }
+}
+
+/** Backward-compatible name used by the subagent resolver/tests. */
+export const resolveChildRollout = resolveCodexRollout
+
+/** Read the child transcript only after it completed, matching the hosted runtime's aggregation semantics. */
+export function readChildRollout(file: string): CodexSubagentInfo | null {
+ let raw: string
+ try { raw = readFileSync(file, 'utf8') } catch { return null }
+
+ const calls: Array<{ id: string; tool: string; input: unknown }> = []
+ const outputs = new Map<string, { output: string; isError: boolean }>()
+ let agentType = 'agent'
+ let totalTokens = 0
+ let firstTs: number | null = null
+ let lastTs: number | null = null
+
+ for (const line of raw.split('\n')) {
+ if (!line.trim()) continue
+ let record: JsonObject
+ try { record = object(JSON.parse(line)) ?? {} } catch { continue }
+ const parsedTs = typeof record.timestamp === 'string' ? Date.parse(record.timestamp) : NaN
+ if (Number.isFinite(parsedTs)) {
+ firstTs ??= parsedTs
+ lastTs = parsedTs
+ }
+ const payload = object(record.payload) ?? {}
+ const payloadType = typeof payload.type === 'string' ? payload.type : ''
+
+ if (record.type === 'session_meta') {
+ const source = object(payload.source)
+ const fromSource = source && typeof source.subagent === 'string' ? source.subagent : ''
+ agentType = fromSource
+ || (typeof payload.agent_nickname === 'string' ? payload.agent_nickname : '')
+ || (typeof payload.agent_role === 'string' ? payload.agent_role : '')
+ || 'agent'
+ continue
+ }
+
+ if (record.type === 'event_msg' && payloadType === 'token_count') {
+ const info = object(payload.info)
+ const usage = object(info?.total_token_usage)
+ if (typeof usage?.total_tokens === 'number') totalTokens = usage.total_tokens
+ continue
+ }
+
+ if (record.type !== 'response_item') continue
+ if (payloadType === 'function_call' || payloadType === 'custom_tool_call' || payloadType === 'tool_search_call') {
+ const id = (typeof payload.call_id === 'string' && payload.call_id)
+ || (typeof payload.id === 'string' && payload.id)
+ || `child-call-${calls.length}`
+ const name = typeof payload.name === 'string'
+ ? payload.name
+ : (payloadType === 'tool_search_call' ? 'tool_search' : 'tool')
+ if (isCodexInternalToolCall(name, payload.arguments ?? payload.input)) continue
+ const descriptor = codexToolDescriptor(name, payload.arguments ?? payload.input)
+ calls.push({ id, tool: descriptor.tool, input: descriptor.input })
+ continue
+ }
+
+ if (payloadType === 'function_call_output' || payloadType === 'custom_tool_call_output' || payloadType === 'tool_search_output') {
+ const id = (typeof payload.call_id === 'string' && payload.call_id)
+ || (typeof payload.id === 'string' && payload.id)
+ if (id) outputs.set(id, {
+ output: text(payload.output),
+ isError: payload.is_error === true || payload.status === 'failed',
+ })
+ }
+ }
+
+ const events: CodexSubagentInfo['events'] = []
+ for (const call of calls) {
+ const stableId = `codex-child-${call.id}`
+ const result = outputs.get(call.id) ?? { output: '', isError: false }
+ events.push({ type: 'tool_start', payload: { id: stableId, tool: call.tool, input: call.input } })
+ events.push({
+ type: 'tool_end',
+ payload: {
+ id: stableId,
+ tool: call.tool,
+ output: result.output,
+ isError: result.isError,
+ summary: result.output.split('\n').find(Boolean)?.slice(0, 120) || `${call.tool} completed`,
+ },
+ })
+ }
+
+ return {
+ events,
+ agentType,
+ totalToolUseCount: calls.length,
+ totalTokens,
+ totalDurationMs: firstTs !== null && lastTs !== null ? Math.max(0, lastTs - firstTs) : 0,
+ }
+}
+
+export const resolveCodexSubagent: CodexSubagentResolver = (threadId) => {
+ const file = resolveChildRollout(threadId)
+ return file ? readChildRollout(file) : null
+}
diff --git a/cli/src/engines/commandcode/normalizer.spec.ts b/cli/src/engines/commandcode/normalizer.spec.ts
new file mode 100644
index 000000000..07357b307
--- /dev/null
+++ b/cli/src/engines/commandcode/normalizer.spec.ts
@@ -0,0 +1,187 @@
+import { describe, expect, it } from 'vitest'
+import {
+ CommandCodeNormalizer,
+ commandCodeRunError,
+ commandCodeRunErrorSummary,
+ commandCodeSessionMeta,
+ commandCodeToolName,
+ commandcodeMessagesToEvents,
+ lastCommandCodeTurnText,
+ reshapeLine,
+ windowCommandCodeLines,
+} from './normalizer.js'
+
+// Lines copied from a REAL captured Command Code session (commandcode 1.4.4): a plain turn, then a
+// tool-calling turn (`shell_command`), then the closing text turn.
+const CALL = 'call_00_U0MkyEAMP9Xu'
+const HEADER = '{"type":"session","version":3,"id":"34e1385f-c18a-4f54-bf12-f8f57e151a3d","timestamp":"2026-07-28T04:16:39.000Z","cwd":"/tmp/cc-probe"}'
+const LINES = [
+ HEADER,
+ '{"type":"message","id":"b9b74cd5","parentId":null,"timestamp":"t1","message":{"role":"user","content":[{"type":"text","text":"hi"}],"meta":{"source":"user","messageId":"m1"}}}',
+ '{"type":"message","id":"be03e3d9","parentId":"b9b74cd5","timestamp":"t2","message":{"role":"assistant","content":[{"type":"thinking","thinking":"Simple greeting.","signature":""},{"type":"text","text":"Hi! What can I help you with today?"}],"meta":{"source":"model","messageId":"m2"}}}',
+ '{"type":"message","id":"59ec89ec","parentId":"be03e3d9","timestamp":"t3","message":{"role":"user","content":[{"type":"text","text":"list the files"}],"meta":{"source":"user","messageId":"m3"}}}',
+ `{"type":"message","id":"6c05e6e5","parentId":"59ec89ec","timestamp":"t4","message":{"role":"assistant","content":[{"type":"thinking","thinking":"I should run ls.","signature":""},{"type":"tool_use","id":"${CALL}","name":"shell_command","input":{"command":"ls -1"}}],"meta":{"source":"model","messageId":"m4"}}}`,
+ `{"type":"message","id":"72d9f290","parentId":"6c05e6e5","timestamp":"t5","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"${CALL}","content":[{"type":"text","text":"a.txt\\nb.txt"}]}],"meta":{"source":"tool","messageId":"m5"}}}`,
+ '{"type":"message","id":"4c3052c4","parentId":"72d9f290","timestamp":"t6","message":{"role":"assistant","content":[{"type":"thinking","thinking":"Report them.","signature":""},{"type":"text","text":"a.txt and b.txt"}],"meta":{"source":"model","messageId":"m6"}}}',
+]
+
+function live(lines: string[]) {
+ const normalizer = new CommandCodeNormalizer('live')
+ return { normalizer, events: lines.flatMap((line) => normalizer.ingest(line)) }
+}
+
+describe('Command Code normalizer — reshape into the Claude shape', () => {
+ it('drops the header and maps meta.source onto the claude record type', () => {
+ expect(reshapeLine(HEADER)).toBeNull()
+ expect(reshapeLine('not json')).toBeNull()
+
+ const user = JSON.parse(reshapeLine(LINES[1])!) as Record<string, unknown>
+ expect(user).toMatchObject({ type: 'user', uuid: 'b9b74cd5', parentUuid: null })
+
+ // A `tool` row is a role:"user" message carrying tool_result — it must NOT look like a prompt.
+ const tool = JSON.parse(reshapeLine(LINES[5])!) as { type: string; message: { content: Array<{ type: string }> } }
+ expect(tool.type).toBe('user')
+ expect(tool.message.content[0].type).toBe('tool_result')
+ })
+
+ it('synthesizes the stop_reason Command Code does not record', () => {
+ const withTool = JSON.parse(reshapeLine(LINES[4])!) as { message: { stop_reason: string } }
+ const withoutTool = JSON.parse(reshapeLine(LINES[2])!) as { message: { stop_reason: string } }
+ expect(withTool.message.stop_reason).toBe('tool_use') // turn continues into the tool
+ expect(withoutTool.message.stop_reason).toBe('end_turn') // turn is done
+ })
+
+ it('maps tool ids onto the shared vocabulary inside the reshaped line', () => {
+ const reshaped = JSON.parse(reshapeLine(LINES[4])!) as { message: { content: Array<{ type: string; name?: string }> } }
+ expect(reshaped.message.content.find((p) => p.type === 'tool_use')?.name).toBe('Bash')
+ expect(commandCodeToolName('shell_command')).toBe('Bash')
+ expect(commandCodeToolName('read_file')).toBe('Read')
+ expect(commandCodeToolName('web_search')).toBe('WebSearch')
+ expect(commandCodeToolName('todo_write')).toBe('TodoWrite')
+ expect(commandCodeToolName('activate_skill')).toBe('Task')
+ expect(commandCodeToolName('some_new_tool')).toBe('SomeNewTool')
+ })
+})
+
+describe('Command Code normalizer — live turn lifecycle', () => {
+ it('derives turn_started/turn_ended for a plain turn and a tool-calling turn', () => {
+ const { normalizer, events } = live(LINES)
+ expect(events.map((e) => e.type)).toEqual([
+ 'turn_started', 'thinking_delta', 'thinking_title', 'text_delta', 'turn_ended', // "hi"
+ 'turn_started', 'thinking_delta', 'thinking_title', 'tool_start', // "list the files"
+ 'tool_end',
+ 'thinking_delta', 'thinking_title', 'text_delta', 'turn_ended',
+ ])
+ expect(events[0]).toMatchObject({ type: 'turn_started', payload: { userMessage: 'hi' } })
+ expect(normalizer.turnOpen).toBe(false)
+ })
+
+ it('keeps the turn OPEN while a tool call is outstanding', () => {
+ const { normalizer } = live(LINES.slice(0, 5)) // … up to the assistant that calls the tool
+ expect(normalizer.turnOpen).toBe(true)
+ })
+
+ it('pairs tool_use with its tool_result on the shared card', () => {
+ const { events } = live(LINES)
+ expect(events.find((e) => e.type === 'tool_start')).toMatchObject({
+ payload: { id: CALL, tool: 'Bash', input: { command: 'ls -1' } },
+ })
+ expect(events.find((e) => e.type === 'tool_end')).toMatchObject({
+ payload: { id: CALL, tool: 'Bash', output: 'a.txt\nb.txt', isError: false },
+ })
+ })
+
+ it('closeTurn() clears the open turn', () => {
+ const { normalizer } = live(LINES.slice(0, 5))
+ normalizer.closeTurn()
+ expect(normalizer.turnOpen).toBe(false)
+ })
+})
+
+describe('Command Code normalizer — replay, recap, window', () => {
+ it('replays as user_message + assistant blocks, terminated by done', () => {
+ const types = commandcodeMessagesToEvents(LINES).map((e) => e.type)
+ expect(types.filter((t) => t === 'user_message')).toHaveLength(2)
+ expect(types).toContain('tool_start')
+ expect(types).toContain('tool_end')
+ expect(types.at(-1)).toBe('done')
+ })
+
+ it('lastCommandCodeTurnText returns the last prompt + the assistant text that followed', () => {
+ expect(lastCommandCodeTurnText(LINES)).toEqual({
+ userMessage: 'list the files',
+ assistantText: 'a.txt and b.txt',
+ })
+ })
+
+ it('commandCodeSessionMeta reads the id + cwd from the header', () => {
+ expect(commandCodeSessionMeta(LINES)).toEqual({ id: '34e1385f-c18a-4f54-bf12-f8f57e151a3d', cwd: '/tmp/cc-probe' })
+ })
+
+ it('windowCommandCodeLines snaps back to a real user prompt (never a tool_result row)', () => {
+ const w = windowCommandCodeLines(LINES, { limit: 2 })
+ expect(JSON.parse(w.window[0]).message.meta.source).toBe('user')
+ expect(w.hasMore).toBe(true)
+ expect(w.oldestCursor).toBe('commandcode:3')
+ })
+
+ it('windowCommandCodeLines flags a malformed cursor as stale', () => {
+ expect(windowCommandCodeLines(LINES, { limit: 2, before: 'nope' }).staleCursor).toBe(true)
+ })
+})
+
+// Both records are copied verbatim from real failed sessions on this computer — the only two source-less
+// rows across 96 captured message records. Command Code writes them when a turn dies (`run_error`) and
+// fires no Stop hook for it, so they are the sole end-of-turn signal.
+const RUN_ERROR = '{"type":"message","id":"9a87ff6f","parentId":"6e6c9931","timestamp":"t7","message":'
+ + '{"role":"user","content":[{"type":"text","text":"Error: 500 [object Object]\\n\\nType \\"continue\\" to try again.'
+ + ' If the issue persists, contact support: https://commandcode.ai/discord\\nTrace ID: 932a62f1e3c8102bf09baf00c08d81a7"}],'
+ + '"meta":{"messageId":"4b13beb7-bcac-4fcf-8261-61ac32a45441"}}}'
+const OUT_OF_CREDITS = '{"type":"message","id":"1c0dd0a1","parentId":null,"timestamp":"t2","message":'
+ + '{"role":"user","content":[{"type":"text","text":"Insufficient credits"}],"meta":{"messageId":"5dafb0e0"}}}'
+
+describe('Command Code normalizer — run-error records', () => {
+ it('detects a source-less user row and leaves genuine records alone', () => {
+ expect(commandCodeRunError(RUN_ERROR)).toMatch(/^Error: 500 \[object Object]/)
+ expect(commandCodeRunError(OUT_OF_CREDITS)).toBe('Insufficient credits')
+ expect(commandCodeRunError(LINES[1])).toBeNull() // a real prompt (meta.source === 'user')
+ expect(commandCodeRunError(LINES[5])).toBeNull() // a tool_result carrier (meta.source === 'tool')
+ expect(commandCodeRunError(HEADER)).toBeNull()
+ })
+
+ it('closes the running turn instead of opening a phantom one', () => {
+ // The exact shape that hung the web: a prompt, then tool work, then the run error and nothing else.
+ const { normalizer, events } = live([...LINES.slice(0, 6), RUN_ERROR])
+ const lifecycle = events.filter((e) => e.type === 'turn_started' || e.type === 'turn_ended')
+
+ expect(lifecycle.map((e) => e.type)).toEqual(['turn_started', 'turn_ended', 'turn_started', 'turn_ended'])
+ // Reshaped as a prompt it would have been a THIRD turn_started, with its text as the user message.
+ expect(lifecycle.filter((e) => e.type === 'turn_started')
+ .map((e) => (e as { payload: { userMessage: string } }).payload.userMessage))
+ .toEqual(['hi', 'list the files'])
+ expect(normalizer.turnOpen).toBe(false)
+ })
+
+ it('is inert when no turn is open', () => {
+ const { normalizer, events } = live([HEADER, RUN_ERROR])
+ expect(events).toEqual([])
+ expect(normalizer.turnOpen).toBe(false)
+ })
+
+ it('stays out of the replay and recap paths', () => {
+ const lines = [...LINES, RUN_ERROR]
+ expect(reshapeLine(RUN_ERROR)).toBeNull()
+ // No extra user bubble on replay…
+ expect(commandcodeMessagesToEvents(lines).filter((e) => e.type === 'user_message')).toHaveLength(2)
+ // …and the recap still summarizes the real turn rather than the error text.
+ expect(lastCommandCodeTurnText(lines)).toEqual({
+ userMessage: 'list the files',
+ assistantText: 'a.txt and b.txt',
+ })
+ })
+
+ it('summarizes to the first line for the device, dropping the support URL and trace id', () => {
+ expect(commandCodeRunErrorSummary(commandCodeRunError(RUN_ERROR)!)).toBe('Error: 500 [object Object]')
+ expect(commandCodeRunErrorSummary('Insufficient credits')).toBe('Insufficient credits')
+ })
+})
diff --git a/cli/src/engines/commandcode/normalizer.ts b/cli/src/engines/commandcode/normalizer.ts
new file mode 100644
index 000000000..8532eae33
--- /dev/null
+++ b/cli/src/engines/commandcode/normalizer.ts
@@ -0,0 +1,290 @@
+/**
+ * Command Code (commandcode.ai) JSONL → shared event vocabulary.
+ *
+ * Command Code writes an append-only JSONL per session at
+ * `<COMMANDCODE_HOME>/projects/<cwd-slug>/<session-uuid>.jsonl`, so it reuses the byte-offset tail
+ * (`Watcher`) like claude/codex/pi — no custom reader.
+ *
+ * The happy accident (verified against real captured sessions, commandcode 1.4.4): its **content blocks
+ * are byte-for-byte Claude's**, wrapped in Pi's envelope:
+ *
+ * line 1 {"type":"session","version":3,"id":"<uuid>","timestamp":"…","cwd":"/abs/path"}
+ * then {"type":"message","id":"<8hex>","parentId":null|"<8hex>","timestamp":"…",
+ * "message":{"role":…,"content":[…],"meta":{"source":"user"|"model"|"tool",…}}}
+ *
+ * content parts: {"type":"thinking","thinking":…,"signature":…}
+ * {"type":"text","text":…}
+ * {"type":"tool_use","id":"call_…","name":"shell_command","input":{…}}
+ * {"type":"tool_result","tool_use_id":"call_…","content":[{"type":"text","text":…}]}
+ *
+ * So instead of re-implementing a normalizer we **reshape each line into the Claude raw shape** and hand
+ * it to the existing, battle-tested `lineToEvents`/`messagesToEvents` (`src/lib/normalize.ts`) — which
+ * already do thinking ids, tool-name tracking, `tool_result`→`tool_end` joining, truncation and tool
+ * summaries.
+ *
+ * Three Command Code specifics the reshape encodes:
+ * - **`message.meta.source`** (`user` | `model` | `tool`) is an explicit role discriminator — better than
+ * Claude's sniffing. A `tool` row is a `role:"user"` message carrying only `tool_result` blocks.
+ * - **There is no `stop_reason`.** A turn continues while the assistant is calling tools, so we synthesize
+ * `'tool_use'` when the message contains a `tool_use` block and `'end_turn'` otherwise — exactly the
+ * values Claude's `TERMINAL_STOP_REASONS` already discriminates on.
+ * - **A failed turn appends a source-LESS user row** — see `commandCodeRunError`.
+ */
+
+import type { EngineNormalizer } from '../types.js'
+import {
+ lastTurnTextFromRawLines,
+ lineToEvents,
+ messagesToEvents,
+ newTurnState,
+ type LastTurnText,
+ type LiveEvent,
+ type SessionEvent,
+ type TurnState,
+} from '../../lib/normalize.js'
+
+type JsonObject = Record<string, unknown>
+
+/** Command Code tool ids → the vocabulary the web/device cards render. */
+const TOOL_NAMES: Record<string, string> = {
+ shell_command: 'Bash',
+ bash_output: 'Bash',
+ read_file: 'Read',
+ read_multiple_files: 'Read',
+ read_directory: 'LS',
+ write_file: 'Write',
+ edit_file: 'Edit',
+ glob: 'Glob',
+ grep: 'Grep',
+ web_search: 'WebSearch',
+ web_fetch: 'WebFetch',
+ todo_write: 'TodoWrite',
+ agent: 'Task',
+ agent_output: 'Task',
+ activate_skill: 'Task',
+}
+
+export function commandCodeToolName(name: string): string {
+ const key = (name || '').toLowerCase()
+ if (TOOL_NAMES[key]) return TOOL_NAMES[key]
+ if (!name) return 'tool'
+ // snake_case → TitleCase so an unmapped/new tool still reads well on a card.
+ return name.split('_').filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join('')
+}
+
+function object(value: unknown): JsonObject | null {
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value as JsonObject : null
+}
+
+function str(value: unknown): string {
+ return typeof value === 'string' ? value : ''
+}
+
+function parse(line: string): JsonObject | null {
+ try { return object(JSON.parse(line)) } catch { return null }
+}
+
+/** Rewrite `tool_use.name` in place (on a copy) so downstream tool cards use the shared vocabulary. */
+function mapParts(content: unknown): unknown[] {
+ if (!Array.isArray(content)) return []
+ return content.map((part) => {
+ const p = object(part)
+ if (!p || p.type !== 'tool_use') return part
+ return { ...p, name: commandCodeToolName(str(p.name)) }
+ })
+}
+
+/**
+ * The failure text of a Command Code **run-error** record, or null for anything else.
+ *
+ * When a turn dies (`stopReason === 'run_error'`) the TUI appends the error as a `role:"user"` message
+ * carrying only `meta.messageId` — **no `meta.source`** — so that typing "continue" replays it to the
+ * model. It is feedback, NOT a prompt, and it is the ONLY record Command Code writes without a source
+ * (verified in commandcode 1.5.0: `buildRunErrorFeedbackContent` feeds the bundle's single
+ * `appendMessage({message:{role:"user",…,meta:{messageId}}})` call site; and across every transcript
+ * captured on this computer — 96 records — the only two source-less rows were `Error: 500 [object Object]`
+ * and `Insufficient credits`).
+ *
+ * Reshaping it as a prompt is what left the web spinning forever: it closed the real turn and opened a
+ * phantom one that nothing could ever close. Nothing else can close it either — Command Code's hook set
+ * is exactly `PreToolUse|PostToolUse|Stop|SessionStart`, with no `StopFailure`, and it fires **no** `Stop`
+ * for a failed turn (audit log: Stop for all three successful turns, none for the errored one). So this
+ * record is the only end-of-turn signal that exists, and the reader must act on it.
+ */
+export function commandCodeRunError(line: string): string | null {
+ const raw = parse(line)
+ if (!raw || str(raw.type) !== 'message') return null
+ const message = object(raw.message)
+ return message ? runErrorText(message) : null
+}
+
+function runErrorText(message: JsonObject): string | null {
+ if (str(message.role) !== 'user') return null
+ if (str(object(message.meta)?.source)) return null // a real prompt or a tool_result carrier
+ const content = Array.isArray(message.content) ? message.content : []
+ // Defensive: a source-less row carrying tool output is not a notice — leave it on the normal path.
+ if (content.some((part) => object(part)?.type === 'tool_result')) return null
+ const text = content
+ .map((part) => (object(part)?.type === 'text' ? str(object(part)?.text) : ''))
+ .filter(Boolean)
+ .join('\n')
+ .trim()
+ return text || null
+}
+
+/**
+ * Device-sized version of a run error: its first line. Command Code appends a support URL and a trace id
+ * ("Type \"continue\" to try again. … Trace ID: 932a…") that are noise on a 1.9" screen, while the first
+ * line is always the error itself (`Error: 500 [object Object]`, `Insufficient credits`).
+ */
+export function commandCodeRunErrorSummary(text: string): string {
+ return text.split('\n').map((line) => line.trim()).find(Boolean) ?? text.trim()
+}
+
+/**
+ * One Command Code line → one Claude-shaped raw line (or null for the header / unknown entries).
+ * Exported for tests; the normalizer and the replay/recap helpers all funnel through it.
+ */
+export function reshapeLine(line: string): string | null {
+ const raw = parse(line)
+ if (!raw || str(raw.type) !== 'message') return null // session header, and any future entry type
+ const message = object(raw.message)
+ if (!message) return null
+ // Keep the run-error record out of the render path entirely: as a prompt it would open a phantom turn
+ // live, show up as a user bubble on replay, and become the recap's "ask". The turn close it implies is
+ // derived in `ingest` (live) — replay/recap only need it gone.
+ if (runErrorText(message) !== null) return null
+
+ const source = str(object(message.meta)?.source)
+ const role = str(message.role)
+ const content = mapParts(message.content)
+ const common = { uuid: raw.id, parentUuid: raw.parentId, timestamp: raw.timestamp }
+
+ // `tool` rows are role:"user" messages carrying tool_result blocks — Claude's path turns those into
+ // tool_end and never mistakes them for a prompt.
+ if (source === 'user' || source === 'tool' || role === 'user') {
+ return JSON.stringify({ ...common, type: 'user', message: { role: 'user', content } })
+ }
+ if (source === 'model' || role === 'assistant') {
+ const hasToolUse = content.some((part) => object(part)?.type === 'tool_use')
+ return JSON.stringify({
+ ...common,
+ type: 'assistant',
+ message: { role: 'assistant', content, stop_reason: hasToolUse ? 'tool_use' : 'end_turn' },
+ })
+ }
+ return null
+}
+
+function reshapeAll(rawLines: string[]): string[] {
+ const out: string[] = []
+ for (const line of rawLines) {
+ const reshaped = reshapeLine(line)
+ if (reshaped) out.push(reshaped)
+ }
+ return out
+}
+
+export class CommandCodeNormalizer implements EngineNormalizer {
+ private readonly state: TurnState = newTurnState()
+
+ constructor(private readonly mode: 'live' | 'replay' = 'live') {}
+
+ get turnOpen(): boolean { return this.state.turnOpen }
+
+ closeTurn(): void { this.state.turnOpen = false; this.state.pendingTools.clear() }
+
+ /**
+ * Open a turn from OUTSIDE the transcript, driven by the PreToolUse hook.
+ *
+ * Every other engine opens its turn from a live signal — a prompt-submit hook, or a user line landing
+ * in the transcript while the turn runs. Command Code has neither: it has no UserPromptSubmit, and it
+ * flushes the whole turn to the JSONL at the end (the user and assistant lines share a timestamp). So
+ * by the time anything is readable the turn is already over, and the device went idle → recap with no
+ * "working" in between.
+ *
+ * Idempotent because PreToolUse fires per tool call: only the first one in a turn opens it. The user
+ * text is not available yet — the transcript has not been written — so the ask arrives later with the
+ * recap, which is where the device reads it from anyway.
+ */
+ openTurn(): LiveEvent[] {
+ if (this.state.turnOpen) return []
+ this.state.turnOpen = true
+ this.state.pendingTools.clear()
+ return [{ type: 'turn_started', payload: { userMessage: '' } }]
+ }
+
+ ingest(line: string): LiveEvent[] {
+ // A run error ends the turn — it is the only signal there is (see `commandCodeRunError`). Emitting
+ // turn_ended here also heals on attach: a daemon restarting onto an already-failed session folds this
+ // record during hydration and comes up with the turn closed instead of stuck.
+ if (commandCodeRunError(line) !== null) {
+ if (!this.state.turnOpen) return []
+ this.closeTurn()
+ return [{ type: 'turn_ended', payload: {} }]
+ }
+ const reshaped = reshapeLine(line)
+ return reshaped ? lineToEvents(reshaped, this.state) : []
+ }
+
+ finishReplay(): LiveEvent[] {
+ return this.mode === 'replay' ? [{ type: 'done', payload: { result: 'success' } }] : []
+ }
+}
+
+/** Full-session replay (session_get) — same render path as the live stream. */
+export function commandcodeMessagesToEvents(rawLines: string[]): SessionEvent[] {
+ return messagesToEvents(reshapeAll(rawLines))
+}
+
+/** Last user prompt + the assistant text that followed it — the recap source of truth. */
+export function lastCommandCodeTurnText(rawLines: string[]): LastTurnText | null {
+ return lastTurnTextFromRawLines(reshapeAll(rawLines))
+}
+
+/** Session id + cwd from the header line. */
+export function commandCodeSessionMeta(rawLines: string[]): { id: string; cwd: string } | null {
+ for (const line of rawLines) {
+ const raw = parse(line)
+ if (!raw || str(raw.type) !== 'session') continue
+ const id = str(raw.id)
+ if (id) return { id, cwd: str(raw.cwd) }
+ }
+ return null
+}
+
+/** True for a line that starts a turn (a real user prompt, not a tool_result carrier). */
+function isUserPromptLine(line: string): boolean {
+ const raw = parse(line)
+ if (!raw || str(raw.type) !== 'message') return false
+ const message = object(raw.message)
+ if (!message) return false
+ return str(object(message.meta)?.source) === 'user'
+}
+
+/**
+ * Turn-snapped pagination window for `session_get {limit, before}`; cursor `commandcode:<lineIndex>`.
+ * The window start snaps back to a user prompt so a turn is never split (replay is stateful: a
+ * tool_use's name must still be known when its tool_result renders).
+ */
+export function windowCommandCodeLines(
+ rawLines: string[],
+ opts: { limit: number; before?: string },
+): { window: string[]; hasMore: boolean; oldestCursor: string | null; staleCursor?: boolean } {
+ let endIndex = rawLines.length
+ if (opts.before) {
+ const match = /^commandcode:(\d+)$/.exec(opts.before)
+ if (!match) return { window: [], hasMore: false, oldestCursor: null, staleCursor: true }
+ endIndex = Number(match[1])
+ if (!Number.isSafeInteger(endIndex) || endIndex < 0 || endIndex > rawLines.length) {
+ return { window: [], hasMore: false, oldestCursor: null, staleCursor: true }
+ }
+ }
+ let start = Math.max(0, endIndex - opts.limit)
+ while (start > 0 && !isUserPromptLine(rawLines[start])) start--
+ return {
+ window: rawLines.slice(start, endIndex),
+ hasMore: start > 0,
+ oldestCursor: `commandcode:${start}`,
+ }
+}
diff --git a/cli/src/engines/commandcode/runtimeProfile.spec.ts b/cli/src/engines/commandcode/runtimeProfile.spec.ts
new file mode 100644
index 000000000..584ed5595
--- /dev/null
+++ b/cli/src/engines/commandcode/runtimeProfile.spec.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from 'vitest'
+import {
+ commandcodeBannerModel,
+ commandcodeEffortRefusal,
+ countCommandcodeRefusals,
+ parseCommandcodeModelsOutput,
+} from './runtimeProfile.js'
+
+// Verbatim from `commandcode --list-models` (Command Code 1.6.0): the counter line, two sections, the
+// `(default)` marker, and the two id shapes — vendor-prefixed and bare.
+const OUTPUT = [
+ 'Available models · 50 models',
+ '',
+ 'Open Source',
+ '',
+ 'deepseek/deepseek-v4-pro hybrid-attention long-context reasoning',
+ 'deepseek/deepseek-v4-flash fast hybrid-attention reasoning (default)',
+ 'moonshotai/kimi-k2.7-code-highspeed high-speed long-horizon coding with vision',
+ '',
+ 'Anthropic',
+ '',
+ 'claude-sonnet-5 best combo of speed & intelligence (recommended)',
+ 'claude-haiku-4-5 fastest & most compact, great for quick tasks',
+].join('\n')
+
+describe('command code model catalog', () => {
+ it('reads ids and sections, and keeps the short name the device labels by', () => {
+ const targets = parseCommandcodeModelsOutput(OUTPUT)
+
+ expect(targets.map((t) => `${t.section}:${t.shortId}`)).toEqual([
+ 'Open Source:deepseek-v4-pro',
+ 'Open Source:deepseek-v4-flash',
+ 'Open Source:kimi-k2.7-code-highspeed',
+ 'Anthropic:claude-sonnet-5',
+ 'Anthropic:claude-haiku-4-5',
+ ])
+ // `/model` needs the full id back — the short form is only what the profile and the chip carry.
+ expect(targets[2].id).toBe('moonshotai/kimi-k2.7-code-highspeed')
+ // A bare id is its own short form.
+ expect(targets[3]).toMatchObject({ id: 'claude-sonnet-5', shortId: 'claude-sonnet-5' })
+ expect(targets.filter((t) => t.isDefault).map((t) => t.id)).toEqual(['deepseek/deepseek-v4-flash'])
+ })
+
+ it('ignores the counter line and never mistakes a heading for a model', () => {
+ expect(parseCommandcodeModelsOutput('Available models · 50 models')).toEqual([])
+ expect(parseCommandcodeModelsOutput('Open Source\n\nAnthropic\n')).toEqual([])
+ })
+
+ it('reads the words Command Code refuses an unsupported effort with', () => {
+ expect(commandcodeEffortRefusal('◼ Reasoning effort not supported for Kimi K2.6.'))
+ .toBe('Reasoning effort not supported for Kimi K2.6')
+ expect(commandcodeEffortRefusal('❯ Ask your question...')).toBeNull()
+ })
+
+ it('counts refusals so an older one cannot be read as this command being refused', () => {
+ const pane = [
+ '◼ Reasoning effort not supported for Kimi K2.6.',
+ '❯ /effort high',
+ '◼ Reasoning effort not supported for Kimi K2.6.',
+ ].join('\n')
+ expect(countCommandcodeRefusals(pane)).toBe(2)
+ expect(countCommandcodeRefusals('❯ Ask your question...')).toBe(0)
+ })
+
+ it('reads the running model out of the session banner', () => {
+ const banner = [
+ '# Command Code v1.6.0',
+ '# models: kimi-k2.6 · taste-1',
+ '# /private/tmp/rp2/cc',
+ ].join('\n')
+
+ expect(commandcodeBannerModel(banner)).toBe('kimi-k2.6')
+ expect(commandcodeBannerModel('# Command Code v1.6.0')).toBeNull()
+ })
+})
diff --git a/cli/src/engines/commandcode/runtimeProfile.ts b/cli/src/engines/commandcode/runtimeProfile.ts
new file mode 100644
index 000000000..fcb9f927d
--- /dev/null
+++ b/cli/src/engines/commandcode/runtimeProfile.ts
@@ -0,0 +1,115 @@
+/**
+ * Command Code model catalog + reasoning effort → runtime-profile options.
+ *
+ * Switching Command Code from the device was built and REVERTED once (owner call, 2026-07-30) because
+ * v1.4/1.5 offered no way to do it safely: the `/model` dialog ignored printable characters, so the only
+ * route was arrow-driving a 49-row picker, and opening it mid-turn wedged the CLI. **v1.6.0 removes both
+ * obstacles**, which is why this exists again — verified by hand on 1.6.0 before a line was written:
+ *
+ * commandcode --list-models → the whole catalog on stdout (50 models), no picker involved
+ * /model moonshotai/kimi-k2.6 → applied; config.json flipped to "moonshotai/Kimi-K2.6"
+ * /effort high → applied, or refused in words:
+ * "◼ Reasoning effort not supported for Kimi K2.6."
+ *
+ * So both axes are single commands with an argument, exactly like devin's — no picker is ever opened and
+ * nothing has to be driven blind.
+ *
+ * Catalog shape:
+ *
+ * Available models · 50 models
+ *
+ * Open Source
+ *
+ * deepseek/deepseek-v4-flash fast hybrid-attention reasoning (default)
+ * moonshotai/kimi-k3 long-horizon coding & knowledge work with 1M context
+ *
+ * Anthropic
+ *
+ * claude-sonnet-5 best combo of speed & intelligence (recommended)
+ *
+ * Note the id may or may not carry a vendor prefix. The PROFILE stores the short name (the part after the
+ * last `/`) because the device labels a model by splitting on `-`/`_` and never on `/`, and because that
+ * is what `ingestCommandcode` already observes from the transcript. `/model` needs the full id back, so
+ * the mapping is kept per session (see commandcodeTarget).
+ */
+
+/**
+ * Levels offered per model. Command Code does not publish which models take which — `--list-models` says
+ * nothing, and the per-model set really does differ (DeepSeek V4 Flash offers Default/high/max, Kimi K2.6
+ * offers none). Offering the union and letting the CLI answer in words is the honest trade: a wrong pick
+ * fails fast and explicitly instead of being silently ignored.
+ */
+export const COMMANDCODE_EFFORTS = new Set(['auto', 'low', 'medium', 'high', 'max'])
+export const COMMANDCODE_EFFORT_LEVELS = ['low', 'medium', 'high', 'max'] as const
+
+export interface CommandcodeModelTarget {
+ /** Full id as `--list-models` prints it — the argument for `/model`. */
+ id: string
+ /** Id after the last `/` — what the profile stores and the device labels. */
+ shortId: string
+ /** Section heading it appeared under ("Open Source", "Anthropic", …). */
+ section: string
+ isDefault: boolean
+}
+
+const ROW_RE = /^(\S+)\s{2,}(.+?)\s*$/
+const HEADER_RE = /^Available models\b/i
+
+/** Parse `commandcode --list-models`. Section headings and the counter line are not models. */
+export function parseCommandcodeModelsOutput(output: string): CommandcodeModelTarget[] {
+ const targets: CommandcodeModelTarget[] = []
+ const seen = new Set<string>()
+ let section = ''
+ for (const rawLine of output.split('\n')) {
+ const line = rawLine.replace(/\s+$/, '')
+ if (!line.trim() || HEADER_RE.test(line)) continue
+ const row = ROW_RE.exec(line)
+ if (!row) {
+ // A lone left-aligned phrase is a section heading; a model row always has a description column.
+ section = line.trim()
+ continue
+ }
+ const id = row[1]
+ if (!/^[a-z0-9][\w.-]*(?:\/[\w.-]+)*$/i.test(id) || seen.has(id)) continue
+ seen.add(id)
+ targets.push({
+ id,
+ shortId: id.slice(id.lastIndexOf('/') + 1),
+ section,
+ isDefault: /\(default\)\s*$/.test(row[2]),
+ })
+ }
+ return targets
+}
+
+/**
+ * What Command Code printed in answer to `/effort <level>`. It refuses in words rather than silently, so
+ * an unsupported level is reported as such instead of timing out.
+ */
+export function commandcodeEffortRefusal(capture: string): string | null {
+ // Stop at the line end, not at the first `.` — model names carry dots ("Kimi K2.6"), and cutting there
+ // truncated the message mid-name.
+ const match = /◼?\s*(Reasoning effort not supported for .*)$/im.exec(capture)
+ return match ? match[1].trim().replace(/\.$/, '') : null
+}
+
+/**
+ * How many effort refusals a capture holds. A tmux capture carries scrollback, so "is there a refusal?"
+ * answers yes off an old one; only an increase means THIS command was refused.
+ */
+export function countCommandcodeRefusals(capture: string): number {
+ return capture.split('\n').filter((line) => commandcodeEffortRefusal(line) !== null).length
+}
+
+/**
+ * The models line Command Code prints in its session banner (`# models: kimi-k2.6 · taste-1`). It names
+ * the running model in SHORT form, which is the same form the profile stores.
+ */
+export function commandcodeBannerModel(capture: string): string | null {
+ const lines = capture.split('\n')
+ for (let i = lines.length - 1; i >= 0; i--) {
+ const match = /^#\s*models:\s*([^\s·]+)/.exec(lines[i].trim())
+ if (match) return match[1]
+ }
+ return null
+}
diff --git a/cli/src/engines/commandcode/transcript.spec.ts b/cli/src/engines/commandcode/transcript.spec.ts
new file mode 100644
index 000000000..4c2ec8087
--- /dev/null
+++ b/cli/src/engines/commandcode/transcript.spec.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest'
+import { commandcodeProjectSlug, commandcodeTranscriptPath } from './transcript.js'
+
+describe('the Command Code transcript layout', () => {
+ it('slugs a working directory the way the CLI does', () => {
+ // Both taken off a real machine: the directory names next to their session's cwd.
+ expect(commandcodeProjectSlug('/Users/example/Working/Tmux/Agent-6'))
+ .toBe('users-example-working-tmux-agent-6')
+ // A dotted segment collapses INTO the dash before it — "/.harness/" is one separator run, not two.
+ expect(commandcodeProjectSlug('/Users/example/.harness/cli/data/summary-scratch'))
+ .toBe('users-example-harness-cli-data-summary-scratch')
+ })
+
+ it('builds the transcript path from cwd and session id', () => {
+ const path = commandcodeTranscriptPath('/Users/me/Work/App', 'ae93cc89-0dff-452a-a875-33b1516bbc80')
+ expect(path).toMatch(/\/projects\/users-me-work-app\/ae93cc89-0dff-452a-a875-33b1516bbc80\.jsonl$/)
+ })
+
+ it('refuses a session id that could escape the projects root', () => {
+ // The id becomes a filename. A malformed hook payload must not be able to point the watcher at, say,
+ // a file outside COMMANDCODE_HOME.
+ expect(commandcodeTranscriptPath('/Users/me/Work/App', '../../../etc/passwd')).toBeNull()
+ expect(commandcodeTranscriptPath('/Users/me/Work/App', 'a/b')).toBeNull()
+ expect(commandcodeTranscriptPath('/Users/me/Work/App', '..')).toBeNull()
+ })
+
+ it('returns null when there is nothing to build from', () => {
+ expect(commandcodeTranscriptPath('', 'abc')).toBeNull()
+ expect(commandcodeTranscriptPath(null, 'abc')).toBeNull()
+ expect(commandcodeTranscriptPath('/Users/me/Work/App', '')).toBeNull()
+ expect(commandcodeTranscriptPath('///', 'abc')).toBeNull() // slug collapses to nothing
+ })
+})
diff --git a/cli/src/engines/commandcode/transcript.ts b/cli/src/engines/commandcode/transcript.ts
new file mode 100644
index 000000000..9c4470e63
--- /dev/null
+++ b/cli/src/engines/commandcode/transcript.ts
@@ -0,0 +1,32 @@
+import { join } from 'path'
+import { env } from '../../config/env.js'
+
+/**
+ * Command Code lays its transcripts out deterministically:
+ *
+ * <COMMANDCODE_HOME>/projects/<cwd slug>/<sessionId>.jsonl
+ *
+ * where the slug is the working directory lowercased with every run of non-alphanumerics collapsed to a
+ * dash ("/Users/me/Working/Tmux/Agent-6" → "users-me-working-tmux-agent-6", and "/Users/me/.harness/cli"
+ * → "users-me-machine-cli").
+ *
+ * Deriving it matters because the CLI fires SessionStart BEFORE the file exists, and a path that is not on
+ * disk fails the registry's realpath check — so the path used to arrive only with the first Stop hook, i.e.
+ * AFTER the first turn. Nothing tailed the transcript for that turn, which is the only signal Command Code
+ * has that a message was accepted, so the first message of every new session reported "the agent did not
+ * accept this message" and produced no recap.
+ */
+export function commandcodeProjectSlug(cwd: string): string {
+ return cwd.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')
+}
+
+/** null when there is not enough to build a path, or when either part could escape the projects root. */
+export function commandcodeTranscriptPath(cwd: string | null | undefined, sessionId: string): string | null {
+ if (!cwd || !sessionId) return null
+ // The session id becomes a FILENAME, so anything that could climb out of the directory disqualifies it.
+ // Command Code uses uuids; this is here so a malformed hook payload cannot point the watcher elsewhere.
+ if (!/^[A-Za-z0-9._-]+$/.test(sessionId) || sessionId === '.' || sessionId === '..') return null
+ const slug = commandcodeProjectSlug(cwd)
+ if (!slug) return null
+ return join(env.COMMANDCODE_HOME, 'projects', slug, `${sessionId}.jsonl`)
+}
diff --git a/cli/src/engines/cursor/discovery.ts b/cli/src/engines/cursor/discovery.ts
new file mode 100644
index 000000000..d50734d55
--- /dev/null
+++ b/cli/src/engines/cursor/discovery.ts
@@ -0,0 +1,74 @@
+import { mkdir, readdir } from 'node:fs/promises'
+import { join } from 'node:path'
+import chokidar, { type FSWatcher } from 'chokidar'
+import { validTranscriptPath } from '../../lib/registry.js'
+
+const SESSION_RE = /^[0-9a-f-]{16,}$/i
+
+export class CursorTranscriptDiscovery {
+ private watcher: FSWatcher | null = null
+ private readonly pending = new Set<string>()
+
+ constructor(
+ private readonly cursorHome: string,
+ private readonly onFound: (sessionId: string, transcriptPath: string) => void,
+ ) {}
+
+ async start(): Promise<void> {
+ if (this.watcher) return
+ const root = join(this.cursorHome, 'projects')
+ await mkdir(root, { recursive: true })
+ this.watcher = chokidar.watch(root, {
+ ignoreInitial: false,
+ depth: 5,
+ // Cursor also places Unix sockets below project roots. Watching those can fail on macOS and
+ // is unnecessary: discovery consumes only transcript JSONL files.
+ ignored: (path, info) => Boolean(info && !info.isDirectory() && !path.endsWith('.jsonl')),
+ })
+ this.watcher
+ .on('add', (path: string) => this.inspect(path))
+ .on('change', (path: string) => this.inspect(path))
+ .on('error', (err: unknown) => console.error('[cursor-discovery] watcher error:', err))
+ }
+
+ async add(sessionId: string): Promise<void> {
+ if (!SESSION_RE.test(sessionId)) return
+ const found = await findCursorTranscript(this.cursorHome, sessionId)
+ if (found) {
+ this.onFound(sessionId, found)
+ return
+ }
+ this.pending.add(sessionId)
+ }
+
+ remove(sessionId: string): void {
+ this.pending.delete(sessionId)
+ }
+
+ async stop(): Promise<void> {
+ this.pending.clear()
+ await this.watcher?.close()
+ this.watcher = null
+ }
+
+ private inspect(path: string): void {
+ const normalized = path.replace(/\\/g, '/')
+ const match = /\/agent-transcripts\/([^/]+)\/\1\.jsonl$/.exec(normalized)
+ const sessionId = match?.[1]
+ if (!sessionId || !this.pending.has(sessionId) || !validTranscriptPath('cursor', path)) return
+ this.pending.delete(sessionId)
+ this.onFound(sessionId, path)
+ }
+}
+
+export async function findCursorTranscript(cursorHome: string, sessionId: string): Promise<string | null> {
+ if (!SESSION_RE.test(sessionId)) return null
+ const root = join(cursorHome, 'projects')
+ let projects: string[]
+ try { projects = await readdir(root) } catch { return null }
+ for (const project of projects) {
+ const candidate = join(root, project, 'agent-transcripts', sessionId, `${sessionId}.jsonl`)
+ if (validTranscriptPath('cursor', candidate)) return candidate
+ }
+ return null
+}
diff --git a/cli/src/engines/cursor/localE2e.spec.ts b/cli/src/engines/cursor/localE2e.spec.ts
new file mode 100644
index 000000000..3b2907fb3
--- /dev/null
+++ b/cli/src/engines/cursor/localE2e.spec.ts
@@ -0,0 +1,312 @@
+import { execFile, spawn, type ChildProcess } from 'node:child_process'
+import { once } from 'node:events'
+import { existsSync } from 'node:fs'
+import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
+import { createServer } from 'node:net'
+import { homedir, tmpdir } from 'node:os'
+import { dirname, join, resolve } from 'node:path'
+import { promisify } from 'node:util'
+import { WebSocket, WebSocketServer } from 'ws'
+import { describe, expect, it } from 'vitest'
+import { cursorMessagesToEvents } from './normalizer.js'
+import { loadCursorReplayTaskLinks } from './subagent.js'
+
+const runCursorE2e = process.env.RUN_CURSOR_E2E === '1'
+const execFileAsync = promisify(execFile)
+const adapterRoot = resolve(import.meta.dirname, '../../..')
+const repoRoot = adapterRoot // this package IS the repo root here
+const cursorHome = join(homedir(), '.cursor')
+const cursorHooksPath = join(cursorHome, 'hooks.json')
+const hookScript = join(adapterRoot, 'hook', 'notify.mjs')
+const tsxBin = join(adapterRoot, 'node_modules', '.bin', 'tsx')
+const E2E_TIMEOUT_MS = 4 * 60_000
+
+interface Envelope {
+ t?: string
+ frame?: {
+ type?: string
+ payload?: Record<string, unknown>
+ }
+}
+
+interface RegistryEntry {
+ id?: string
+ sessionId?: string
+ engine?: string
+ transcriptPath?: string | null
+ tmuxPane?: string
+}
+
+function shellQuote(value: string): string {
+ return `'${value.replace(/'/g, `'\\''`)}'`
+}
+
+async function freePort(): Promise<number> {
+ const server = createServer()
+ server.listen(0, '127.0.0.1')
+ await once(server, 'listening')
+ const address = server.address()
+ if (!address || typeof address === 'string') throw new Error('could not allocate a local port')
+ await new Promise<void>((resolveClose, reject) =>
+ server.close((error) => error ? reject(error) : resolveClose()))
+ return address.port
+}
+
+async function waitUntil<T>(
+ label: string,
+ read: () => T | Promise<T>,
+ accept: (value: T) => boolean,
+ timeoutMs = 30_000,
+): Promise<T> {
+ const deadline = Date.now() + timeoutMs
+ let last: T
+ do {
+ last = await read()
+ if (accept(last)) return last
+ await new Promise((resolveWait) => setTimeout(resolveWait, 200))
+ } while (Date.now() < deadline)
+ throw new Error(`timed out waiting for ${label}; latest=${JSON.stringify(last!)}`)
+}
+
+async function stopChild(child: ChildProcess): Promise<void> {
+ if (child.exitCode !== null || child.signalCode !== null) return
+ child.kill('SIGTERM')
+ const exited = once(child, 'exit').then(() => true)
+ const graceful = await Promise.race([
+ exited,
+ new Promise<false>((resolveWait) => setTimeout(() => resolveWait(false), 5_000)),
+ ])
+ if (!graceful && child.exitCode === null && child.signalCode === null) {
+ child.kill('SIGKILL')
+ await once(child, 'exit').catch(() => undefined)
+ }
+}
+
+async function installTemporaryCursorHooks(port: number, dataDir: string): Promise<void> {
+ let settings: Record<string, unknown> = {}
+ if (existsSync(cursorHooksPath)) {
+ settings = JSON.parse(await readFile(cursorHooksPath, 'utf8')) as Record<string, unknown>
+ }
+ const hooks = settings.hooks && typeof settings.hooks === 'object' && !Array.isArray(settings.hooks)
+ ? settings.hooks as Record<string, unknown>
+ : {}
+ const command = [
+ 'node',
+ shellQuote(hookScript),
+ '--port', String(port),
+ '--data-dir', shellQuote(dataDir),
+ '--claude-projects-dir', shellQuote(join(dataDir, 'claude-projects')),
+ '--codex-home', shellQuote(join(dataDir, 'codex')),
+ '--cursor-home', shellQuote(cursorHome),
+ '--engine', 'cursor',
+ ].join(' ')
+ for (const event of ['sessionStart', 'beforeSubmitPrompt', 'preToolUse', 'stop', 'sessionEnd']) {
+ const current = Array.isArray(hooks[event]) ? hooks[event] as Array<Record<string, unknown>> : []
+ hooks[event] = [
+ ...current.filter((entry) => typeof entry.command !== 'string' || !entry.command.includes('notify.mjs')),
+ { command, failClosed: false },
+ ]
+ }
+ settings = { ...settings, version: typeof settings.version === 'number' ? settings.version : 1, hooks }
+ await mkdir(dirname(cursorHooksPath), { recursive: true })
+ await writeFile(cursorHooksPath, `${JSON.stringify(settings, null, 2)}\n`)
+}
+
+describe.skipIf(!runCursorE2e)('Cursor local HTTP/WS/tmux E2E', () => {
+ it('runs TodoWrite and Task through the real Cursor CLI without changing the wire protocol', async () => {
+ await execFileAsync('agent', ['--version'])
+ await execFileAsync('tmux', ['-V'])
+
+ const temp = await mkdtemp(join(tmpdir(), 'machine-cursor-e2e-'))
+ const dataDir = join(temp, 'adapter-data')
+ const registryPath = join(dataDir, 'registry.json')
+ const tmuxSession = `machine-cursor-e2e-${process.pid}`
+ const hookPort = await freePort()
+ const token = 'a'.repeat(64)
+ const frames: Envelope[] = []
+ const logs: string[] = []
+ const originalHooks = existsSync(cursorHooksPath) ? await readFile(cursorHooksPath) : null
+ const originalHooksMode = originalHooks ? (await stat(cursorHooksPath)).mode : null
+ const wss = new WebSocketServer({ host: '127.0.0.1', port: 0 })
+ await once(wss, 'listening')
+ const address = wss.address()
+ if (!address || typeof address === 'string') throw new Error('fake backend did not bind')
+ let socket: WebSocket | null = null
+ wss.on('connection', (connected) => {
+ socket = connected
+ connected.on('message', (raw) => {
+ try { frames.push(JSON.parse(raw.toString()) as Envelope) } catch { /* ignore app ping */ }
+ })
+ })
+
+ let adapter: ChildProcess | null = null
+ try {
+ await installTemporaryCursorHooks(hookPort, dataDir)
+ adapter = spawn(tsxBin, ['src/cli.ts', '__run'], {
+ cwd: adapterRoot,
+ env: {
+ ...process.env,
+ NODE_ENV: 'test',
+ ADAPTER_TOKEN: token,
+ ADAPTER_DATA_DIR: dataDir,
+ BACKEND_WS_URL: `ws://127.0.0.1:${address.port}`,
+ WEB_URL: 'http://127.0.0.1:3000',
+ PORT: String(hookPort),
+ DISABLE_HOOK_INSTALL: 'true',
+ ADAPTER_UPDATE_DISABLE: 'true',
+ RECAP_FORCE: 'false',
+ TMUX_REAP_INTERVAL_MS: '1000',
+ CLAUDE_PROJECTS_DIR: join(temp, 'claude-projects'),
+ CODEX_HOME: join(temp, 'codex'),
+ CURSOR_HOME: cursorHome,
+ },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ adapter.stdout?.on('data', (chunk) => logs.push(chunk.toString()))
+ adapter.stderr?.on('data', (chunk) => logs.push(chunk.toString()))
+
+ await waitUntil(
+ 'adapter health',
+ async () => fetch(`http://127.0.0.1:${hookPort}/api/health`).then((res) => res.ok).catch(() => false),
+ Boolean,
+ )
+ const backendSocket = await waitUntil<WebSocket | null>(
+ 'adapter backend websocket',
+ () => socket,
+ (value) => value?.readyState === WebSocket.OPEN,
+ )
+ if (!backendSocket) throw new Error('adapter backend websocket disappeared')
+
+ await execFileAsync('tmux', [
+ 'new-session', '-d', '-s', tmuxSession, '-c', repoRoot,
+ 'agent', '--trust', '--model', 'auto',
+ 'Reply exactly CURSOR_BOOTSTRAP_OK. Do not use tools or edit files.',
+ ])
+
+ const synced = await waitUntil<Envelope | undefined>(
+ 'Cursor agent_synced frame',
+ () => frames.find((item) =>
+ item.t === 'up'
+ && item.frame?.type === 'agent_synced'),
+ Boolean,
+ 45_000,
+ )
+ if (!synced) throw new Error('Cursor agent_synced frame disappeared')
+ expect(synced.frame?.payload?.__e2e).toBeTruthy()
+ const agent = await waitUntil<RegistryEntry | undefined>(
+ 'Cursor session in local adapter status',
+ async () => {
+ const status = await fetch(`http://127.0.0.1:${hookPort}/api/status`).then((res) => res.json()) as {
+ sessions?: RegistryEntry[]
+ }
+ return status.sessions?.find((session) => session.engine === 'cursor')
+ },
+ Boolean,
+ )
+ if (!agent) throw new Error('Cursor session disappeared from local adapter status')
+ expect(agent.id).toBeTruthy()
+ expect(agent.tmuxPane).toMatch(/^%\d+$/)
+
+ await waitUntil(
+ 'bootstrap Cursor turn_ended frame',
+ () => frames.some((item) => item.t === 'up' && item.frame?.type === 'turn_ended'),
+ Boolean,
+ 90_000,
+ )
+ const remoteStartIndex = frames.length
+ backendSocket.send(JSON.stringify({
+ t: 'down',
+ connId: 'e2e-web',
+ frame: {
+ type: 'message',
+ payload: {
+ agentId: agent.id,
+ dbSessionId: agent.id,
+ content: [
+ 'You must use TodoWrite and exactly one Task subagent.',
+ 'Create two todos. The subagent must use Read to inspect package.json and report its package name.',
+ 'Complete both todos, do not edit files, and finish with exactly CURSOR_E2E_OK.',
+ ].join(' '),
+ },
+ },
+ }))
+
+ await waitUntil(
+ 'encrypted Cursor turn_started frame',
+ () => frames.slice(remoteStartIndex)
+ .some((item) => item.t === 'up' && item.frame?.type === 'turn_started'),
+ Boolean,
+ 45_000,
+ )
+ await waitUntil(
+ 'encrypted Cursor turn_ended frame',
+ () => frames.slice(remoteStartIndex)
+ .some((item) => item.t === 'up' && item.frame?.type === 'turn_ended'),
+ Boolean,
+ 3 * 60_000,
+ )
+ await new Promise((resolveWait) => setTimeout(resolveWait, 2_000))
+
+ const entries = JSON.parse(await readFile(registryPath, 'utf8')) as RegistryEntry[]
+ const registered = entries.find((entry) => entry.sessionId === agent.id)
+ expect(registered).toMatchObject({ engine: 'cursor', tmuxPane: agent.tmuxPane })
+ expect(registered?.transcriptPath).toBeTruthy()
+
+ const transcript = await readFile(registered!.transcriptPath!, 'utf8')
+ const lines = transcript.split('\n').filter(Boolean)
+ const links = await loadCursorReplayTaskLinks(cursorHome, agent.id!)
+ const events = cursorMessagesToEvents(lines, agent.id!, links)
+ const starts = events.filter((event) => event.type === 'tool_start')
+ const ends = events.filter((event) => event.type === 'tool_end')
+ const todoStarts = starts.filter((event) => event.payload.tool === 'TodoWrite')
+ const finalTodos = todoStarts.at(-1)?.payload.input as { todos?: Array<{ status?: string }> } | undefined
+ const remoteUsers = events.filter((event) =>
+ event.type === 'user_message'
+ && event.payload.content.includes('You must use TodoWrite and exactly one Task subagent.'))
+
+ expect(events.some((event) => event.type === 'user_message')).toBe(true)
+ expect(remoteUsers).toHaveLength(1)
+ expect(events.some((event) => event.type === 'text_delta'
+ && event.payload.content.includes('CURSOR_E2E_OK'))).toBe(true)
+ expect(todoStarts.length).toBeGreaterThanOrEqual(2)
+ expect(finalTodos?.todos?.length).toBe(2)
+ expect(finalTodos?.todos?.every((todo) => todo.status === 'completed')).toBe(true)
+ expect(starts.some((event) => event.payload.tool === 'Task')).toBe(true)
+ expect(ends.some((event) => event.payload.tool === 'Task')).toBe(true)
+ expect(starts.some((event) => event.payload.parentToolUseId)).toBe(true)
+ expect(frames.some((item) => item.frame?.type === 'tool_start')).toBe(true)
+ expect(frames.some((item) => item.frame?.type === 'tool_end')).toBe(true)
+ const liveFrameTypes = frames.slice(remoteStartIndex)
+ .filter((item) => item.t === 'up')
+ .map((item) => item.frame?.type)
+ expect(liveFrameTypes.indexOf('turn_started')).toBeGreaterThanOrEqual(0)
+ expect(liveFrameTypes.indexOf('tool_start')).toBeGreaterThan(liveFrameTypes.indexOf('turn_started'))
+ } catch (error) {
+ const pane = await execFileAsync('tmux', ['capture-pane', '-p', '-t', tmuxSession, '-S', '-80'])
+ .then(({ stdout }) => stdout)
+ .catch(() => '<tmux session unavailable>')
+ throw new Error([
+ error instanceof Error ? error.stack ?? error.message : String(error),
+ '--- adapter log ---',
+ logs.join('').slice(-20_000),
+ '--- websocket frame types ---',
+ frames.map((item) => `${item.t ?? '?'}:${item.frame?.type ?? '?'}`).join('\n').slice(-10_000),
+ '--- agent_synced frames ---',
+ JSON.stringify(frames.filter((item) => item.frame?.type === 'agent_synced'), null, 2).slice(-20_000),
+ '--- cursor pane ---',
+ pane,
+ ].join('\n'))
+ } finally {
+ await execFileAsync('tmux', ['kill-session', '-t', tmuxSession]).catch(() => undefined)
+ if (adapter) await stopChild(adapter)
+ for (const client of wss.clients) client.terminate()
+ await new Promise<void>((resolveClose) => wss.close(() => resolveClose()))
+ if (originalHooks) {
+ await writeFile(cursorHooksPath, originalHooks, { mode: originalHooksMode ?? undefined })
+ } else {
+ await rm(cursorHooksPath, { force: true })
+ }
+ await rm(temp, { recursive: true, force: true })
+ }
+ }, E2E_TIMEOUT_MS)
+})
diff --git a/cli/src/engines/cursor/normalizer.spec.ts b/cli/src/engines/cursor/normalizer.spec.ts
new file mode 100644
index 000000000..864b81e8c
--- /dev/null
+++ b/cli/src/engines/cursor/normalizer.spec.ts
@@ -0,0 +1,197 @@
+import { describe, expect, it } from 'vitest'
+import {
+ CursorNormalizer,
+ cursorMessagesToEvents,
+ cursorTaskId,
+ cursorUserText,
+ lastCursorTurnText,
+ windowCursorLines,
+} from './normalizer.js'
+
+const line = (value: unknown): string => JSON.stringify(value)
+const user = (text: string): string => line({
+ role: 'user',
+ message: { content: [{ type: 'text', text: `<timestamp>now</timestamp>\n<user_query>\n${text}\n</user_query>` }] },
+})
+const assistant = (...content: unknown[]): string => line({ role: 'assistant', message: { content } })
+
+describe('CursorNormalizer', () => {
+ it('strips only the outer Cursor user wrapper', () => {
+ expect(cursorUserText('<timestamp>x</timestamp><user_query>hello <tag>x</tag></user_query>'))
+ .toBe('hello <tag>x</tag>')
+ })
+
+ it('folds TodoWrite deltas into full snapshots', () => {
+ const events = cursorMessagesToEvents([
+ user('todo'),
+ assistant({ type: 'tool_use', name: 'TodoWrite', input: {
+ merge: false,
+ todos: [
+ { id: 'a', content: 'A', status: 'in_progress' },
+ { id: 'b', content: 'B', status: 'pending' },
+ ],
+ } }),
+ assistant({ type: 'tool_use', name: 'TodoWrite', input: {
+ merge: true,
+ todos: [
+ { id: 'a', status: 'completed' },
+ { id: 'b', status: 'deleted' },
+ ],
+ } }),
+ line({ type: 'turn_ended', status: 'success' }),
+ ], 'session')
+ const starts = events.filter((event) => event.type === 'tool_start')
+ expect(starts).toHaveLength(2)
+ expect(starts[1]).toMatchObject({
+ payload: {
+ tool: 'TodoWrite',
+ input: {
+ todos: [
+ { id: 'a', content: 'A', status: 'completed' },
+ ],
+ },
+ },
+ })
+ })
+
+ it('normalizes Cursor WebSearch search_term to the client query field', () => {
+ const events = cursorMessagesToEvents([
+ user('search'),
+ assistant({ type: 'tool_use', name: 'WebSearch', input: {
+ search_term: 'Bitcoin BTC Ethereum ETH price USD today live',
+ explanation: 'Get current prices.',
+ } }),
+ line({ type: 'turn_ended', status: 'success' }),
+ ], 'session')
+
+ expect(events).toContainEqual({
+ type: 'tool_start',
+ payload: {
+ id: 'cursor:session:1:0',
+ tool: 'WebSearch',
+ input: {
+ query: 'Bitcoin BTC Ethereum ETH price USD today live',
+ search_term: 'Bitcoin BTC Ethereum ETH price USD today live',
+ explanation: 'Get current prices.',
+ },
+ },
+ })
+ })
+
+ it('hides Cursor redaction placeholders from live and replay text', () => {
+ const response = assistant(
+ { type: 'text', text: 'Hi - can gi tiep khong?\n\n[REDACTED]' },
+ { type: 'text', text: '[REDACTED]' },
+ )
+ const live = new CursorNormalizer('live', 'session')
+ live.ingest(user('hi'))
+
+ expect(live.ingest(response)).toEqual([{
+ type: 'text_delta',
+ payload: { content: 'Hi - can gi tiep khong?' },
+ }])
+ expect(cursorMessagesToEvents([user('hi'), response], 'session')).toContainEqual({
+ type: 'text_delta',
+ payload: { content: 'Hi - can gi tiep khong?' },
+ })
+ expect(cursorMessagesToEvents([user('hi'), response], 'session'))
+ .not.toContainEqual(expect.objectContaining({
+ type: 'text_delta',
+ payload: expect.objectContaining({ content: '[REDACTED]' }),
+ }))
+ })
+
+ it('hides Cursor redaction placeholders from recap text', () => {
+ expect(lastCursorTurnText([
+ user('hi'),
+ assistant({ type: 'text', text: 'Hi - can gi tiep khong?\n\n[REDACTED]' }),
+ assistant({ type: 'text', text: '[REDACTED]' }),
+ ])).toEqual({
+ userMessage: 'hi',
+ assistantText: 'Hi - can gi tiep khong?',
+ })
+ })
+
+ it('deduplicates Task preToolUse from the later transcript block', () => {
+ const normalizer = new CursorNormalizer('live', 'session')
+ const input = { description: 'Inspect', prompt: 'Inspect it', model: 'inherit' }
+ const hook = normalizer.ingestTaskHook({ toolUseId: 'call-1', input })
+ const transcript = normalizer.ingest(assistant({ type: 'tool_use', name: 'Task', input }))
+ expect(hook).toEqual([{
+ type: 'tool_start',
+ payload: { id: cursorTaskId('session', 'call-1'), tool: 'Task', input },
+ }])
+ expect(transcript).toEqual([])
+ })
+
+ it('maps replay child tools and result under the Task launcher', () => {
+ const events = cursorMessagesToEvents([
+ user('delegate'),
+ assistant({ type: 'tool_use', name: 'Task', input: { description: 'Inspect', prompt: 'Inspect it' } }),
+ ], 'session', [{
+ toolUseId: 'call-1',
+ prompt: 'Inspect it',
+ output: 'Done',
+ isError: false,
+ agentId: 'child',
+ totalToolUseCount: 1,
+ events: [
+ { type: 'tool_start', payload: { id: 'child-tool', tool: 'Read', input: { path: 'a' } } },
+ { type: 'tool_end', payload: { id: 'child-tool', tool: 'Read', output: '', isError: false, summary: 'Completed' } },
+ ],
+ }])
+ const launcherId = cursorTaskId('session', 'call-1')
+ expect(events).toContainEqual({
+ type: 'tool_start',
+ payload: { id: 'child-tool', tool: 'Read', input: { path: 'a' }, parentToolUseId: launcherId },
+ })
+ expect(events).toContainEqual(expect.objectContaining({
+ type: 'tool_end',
+ payload: expect.objectContaining({ id: launcherId, output: 'Done' }),
+ }))
+ })
+
+ it('hydrates Todo state before a paginated window that starts with a delta', () => {
+ const lines = [
+ user('first'),
+ assistant({ type: 'tool_use', name: 'TodoWrite', input: {
+ merge: false,
+ todos: [{ id: 'a', content: 'A', status: 'pending' }],
+ } }),
+ line({ type: 'turn_ended', status: 'success' }),
+ user('second'),
+ assistant({ type: 'tool_use', name: 'TodoWrite', input: {
+ merge: true,
+ todos: [{ id: 'a', status: 'completed' }],
+ } }),
+ line({ type: 'turn_ended', status: 'success' }),
+ ]
+ const window = windowCursorLines(lines, { limit: 2 })
+ const events = cursorMessagesToEvents(
+ window.window,
+ 'session',
+ [],
+ window.startIndex,
+ window.initialTodos,
+ )
+ expect(events).toContainEqual(expect.objectContaining({
+ type: 'tool_start',
+ payload: expect.objectContaining({
+ tool: 'TodoWrite',
+ input: { todos: [{ id: 'a', content: 'A', status: 'completed' }] },
+ }),
+ }))
+ })
+
+ it('emits the existing done marker before the live turn boundary', () => {
+ const normalizer = new CursorNormalizer('live', 'session')
+ const events = [
+ ...normalizer.ingest(user('hello')),
+ ...normalizer.ingest(line({ type: 'turn_ended', status: 'success' })),
+ ]
+ expect(events.slice(-2)).toEqual([
+ { type: 'done', payload: { result: 'success' } },
+ { type: 'turn_ended', payload: {} },
+ ])
+ })
+})
diff --git a/cli/src/engines/cursor/normalizer.ts b/cli/src/engines/cursor/normalizer.ts
new file mode 100644
index 000000000..31856bfd6
--- /dev/null
+++ b/cli/src/engines/cursor/normalizer.ts
@@ -0,0 +1,452 @@
+import { createHash } from 'node:crypto'
+import type { EngineNormalizer } from '../types.js'
+import type { LastTurnText, LiveEvent, SessionEvent } from '../../lib/normalize.js'
+
+type JsonObject = Record<string, unknown>
+
+const MAX_OUTPUT = 2_000
+const TODO_STATUSES = new Set(['pending', 'in_progress', 'completed'])
+
+interface PendingTool {
+ tool: string
+ fromHook: boolean
+}
+
+interface CursorTodo {
+ id: string
+ content: string
+ status: string
+}
+
+export interface CursorTaskHook {
+ toolUseId: string
+ input: unknown
+}
+
+export interface CursorTaskCompletion {
+ output: string
+ isError: boolean
+ agentId?: string
+ agentType?: string
+ totalToolUseCount?: number
+ totalDurationMs?: number
+ events?: SessionEvent[]
+}
+
+export interface CursorReplayTaskLink extends CursorTaskCompletion {
+ toolUseId: string
+ prompt: string
+ description?: string
+}
+
+function object(value: unknown): JsonObject | null {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+ ? value as JsonObject
+ : null
+}
+
+function string(value: unknown): string {
+ return typeof value === 'string' ? value : ''
+}
+
+function parse(line: string): JsonObject | null {
+ try { return object(JSON.parse(line)) } catch { return null }
+}
+
+function clip(value: string): string {
+ return value.length > MAX_OUTPUT ? `${value.slice(0, MAX_OUTPUT)}\n...[truncated]` : value
+}
+
+function contentBlocks(raw: JsonObject): JsonObject[] {
+ const message = object(raw.message)
+ return Array.isArray(message?.content)
+ ? message.content.map(object).filter((item): item is JsonObject => item !== null)
+ : []
+}
+
+function cursorAssistantText(rawText: string): string | null {
+ const lines = rawText.split(/\r?\n/)
+ while (lines.at(-1)?.trim() === '[REDACTED]') {
+ lines.pop()
+ while (lines.at(-1)?.trim() === '') lines.pop()
+ }
+ const text = lines.join('\n').trimEnd()
+ return text.trim() ? text : null
+}
+
+export function cursorUserText(rawText: string): string | null {
+ const wrapped = /^\s*<timestamp>[\s\S]*?<\/timestamp>\s*<user_query>\s*([\s\S]*?)\s*<\/user_query>\s*$/.exec(rawText)
+ if (wrapped) return wrapped[1].trim()
+ return rawText.trim() || null
+}
+
+function taskInput(value: unknown): JsonObject {
+ return object(value) ?? {}
+}
+
+function cursorToolInput(tool: string, value: unknown): unknown {
+ const input = object(value)
+ if (tool === 'WebSearch' && input && !string(input.query) && string(input.search_term)) {
+ return { ...input, query: input.search_term }
+ }
+ return value ?? {}
+}
+
+function taskKey(value: unknown): string {
+ const input = taskInput(value)
+ return JSON.stringify({
+ description: string(input.description),
+ prompt: string(input.prompt),
+ model: string(input.model),
+ })
+}
+
+export function cursorTaskId(sessionId: string, toolUseId: string): string {
+ return `cursor-task:${createHash('sha256').update(sessionId).update('\0').update(toolUseId).digest('hex')}`
+}
+
+function taskSummary(output: string, isError: boolean): string {
+ if (isError) return 'Subagent failed'
+ return output.trim().split('\n')[0]?.slice(0, 120) || 'Subagent completed'
+}
+
+function applyTodoInput(
+ todoById: Map<string, CursorTodo>,
+ todoOrder: string[],
+ value: unknown,
+): boolean {
+ const input = object(value)
+ const merge = input?.merge
+ const todos = Array.isArray(input?.todos) ? input.todos : null
+ if (typeof merge !== 'boolean' || !todos) return false
+ if (!merge) {
+ todoById.clear()
+ todoOrder.splice(0)
+ }
+ for (const rawTodo of todos) {
+ const todo = object(rawTodo)
+ const todoId = string(todo?.id)
+ if (!todoId) continue
+ if (todo?.status === 'deleted') {
+ todoById.delete(todoId)
+ const index = todoOrder.indexOf(todoId)
+ if (index >= 0) todoOrder.splice(index, 1)
+ continue
+ }
+ const previous = todoById.get(todoId)
+ const content = string(todo?.content) || previous?.content || ''
+ if (!content) continue
+ const rawStatus = string(todo?.status)
+ const status = TODO_STATUSES.has(rawStatus) ? rawStatus : previous?.status ?? 'pending'
+ if (!previous) todoOrder.push(todoId)
+ todoById.set(todoId, { id: todoId, content, status })
+ }
+ return true
+}
+
+function todoSnapshot(todoById: Map<string, CursorTodo>, todoOrder: string[]): CursorTodo[] {
+ return todoOrder
+ .map((todoId) => todoById.get(todoId))
+ .filter((todo): todo is CursorTodo => todo !== undefined)
+}
+
+function cursorTodoState(rawLines: string[]): CursorTodo[] {
+ const todoById = new Map<string, CursorTodo>()
+ const todoOrder: string[] = []
+ for (const line of rawLines) {
+ const raw = parse(line)
+ if (raw?.role !== 'assistant') continue
+ for (const block of contentBlocks(raw)) {
+ if (block.type === 'tool_use' && block.name === 'TodoWrite') {
+ applyTodoInput(todoById, todoOrder, block.input)
+ }
+ }
+ }
+ return todoSnapshot(todoById, todoOrder)
+}
+
+export class CursorNormalizer implements EngineNormalizer {
+ private open = false
+ private recordIndex: number
+ private readonly pending = new Map<string, PendingTool>()
+ private readonly hookQueue: Array<{ id: string; key: string; matched: boolean }> = []
+ private readonly todoById = new Map<string, CursorTodo>()
+ private readonly todoOrder: string[] = []
+ private readonly replayLinks: CursorReplayTaskLink[]
+
+ constructor(
+ private readonly mode: 'live' | 'replay',
+ private readonly sessionId: string,
+ options: {
+ startIndex?: number
+ replayLinks?: CursorReplayTaskLink[]
+ initialTodos?: CursorTodo[]
+ } = {},
+ ) {
+ this.recordIndex = options.startIndex ?? 0
+ this.replayLinks = [...(options.replayLinks ?? [])]
+ for (const todo of options.initialTodos ?? []) {
+ this.todoOrder.push(todo.id)
+ this.todoById.set(todo.id, { ...todo })
+ }
+ }
+
+ get turnOpen(): boolean { return this.open }
+
+ ingest(line: string): LiveEvent[] {
+ const index = this.recordIndex++
+ const raw = parse(line)
+ if (!raw) return []
+
+ if (raw.type === 'turn_ended') {
+ return this.finishTurn(string(raw.status).toLowerCase() === 'error')
+ }
+
+ if (raw.role === 'user') {
+ const first = contentBlocks(raw).find((block) => block.type === 'text')
+ const userText = cursorUserText(string(first?.text))
+ if (!userText) return []
+ if (this.mode === 'replay') {
+ this.open = true
+ return [{ type: 'user_message', payload: { content: userText } }]
+ }
+ const events: LiveEvent[] = []
+ if (this.open) events.push(...this.finishTurn(false))
+ this.open = true
+ events.push({ type: 'turn_started', payload: { userMessage: userText } })
+ return events
+ }
+
+ if (raw.role !== 'assistant') return []
+ const events: LiveEvent[] = []
+ const blocks = contentBlocks(raw)
+ for (let contentIndex = 0; contentIndex < blocks.length; contentIndex++) {
+ const block = blocks[contentIndex]
+ if (block.type === 'text') {
+ const text = cursorAssistantText(string(block.text))
+ if (text) events.push({ type: 'text_delta', payload: { content: text } })
+ continue
+ }
+ if (block.type !== 'tool_use') continue
+ const tool = string(block.name) || 'Tool'
+ const input = cursorToolInput(tool, block.input)
+ const id = `cursor:${this.sessionId}:${index}:${contentIndex}`
+ if (tool === 'TodoWrite') {
+ events.push(...this.todoEvents(id, input))
+ } else if (tool === 'Task') {
+ events.push(...this.taskEvents(id, input))
+ } else {
+ this.pending.set(id, { tool, fromHook: false })
+ events.push({ type: 'tool_start', payload: { id, tool, input } })
+ }
+ }
+ return events
+ }
+
+ ingestTaskHook(hook: CursorTaskHook): LiveEvent[] {
+ if (!hook.toolUseId) return []
+ const id = cursorTaskId(this.sessionId, hook.toolUseId)
+ if (this.pending.has(id)) return []
+ this.pending.set(id, { tool: 'Task', fromHook: true })
+ this.hookQueue.push({ id, key: taskKey(hook.input), matched: false })
+ return [{ type: 'tool_start', payload: { id, tool: 'Task', input: hook.input } }]
+ }
+
+ completeTask(id: string, completion: CursorTaskCompletion): LiveEvent[] {
+ const pending = this.pending.get(id)
+ if (!pending || pending.tool !== 'Task') return []
+ this.pending.delete(id)
+ const events: LiveEvent[] = []
+ for (const event of completion.events ?? []) {
+ if (event.type === 'tool_start') {
+ events.push({ type: 'tool_start', payload: { ...event.payload, parentToolUseId: id } })
+ } else if (event.type === 'tool_end') {
+ events.push({ type: 'tool_end', payload: { ...event.payload, parentToolUseId: id } })
+ }
+ }
+ const output = completion.output || (completion.isError ? 'Subagent failed' : 'Subagent completed')
+ events.push({
+ type: 'tool_end',
+ payload: {
+ id,
+ tool: 'Task',
+ output: clip(output),
+ isError: completion.isError,
+ summary: taskSummary(output, completion.isError),
+ subagent: completion.agentId || completion.agentType || completion.totalToolUseCount != null
+ ? {
+ agentId: completion.agentId,
+ agentType: completion.agentType,
+ totalToolUseCount: completion.totalToolUseCount,
+ totalDurationMs: completion.totalDurationMs,
+ }
+ : undefined,
+ },
+ })
+ return events
+ }
+
+ closeOutstandingTasks(isError = false): LiveEvent[] {
+ const events: LiveEvent[] = []
+ for (const [id, pending] of [...this.pending]) {
+ if (pending.tool !== 'Task') continue
+ this.pending.delete(id)
+ const output = isError ? 'Subagent turn aborted' : 'Subagent completed'
+ events.push({
+ type: 'tool_end',
+ payload: { id, tool: 'Task', output: '', isError, summary: output },
+ })
+ }
+ return events
+ }
+
+ closeTurn(): LiveEvent[] {
+ return this.finishTurn(false)
+ }
+
+ finishReplay(): LiveEvent[] {
+ return this.closePending(false, true)
+ }
+
+ private todoEvents(id: string, value: unknown): LiveEvent[] {
+ if (!applyTodoInput(this.todoById, this.todoOrder, value)) return []
+ const snapshot = todoSnapshot(this.todoById, this.todoOrder)
+ return [
+ { type: 'tool_start', payload: { id, tool: 'TodoWrite', input: { todos: snapshot } } },
+ {
+ type: 'tool_end',
+ payload: { id, tool: 'TodoWrite', output: 'Updated tasks', isError: false, summary: 'Updated tasks' },
+ },
+ ]
+ }
+
+ private taskEvents(fallbackId: string, input: unknown): LiveEvent[] {
+ const key = taskKey(input)
+ const hook = this.hookQueue.find((entry) => !entry.matched && entry.key === key)
+ if (hook) {
+ hook.matched = true
+ return []
+ }
+
+ if (this.mode === 'replay') {
+ const task = taskInput(input)
+ const prompt = string(task.prompt)
+ const description = string(task.description)
+ const linkIndex = this.replayLinks.findIndex((candidate) =>
+ candidate.prompt === prompt
+ && (!candidate.description || !description || candidate.description === description))
+ if (linkIndex >= 0) {
+ const link = this.replayLinks.splice(linkIndex, 1)[0]
+ const id = cursorTaskId(this.sessionId, link.toolUseId)
+ this.pending.set(id, { tool: 'Task', fromHook: false })
+ return [
+ { type: 'tool_start', payload: { id, tool: 'Task', input } },
+ ...this.completeTask(id, link),
+ ]
+ }
+ }
+
+ this.pending.set(fallbackId, { tool: 'Task', fromHook: false })
+ return [{ type: 'tool_start', payload: { id: fallbackId, tool: 'Task', input } }]
+ }
+
+ private finishTurn(isError: boolean): LiveEvent[] {
+ const events = this.closePending(isError, false)
+ if (!this.open) return events
+ events.push({ type: 'done', payload: { result: isError ? 'error' : 'success' } })
+ if (this.mode === 'live') events.push({ type: 'turn_ended', payload: {} })
+ this.open = false
+ return events
+ }
+
+ private closePending(isError: boolean, includeHookTasks: boolean): LiveEvent[] {
+ const events: LiveEvent[] = []
+ for (const [id, pending] of [...this.pending]) {
+ if (pending.fromHook && !includeHookTasks) continue
+ this.pending.delete(id)
+ const output = isError ? 'Turn failed' : ''
+ events.push({
+ type: 'tool_end',
+ payload: {
+ id,
+ tool: pending.tool,
+ output,
+ isError,
+ summary: isError ? 'Turn failed' : 'Completed',
+ },
+ })
+ }
+ return events
+ }
+}
+
+export function cursorMessagesToEvents(
+ rawLines: string[],
+ sessionId: string,
+ replayLinks: CursorReplayTaskLink[] = [],
+ startIndex = 0,
+ initialTodos: CursorTodo[] = [],
+): SessionEvent[] {
+ const normalizer = new CursorNormalizer('replay', sessionId, { replayLinks, startIndex, initialTodos })
+ const events: SessionEvent[] = []
+ for (const line of rawLines) events.push(...normalizer.ingest(line) as SessionEvent[])
+ events.push(...normalizer.finishReplay() as SessionEvent[])
+ return events
+}
+
+export function lastCursorTurnText(rawLines: string[]): LastTurnText | null {
+ let userMessage = ''
+ let assistantText = ''
+ for (const line of rawLines) {
+ const raw = parse(line)
+ if (!raw) continue
+ if (raw.role === 'user') {
+ const first = contentBlocks(raw).find((block) => block.type === 'text')
+ const text = cursorUserText(string(first?.text))
+ if (text) { userMessage = text; assistantText = '' }
+ } else if (raw.role === 'assistant') {
+ for (const block of contentBlocks(raw)) {
+ if (block.type === 'text') {
+ const text = cursorAssistantText(string(block.text))
+ if (text) assistantText += `${assistantText ? '\n\n' : ''}${text}`
+ }
+ }
+ }
+ }
+ return assistantText ? { userMessage, assistantText } : null
+}
+
+export function windowCursorLines(
+ rawLines: string[],
+ opts: { limit: number; before?: string },
+): {
+ window: string[]
+ startIndex: number
+ initialTodos: CursorTodo[]
+ hasMore: boolean
+ oldestCursor: string | null
+ staleCursor?: boolean
+} {
+ let endIndex = rawLines.length
+ if (opts.before) {
+ const match = /^cursor:(\d+)$/.exec(opts.before)
+ if (!match) return { window: [], startIndex: 0, initialTodos: [], hasMore: false, oldestCursor: null, staleCursor: true }
+ endIndex = Number(match[1])
+ if (!Number.isSafeInteger(endIndex) || endIndex < 0 || endIndex > rawLines.length) {
+ return { window: [], startIndex: 0, initialTodos: [], hasMore: false, oldestCursor: null, staleCursor: true }
+ }
+ }
+ let start = Math.max(0, endIndex - opts.limit)
+ while (start > 0) {
+ const raw = parse(rawLines[start])
+ if (raw?.role === 'user') break
+ start--
+ }
+ return {
+ window: rawLines.slice(start, endIndex),
+ startIndex: start,
+ initialTodos: cursorTodoState(rawLines.slice(0, start)),
+ hasMore: start > 0,
+ oldestCursor: `cursor:${start}`,
+ }
+}
diff --git a/cli/src/engines/cursor/pendingTasks.ts b/cli/src/engines/cursor/pendingTasks.ts
new file mode 100644
index 000000000..0828e20f5
--- /dev/null
+++ b/cli/src/engines/cursor/pendingTasks.ts
@@ -0,0 +1,87 @@
+import { mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
+import { dirname, join } from 'node:path'
+
+export interface PendingCursorTask {
+ sessionId: string
+ toolUseId: string
+ input: unknown
+ createdAt: number
+}
+
+const FILE_NAME = 'cursor-pending-tasks.json'
+const MAX_AGE_MS = 10 * 60_000
+const LOCK_RETRIES = 20
+const LOCK_RETRY_MS = 25
+const LOCK_STALE_MS = 5_000
+
+function valid(raw: unknown): raw is PendingCursorTask {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return false
+ const value = raw as Record<string, unknown>
+ return typeof value.sessionId === 'string'
+ && !!value.sessionId
+ && typeof value.toolUseId === 'string'
+ && !!value.toolUseId
+ && typeof value.createdAt === 'number'
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms))
+}
+
+async function withLock<T>(file: string, operation: () => Promise<T>): Promise<T | null> {
+ const lock = `${file}.lock`
+ await mkdir(dirname(file), { recursive: true })
+ for (let attempt = 0; attempt < LOCK_RETRIES; attempt++) {
+ try {
+ await mkdir(lock)
+ try { return await operation() } finally { await rm(lock, { recursive: true, force: true }) }
+ } catch {
+ try {
+ if (Date.now() - (await stat(lock)).mtimeMs > LOCK_STALE_MS) {
+ await rm(lock, { recursive: true, force: true })
+ }
+ } catch {
+ // lock disappeared
+ }
+ await sleep(LOCK_RETRY_MS)
+ }
+ }
+ return null
+}
+
+async function read(file: string): Promise<PendingCursorTask[]> {
+ try {
+ const parsed = JSON.parse(await readFile(file, 'utf8')) as unknown
+ const now = Date.now()
+ return Array.isArray(parsed)
+ ? parsed.filter((item): item is PendingCursorTask => valid(item) && now - item.createdAt <= MAX_AGE_MS)
+ : []
+ } catch {
+ return []
+ }
+}
+
+async function write(file: string, tasks: PendingCursorTask[]): Promise<void> {
+ const tmp = `${file}.${process.pid}.tmp`
+ await writeFile(tmp, JSON.stringify(tasks, null, 2))
+ await rename(tmp, file)
+}
+
+export async function loadCursorPendingTasks(dataDir: string): Promise<PendingCursorTask[]> {
+ const file = join(dataDir, FILE_NAME)
+ return (await withLock(file, async () => {
+ const tasks = await read(file)
+ if (tasks.length) await write(file, tasks)
+ else await rm(file, { force: true })
+ return tasks
+ })) ?? []
+}
+
+export async function removeCursorPendingTasks(dataDir: string, sessionId: string): Promise<void> {
+ const file = join(dataDir, FILE_NAME)
+ await withLock(file, async () => {
+ const tasks = (await read(file)).filter((task) => task.sessionId !== sessionId)
+ if (tasks.length) await write(file, tasks)
+ else await rm(file, { force: true })
+ })
+}
diff --git a/cli/src/engines/cursor/subagent.ts b/cli/src/engines/cursor/subagent.ts
new file mode 100644
index 000000000..3f457b051
--- /dev/null
+++ b/cli/src/engines/cursor/subagent.ts
@@ -0,0 +1,296 @@
+import { readFile, readdir, realpath, stat } from 'node:fs/promises'
+import { basename, dirname, join, relative } from 'node:path'
+import type { LiveEvent, SessionEvent } from '../../lib/normalize.js'
+import {
+ CursorNormalizer,
+ cursorMessagesToEvents,
+ cursorTaskId,
+ cursorUserText,
+ lastCursorTurnText,
+ type CursorReplayTaskLink,
+ type CursorTaskCompletion,
+ type CursorTaskHook,
+} from './normalizer.js'
+import { findCursorTranscript } from './discovery.js'
+
+type JsonObject = Record<string, unknown>
+
+interface ChildMeta {
+ agentId: string
+ createdAt?: number
+ subagentInfo: {
+ parentAgentId: string
+ rootParentAgentId?: string
+ toolCallId: string
+ typeName?: string
+ }
+}
+
+interface PendingTask {
+ parentId: string
+ launcherId: string
+ hook: CursorTaskHook
+ normalizer: CursorNormalizer
+ startedAt: number
+ timer: NodeJS.Timeout | null
+ attempts: number
+}
+
+interface Database {
+ prepare(sql: string): { get(...params: unknown[]): Record<string, unknown> | undefined }
+ close(): void
+}
+
+type DatabaseConstructor = new(path: string, options: { readOnly: boolean }) => Database
+
+const META_MAX_BYTES = 64 * 1024
+const RESOLVE_MAX_ATTEMPTS = 600
+
+function object(value: unknown): JsonObject | null {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+ ? value as JsonObject
+ : null
+}
+
+function string(value: unknown): string {
+ return typeof value === 'string' ? value : ''
+}
+
+function isWithin(root: string, file: string): boolean {
+ const rel = relative(root, file)
+ return rel === '' || (!rel.startsWith('..') && !rel.startsWith('/') && !rel.startsWith('\\'))
+}
+
+async function databaseConstructor(): Promise<DatabaseConstructor | null> {
+ try {
+ const moduleName = 'node:sqlite'
+ const mod = await import(moduleName) as { DatabaseSync?: DatabaseConstructor }
+ return mod.DatabaseSync ?? null
+ } catch {
+ return null
+ }
+}
+
+async function readChildMeta(chatsRoot: string, dbPath: string): Promise<ChildMeta | null> {
+ let actualRoot: string
+ let actual: string
+ try {
+ [actualRoot, actual] = await Promise.all([realpath(chatsRoot), realpath(dbPath)])
+ const info = await stat(actual)
+ const uid = typeof process.getuid === 'function' ? process.getuid() : null
+ if (!info.isFile() || !isWithin(actualRoot, actual) || (uid !== null && info.uid !== uid)) return null
+ } catch {
+ return null
+ }
+ const DatabaseSync = await databaseConstructor()
+ if (!DatabaseSync) return null
+ let db: Database | null = null
+ try {
+ db = new DatabaseSync(actual, { readOnly: true })
+ const row = db.prepare("SELECT value FROM meta WHERE key = '0' LIMIT 1").get()
+ const encoded = string(row?.value)
+ if (!encoded || encoded.length > META_MAX_BYTES * 2 || encoded.length % 2 !== 0 || !/^[0-9a-f]+$/i.test(encoded)) return null
+ const decoded = Buffer.from(encoded, 'hex').toString('utf8')
+ if (Buffer.byteLength(decoded) > META_MAX_BYTES) return null
+ const raw = object(JSON.parse(decoded))
+ const subagent = object(raw?.subagentInfo)
+ const agentId = string(raw?.agentId)
+ const parentAgentId = string(subagent?.parentAgentId)
+ const toolCallId = string(subagent?.toolCallId)
+ if (!agentId || basename(dirname(actual)) !== agentId || !parentAgentId || !toolCallId) return null
+ return {
+ agentId,
+ createdAt: typeof raw?.createdAt === 'number' ? raw.createdAt : undefined,
+ subagentInfo: {
+ parentAgentId,
+ rootParentAgentId: string(subagent?.rootParentAgentId) || undefined,
+ toolCallId,
+ typeName: string(subagent?.typeName) || undefined,
+ },
+ }
+ } catch {
+ return null
+ } finally {
+ try { db?.close() } catch { /* read-only best effort */ }
+ }
+}
+
+async function parentChatDir(cursorHome: string, parentId: string): Promise<string | null> {
+ const chatsRoot = join(cursorHome, 'chats')
+ let roots: string[]
+ try { roots = await readdir(chatsRoot) } catch { return null }
+ for (const root of roots) {
+ const candidate = join(chatsRoot, root, parentId, 'store.db')
+ try {
+ if ((await stat(candidate)).isFile()) return dirname(dirname(candidate))
+ } catch {
+ // next workspace hash
+ }
+ }
+ return null
+}
+
+async function childMetas(cursorHome: string, parentId: string): Promise<ChildMeta[]> {
+ const dir = await parentChatDir(cursorHome, parentId)
+ if (!dir) return []
+ const chatsRoot = join(cursorHome, 'chats')
+ let children: string[]
+ try { children = await readdir(dir) } catch { return [] }
+ const values = await Promise.all(children.map((child) => readChildMeta(chatsRoot, join(dir, child, 'store.db'))))
+ return values.filter((value): value is ChildMeta => value?.subagentInfo.parentAgentId === parentId)
+}
+
+function firstUserPrompt(lines: string[]): string {
+ for (const line of lines) {
+ try {
+ const raw = object(JSON.parse(line))
+ const message = object(raw?.message)
+ const content = Array.isArray(message?.content) ? message.content : []
+ if (raw?.role !== 'user') continue
+ for (const block of content) {
+ const item = object(block)
+ if (item?.type !== 'text') continue
+ return cursorUserText(string(item.text)) ?? ''
+ }
+ } catch {
+ // malformed child line
+ }
+ }
+ return ''
+}
+
+function terminalStatus(lines: string[]): { complete: boolean; isError: boolean } {
+ for (let i = lines.length - 1; i >= 0; i--) {
+ try {
+ const raw = object(JSON.parse(lines[i]))
+ if (raw?.type === 'turn_ended') return { complete: true, isError: string(raw.status) === 'error' }
+ } catch {
+ // keep searching
+ }
+ }
+ return { complete: false, isError: false }
+}
+
+async function childCompletion(
+ cursorHome: string,
+ meta: ChildMeta,
+ observedDurationMs?: number,
+): Promise<(CursorTaskCompletion & { prompt: string }) | null> {
+ const transcript = await findCursorTranscript(cursorHome, meta.agentId)
+ if (!transcript) return null
+ let raw: string
+ try { raw = await readFile(transcript, 'utf8') } catch { return null }
+ const lines = raw.split('\n').filter((line) => line.trim())
+ const terminal = terminalStatus(lines)
+ if (!terminal.complete) return null
+ const events = cursorMessagesToEvents(lines, meta.agentId)
+ .filter((event): event is SessionEvent => event.type === 'tool_start' || event.type === 'tool_end')
+ const last = lastCursorTurnText(lines)
+ return {
+ prompt: firstUserPrompt(lines),
+ output: last?.assistantText ?? (terminal.isError ? 'Subagent failed' : 'Subagent completed'),
+ isError: terminal.isError,
+ agentId: meta.agentId,
+ agentType: meta.subagentInfo.typeName,
+ totalToolUseCount: events.filter((event) => event.type === 'tool_start').length,
+ totalDurationMs: observedDurationMs,
+ events,
+ }
+}
+
+export async function loadCursorReplayTaskLinks(
+ cursorHome: string,
+ parentId: string,
+): Promise<CursorReplayTaskLink[]> {
+ const links: CursorReplayTaskLink[] = []
+ for (const meta of await childMetas(cursorHome, parentId)) {
+ const completion = await childCompletion(cursorHome, meta)
+ if (!completion) continue
+ links.push({
+ ...completion,
+ toolUseId: meta.subagentInfo.toolCallId,
+ prompt: completion.prompt,
+ })
+ }
+ return links
+}
+
+export class CursorSubagentManager {
+ private readonly pending = new Map<string, PendingTask>()
+
+ constructor(
+ private readonly cursorHome: string,
+ private readonly emit: (parentId: string, events: LiveEvent[]) => void,
+ ) {}
+
+ register(parentId: string, hook: CursorTaskHook, normalizer: CursorNormalizer): void {
+ const launcherId = cursorTaskId(parentId, hook.toolUseId)
+ if (this.pending.has(hook.toolUseId)) return
+ const task: PendingTask = {
+ parentId,
+ launcherId,
+ hook,
+ normalizer,
+ startedAt: Date.now(),
+ timer: null,
+ attempts: 0,
+ }
+ this.pending.set(hook.toolUseId, task)
+ this.schedule(task, 50)
+ }
+
+ closeParent(parentId: string, isError = false): void {
+ setTimeout(() => {
+ const tasks = [...this.pending.values()].filter((task) => task.parentId === parentId)
+ if (tasks.length === 0) return
+ for (const task of tasks) this.clear(task)
+ const normalizer = tasks[0].normalizer
+ this.emit(parentId, normalizer.closeOutstandingTasks(isError))
+ }, 2_000)
+ }
+
+ forget(parentId: string): void {
+ for (const task of [...this.pending.values()]) if (task.parentId === parentId) this.clear(task)
+ }
+
+ stop(): void {
+ for (const task of [...this.pending.values()]) this.clear(task)
+ }
+
+ private schedule(task: PendingTask, delay: number): void {
+ task.timer = setTimeout(() => void this.resolve(task), delay)
+ }
+
+ private async resolve(task: PendingTask): Promise<void> {
+ if (this.pending.get(task.hook.toolUseId) !== task) return
+ task.attempts++
+ try {
+ const meta = (await childMetas(this.cursorHome, task.parentId))
+ .find((candidate) => candidate.subagentInfo.toolCallId === task.hook.toolUseId)
+ if (meta) {
+ const completion = await childCompletion(this.cursorHome, meta, Date.now() - task.startedAt)
+ if (completion) {
+ this.clear(task)
+ this.emit(task.parentId, task.normalizer.completeTask(task.launcherId, completion))
+ return
+ }
+ }
+ } catch {
+ // retry while the parent turn is alive
+ }
+ if (task.attempts >= RESOLVE_MAX_ATTEMPTS) {
+ this.clear(task)
+ this.emit(task.parentId, task.normalizer.completeTask(task.launcherId, {
+ output: '',
+ isError: false,
+ }))
+ return
+ }
+ this.schedule(task, task.attempts < 20 ? 250 : 1_000)
+ }
+
+ private clear(task: PendingTask): void {
+ if (task.timer) clearTimeout(task.timer)
+ this.pending.delete(task.hook.toolUseId)
+ }
+}
diff --git a/cli/src/engines/cursor/taskHookQueue.spec.ts b/cli/src/engines/cursor/taskHookQueue.spec.ts
new file mode 100644
index 000000000..5de889c50
--- /dev/null
+++ b/cli/src/engines/cursor/taskHookQueue.spec.ts
@@ -0,0 +1,89 @@
+import { describe, expect, it } from 'vitest'
+import type { LiveEvent, SessionEvent } from '../../lib/normalize.js'
+import {
+ CursorNormalizer,
+ cursorMessagesToEvents,
+ cursorTaskId,
+ type CursorTaskHook,
+} from './normalizer.js'
+import { CursorTaskHookQueue } from './taskHookQueue.js'
+
+const line = (value: unknown): string => JSON.stringify(value)
+const user = (text: string): string => line({
+ role: 'user',
+ message: { content: [{ type: 'text', text: `<timestamp>now</timestamp>\n<user_query>\n${text}\n</user_query>` }] },
+})
+const assistant = (...content: unknown[]): string => line({ role: 'assistant', message: { content } })
+
+function renderOrder(events: Array<LiveEvent | SessionEvent>): string[] {
+ return events.flatMap((event) => {
+ if (event.type === 'turn_started') return [`user:${event.payload.userMessage}`]
+ if (event.type === 'user_message') return [`user:${event.payload.content}`]
+ if (event.type === 'text_delta') return [`text:${event.payload.content}`]
+ if (event.type === 'tool_start' && event.payload.tool === 'Task' && !event.payload.parentToolUseId) {
+ const input = event.payload.input as { description?: string }
+ return [`task:${input.description ?? ''}`]
+ }
+ return []
+ })
+}
+
+describe('CursorTaskHookQueue', () => {
+ it('makes live watcher order match transcript replay for parallel Task launches', async () => {
+ const sessionId = 'session'
+ const prompt = 'Run three reports in parallel'
+ const inputs = ['BTC', 'ETH', 'BNB'].map((coin) => ({
+ description: `Report ${coin}`,
+ prompt: `Report price for ${coin}`,
+ model: 'inherit',
+ }))
+ const transcript = [
+ user(prompt),
+ assistant({ type: 'text', text: 'Launching three agents.' }),
+ ...inputs.map((input) => assistant({ type: 'tool_use', name: 'Task', input })),
+ ]
+ const normalizer = new CursorNormalizer('live', sessionId)
+ const liveEvents: LiveEvent[] = []
+ let transcriptDrained = false
+ const registered: CursorTaskHook[] = []
+ const queue = new CursorTaskHookQueue({
+ drainTranscript: async () => {
+ if (transcriptDrained) return
+ transcriptDrained = true
+ for (const raw of transcript) liveEvents.push(...normalizer.ingest(raw))
+ },
+ emit: (_id, events) => liveEvents.push(...events),
+ register: (_id, hook) => registered.push(hook),
+ isActive: () => true,
+ })
+
+ inputs.forEach((input, index) => {
+ queue.enqueue(sessionId, { toolUseId: `call-${index + 1}`, input }, normalizer)
+ })
+ await queue.wait(sessionId)
+
+ const replayEvents = cursorMessagesToEvents(
+ transcript,
+ sessionId,
+ inputs.map((input, index) => ({
+ toolUseId: `call-${index + 1}`,
+ prompt: input.prompt,
+ description: input.description,
+ output: `${input.description} done`,
+ isError: false,
+ })),
+ )
+
+ expect(renderOrder(liveEvents)).toEqual(renderOrder(replayEvents))
+ expect(renderOrder(liveEvents)).toEqual([
+ `user:${prompt}`,
+ 'text:Launching three agents.',
+ 'task:Report BTC',
+ 'task:Report ETH',
+ 'task:Report BNB',
+ ])
+ expect(registered.map((hook) => cursorTaskId(sessionId, hook.toolUseId))).toEqual(
+ [1, 2, 3].map((index) => cursorTaskId(sessionId, `call-${index}`)),
+ )
+ })
+})
diff --git a/cli/src/engines/cursor/taskHookQueue.ts b/cli/src/engines/cursor/taskHookQueue.ts
new file mode 100644
index 000000000..1162a74fd
--- /dev/null
+++ b/cli/src/engines/cursor/taskHookQueue.ts
@@ -0,0 +1,55 @@
+import type { LiveEvent } from '../../lib/normalize.js'
+import {
+ CursorNormalizer,
+ type CursorTaskHook,
+} from './normalizer.js'
+
+interface CursorTaskHookQueueOptions {
+ drainTranscript: (sessionId: string) => Promise<void>
+ emit: (sessionId: string, events: LiveEvent[]) => void
+ register: (sessionId: string, hook: CursorTaskHook, normalizer: CursorNormalizer) => void
+ isActive: (sessionId: string) => boolean
+ onError?: (sessionId: string, error: unknown) => void
+}
+
+/**
+ * Cursor's preToolUse hook can beat the transcript watcher by one debounce window. Ingest the hook
+ * immediately for stable-id dedupe, but serialize its visible start behind a transcript drain so the
+ * parent user/text records always reach clients before Task cards.
+ */
+export class CursorTaskHookQueue {
+ private readonly tails = new Map<string, Promise<void>>()
+
+ constructor(private readonly options: CursorTaskHookQueueOptions) {}
+
+ enqueue(sessionId: string, hook: CursorTaskHook, normalizer: CursorNormalizer): void {
+ const startEvents = normalizer.ingestTaskHook(hook)
+ const previous = this.tails.get(sessionId) ?? Promise.resolve()
+ let current: Promise<void>
+ current = previous
+ .then(async () => {
+ try {
+ await this.options.drainTranscript(sessionId)
+ } catch (error) {
+ this.options.onError?.(sessionId, error)
+ }
+ if (!this.options.isActive(sessionId)) return
+ this.options.emit(sessionId, startEvents)
+ this.options.register(sessionId, hook, normalizer)
+ })
+ .catch((error) => this.options.onError?.(sessionId, error))
+ .finally(() => {
+ if (this.tails.get(sessionId) === current) this.tails.delete(sessionId)
+ })
+ this.tails.set(sessionId, current)
+ }
+
+ async wait(sessionId: string): Promise<void> {
+ while (true) {
+ const current = this.tails.get(sessionId)
+ if (!current) return
+ await current
+ if (this.tails.get(sessionId) === current) return
+ }
+ }
+}
diff --git a/cli/src/engines/devin/askQuestion.spec.ts b/cli/src/engines/devin/askQuestion.spec.ts
new file mode 100644
index 000000000..83a3892f0
--- /dev/null
+++ b/cli/src/engines/devin/askQuestion.spec.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'fs'
+import { fileURLToPath } from 'url'
+import { parseDevinQuestionPane } from './askQuestion.js'
+import type { QuestionView } from '../../lib/askQuestion.js'
+
+/**
+ * Both fixtures are real `tmux capture-pane -e -J` output from devin 3000.3.22, taken while the dialog was
+ * open — including the scrollback of ALREADY ANSWERED questions above it, which is the thing most likely to
+ * fool a parser on this engine (devin keeps every `⏺ Asked user …` summary on screen).
+ */
+function fixture(name: string): string {
+ return readFileSync(fileURLToPath(new URL(`../../lib/__fixtures__/${name}`, import.meta.url)), 'utf-8')
+}
+
+const single = (): QuestionView => parseDevinQuestionPane(fixture('question-devin.txt')) as QuestionView
+const multi = (): QuestionView => parseDevinQuestionPane(fixture('question-devin-multi.txt')) as QuestionView
+
+describe('devin question dialog', () => {
+ it('reads the question and its options', () => {
+ const view = single()
+ expect(view.kind).toBe('question')
+ expect(view.question).toBe('Bạn thích màu gì?')
+ expect(view.rows.map((r) => [r.number, r.label])).toEqual([['1', 'Xanh'], ['2', 'Đỏ']])
+ expect(view.multi).toBe(false)
+ })
+
+ it('drops the description line under each option', () => {
+ // "Màu xanh dương hoặc xanh lá" sits directly below its row and has no marker; treating it as an
+ // option would offer the device an answer no keystroke can reach.
+ const labels = single().rows.map((r) => r.label)
+ expect(labels).not.toContain('Màu xanh dương hoặc xanh lá')
+ expect(labels).toHaveLength(2)
+ })
+
+ it('never offers "Other (type your own)" as an option', () => {
+ // It opens a text editor rather than selecting anything, and the device's question screen has no
+ // input — so an answer of "Other" could never be keyed in.
+ for (const view of [single(), multi()]) {
+ expect(view.rows.map((r) => r.label)).not.toContain('Other (type your own)')
+ }
+ })
+
+ it('recognises a multi-select dialog and which boxes are already ticked', () => {
+ const view = multi()
+ expect(view.multi).toBe(true)
+ expect(view.question).toBe('Bạn thích màu nào? (có thể chọn nhiều màu)') // the `(multi-select)` tag is UI, not question
+ expect(view.rows.map((r) => [r.number, r.label, r.checked])).toEqual([
+ ['1', 'Xanh', false], ['2', 'Đỏ', false], ['3', 'Vàng', false],
+ ])
+ })
+
+ it('reads the live dialog, not an answered one left in the scrollback', () => {
+ // Both fixtures carry earlier `⏺ Asked user …` summaries with their chosen answers above the live
+ // dialog; anchoring on the LAST footer is what keeps those out.
+ expect(fixture('question-devin.txt')).toContain('Asked user')
+ expect(single().question).toBe('Bạn thích màu gì?')
+ })
+
+ it('says nothing when no dialog is open', () => {
+ expect(parseDevinQuestionPane('')).toBeNull()
+ expect(parseDevinQuestionPane('⏺ Asked user Bạn thích màu gì?\n └ Đỏ\n❭ Ask Devin to build features')).toBeNull()
+ })
+
+ it('ignores a footer with no dialog above it', () => {
+ expect(parseDevinQuestionPane('some prose\n↑↓ navigate · ↵ select · esc cancel')).toBeNull()
+ })
+})
diff --git a/cli/src/engines/devin/askQuestion.ts b/cli/src/engines/devin/askQuestion.ts
new file mode 100644
index 000000000..7e57b590a
--- /dev/null
+++ b/cli/src/engines/devin/askQuestion.ts
@@ -0,0 +1,86 @@
+/**
+ * Devin's AskUserQuestion dialog, as it paints in the tmux pane.
+ *
+ * Same job as the shared parser in `lib/askQuestion.ts`, different shape — devin draws its own dialog and
+ * none of Claude's anchors exist in it:
+ *
+ * ── Màu yêu thích ────────────────────────────── ← titled rule (tabs when multi-step)
+ * Bạn thích màu nào? (có thể chọn nhiều màu) (multi-select)
+ * ■ 1 Xanh ← marker, number, label
+ * Màu xanh dương hoặc xanh lá ← description of the row above, NOT an option
+ * □ 2 Đỏ
+ * □ 3 Other (type your own)
+ * ─────────────────────────────────────────────── ← plain rule
+ * ↑↓ navigate · ␣ toggle · ↵ select · e select+type · ? help me out · esc cancel
+ *
+ * Differences that matter: rows have NO dot after the number (Claude writes `1. Label`), every row carries
+ * a description line beneath it, and single-select rows use `·` / `❭` where multi-select uses `□` / `■`.
+ *
+ * Key mechanics, measured against devin 3000.3.22 on a live pane rather than read off the footer (which
+ * advertises only arrows):
+ * - single-select : typing the row's DIGIT selects and submits in one keystroke, like Claude.
+ * - multi-select : the digit TOGGLES the box; `Enter` submits (Claude uses Tab here).
+ * - "Other (type your own)" opens a text editor, so it is never offered as an answerable option.
+ */
+
+import type { PaneView, QuestionRow } from '../../lib/askQuestion.js'
+
+/** `↑↓ navigate · ␣ toggle · ↵ select · …` — the line that marks a dialog as open. */
+const FOOTER_RE = /navigate\s*·.*\bselect\b/i
+/** A rule with a title in it: `── Màu yêu thích ──` or the multi-step `── Size ✓ · Màu sắc ──`.
+ * The title may not be made of dashes: `\S` alone also matched a rule of PURE dashes, so the plain
+ * closing rule under the options looked like the opening one and the dialog read as empty. */
+const TITLED_RULE_RE = /^\s*─{2,}\s*[^─\s][^─]*─{2,}\s*$/
+const PLAIN_RULE_RE = /^\s*─{2,}\s*$/
+/** Marker, optional number, label. The description lines below a row carry neither, so they never match. */
+const ROW_RE = /^\s*([❭❯›>·□■☑✔])\s+(?:(\d+)\s+)?(\S.*?)\s*$/
+const OTHER_RE = /^other\s*\(type your own\)$/i
+const CHECKED = new Set(['■', '☑', '✔'])
+
+function stripAnsi(value: string): string {
+ return value.replace(/\u001b\[[0-9;:]*[A-Za-z]/g, '')
+}
+
+/**
+ * The open devin dialog in `capture`, or null when there is none.
+ *
+ * Anchored on the LAST footer in the capture and read upward, because a devin pane keeps every answered
+ * question in its scrollback (`⏺ Asked user …`) and an earlier dialog must never be mistaken for the live
+ * one.
+ */
+export function parseDevinQuestionPane(capture: string): PaneView {
+ const lines = stripAnsi(capture).replace(/\u00a0/g, ' ').split('\n')
+ const footer = lines.findLastIndex((line) => FOOTER_RE.test(line))
+ if (footer < 0) return null
+
+ // Above the footer: the plain closing rule, the rows, then the titled rule that opens the dialog.
+ let top = -1
+ for (let i = footer - 1; i >= 0 && footer - i < 40; i--) {
+ if (TITLED_RULE_RE.test(lines[i])) { top = i; break }
+ }
+ if (top < 0) return null
+
+ const rows: QuestionRow[] = []
+ let question = ''
+ let multi = false
+ for (let i = top + 1; i < footer; i++) {
+ const line = lines[i]
+ if (PLAIN_RULE_RE.test(line)) break
+ const row = ROW_RE.exec(line)
+ if (!row) {
+ // The first non-row line under the title is the question itself; anything later is a description.
+ if (!rows.length && !question && line.trim()) question = line.trim()
+ continue
+ }
+ const [, marker, number, label] = row
+ if (CHECKED.has(marker) || marker === '□') multi = true
+ // Unnumbered rows cannot be answered by keystroke, and "Other" opens a text editor either way.
+ if (!number || OTHER_RE.test(label)) continue
+ rows.push({ number, label, checked: CHECKED.has(marker) })
+ }
+
+ if (!rows.length) return null
+ // Devin also states it outright, which covers a dialog whose boxes are off-screen.
+ if (/\(multi-select\)/i.test(question)) multi = true
+ return { kind: 'question', question: question.replace(/\s*\(multi-select\)\s*$/i, '').trim(), rows, multi, typeRow: null }
+}
diff --git a/cli/src/engines/devin/errorLog.spec.ts b/cli/src/engines/devin/errorLog.spec.ts
new file mode 100644
index 000000000..465f9dbe2
--- /dev/null
+++ b/cli/src/engines/devin/errorLog.spec.ts
@@ -0,0 +1,98 @@
+import { afterEach, describe, expect, it } from 'vitest'
+import { appendFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
+import { join } from 'path'
+import { tmpdir } from 'os'
+import { cleanDevinErrorMessage, DevinErrorTail, devinLogPathForSession } from './errorLog.js'
+
+/** The exact line Devin logged when the live session `tested-crabapple` lost its turn. */
+const REAL_ERROR = "2026-07-28T06:38:22.096212Z WARN chisel_core::translator: ACP: agent error (Internal):"
+ + " Permission denied: Permission denied: We're currently facing high demand for this model."
+ + " Please try again later. (trace ID: acb60788b786ddfb16a00ddb3d83b053)"
+const NOISE = [
+ '2026-07-28T06:38:10.872387Z WARN chisel_api::telemetry::unleash_sampling: sentry sampling poll failed: error decoding response body',
+ "2026-07-28T06:38:11.066878Z WARN toolbox::tools::mcp: server=\"gitnexus\" error=connection closed: initialize response",
+].join('\n')
+
+const dirs: string[] = []
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })
+
+function devinHome(pid = 39022, sessionId = 'tested-crabapple'): { home: string; log: string } {
+ const home = mkdtempSync(join(tmpdir(), 'adapter-devin-logs-'))
+ dirs.push(home)
+ mkdirSync(join(home, 'session_locks'), { recursive: true })
+ mkdirSync(join(home, 'logs'), { recursive: true })
+ writeFileSync(join(home, 'session_locks', `${sessionId}.lock`), String(pid))
+ const log = join(home, 'logs', `devin_20260728-133808_${pid}.log`)
+ writeFileSync(log, '')
+ return { home, log }
+}
+
+describe('devin error log', () => {
+ it('resolves a session log through its lock PID', () => {
+ const { home, log } = devinHome()
+ // A log belonging to another devin process must not match.
+ writeFileSync(join(home, 'logs', 'devin_20260728-133746_37518.log'), '')
+
+ expect(devinLogPathForSession(home, 'tested-crabapple')).toBe(log)
+ expect(devinLogPathForSession(home, 'no-such-session')).toBeNull()
+ })
+
+ it('reports the agent error and ignores unrelated WARN noise', () => {
+ const { home, log } = devinHome()
+ const tail = new DevinErrorTail(home, 'tested-crabapple')
+ tail.seekToEnd()
+
+ appendFileSync(log, NOISE + '\n')
+ expect(tail.poll()).toEqual([])
+
+ appendFileSync(log, REAL_ERROR + '\n')
+ expect(tail.poll()).toEqual([
+ "Permission denied: We're currently facing high demand for this model. Please try again later.",
+ ])
+ expect(tail.poll()).toEqual([]) // consumed — never re-reported
+ })
+
+ it('never replays a failure logged before the watcher attached', () => {
+ const { home, log } = devinHome()
+ appendFileSync(log, REAL_ERROR + '\n')
+
+ const tail = new DevinErrorTail(home, 'tested-crabapple')
+ tail.seekToEnd()
+ expect(tail.poll()).toEqual([])
+ })
+
+ it('recovers when the log is truncated or rotated under it', () => {
+ const { home, log } = devinHome()
+ const tail = new DevinErrorTail(home, 'tested-crabapple')
+ tail.seekToEnd()
+ appendFileSync(log, NOISE + '\n')
+ tail.poll()
+
+ writeFileSync(log, REAL_ERROR + '\n') // shorter than the old offset
+ expect(tail.poll()).toHaveLength(1)
+ })
+
+ it('binds late when the lock exists before the log file does', () => {
+ const home = mkdtempSync(join(tmpdir(), 'adapter-devin-logs-'))
+ dirs.push(home)
+ mkdirSync(join(home, 'session_locks'), { recursive: true })
+ mkdirSync(join(home, 'logs'), { recursive: true })
+ writeFileSync(join(home, 'session_locks', 'late-session.lock'), '4242')
+
+ const tail = new DevinErrorTail(home, 'late-session')
+ tail.seekToEnd()
+ expect(tail.poll()).toEqual([])
+
+ const log = join(home, 'logs', 'devin_20260728-140000_4242.log')
+ writeFileSync(log, '')
+ expect(tail.poll()).toEqual([]) // first poll binds and seeks to end
+ appendFileSync(log, REAL_ERROR + '\n')
+ expect(tail.poll()).toHaveLength(1)
+ })
+
+ it('collapses Devin\'s doubled prefix and drops the trace id', () => {
+ expect(cleanDevinErrorMessage('Permission denied: Permission denied: Too busy. (trace ID: abc123)'))
+ .toBe('Permission denied: Too busy.')
+ expect(cleanDevinErrorMessage('Internal error: something broke')).toBe('Internal error: something broke')
+ })
+})
diff --git a/cli/src/engines/devin/errorLog.ts b/cli/src/engines/devin/errorLog.ts
new file mode 100644
index 000000000..144d21647
--- /dev/null
+++ b/cli/src/engines/devin/errorLog.ts
@@ -0,0 +1,135 @@
+/**
+ * Devin turn-failure detection.
+ *
+ * Devin has no `StopFailure` counterpart to claude's: when a turn dies on a provider error it writes NO
+ * assistant row and fires NO `Stop` hook, so both of the reader's turn-close signals are absent and the
+ * web spins on the typing indicator forever. Observed live (session `tested-crabapple`): the user row
+ * landed, `[turn] started` was logged, and nothing followed.
+ *
+ * Devin does record the failure in its own rotating log, one line, 0.7s after the turn began:
+ *
+ * 2026-07-28T06:38:22.096212Z WARN chisel_core::translator: ACP: agent error (Internal):
+ * Permission denied: … We're currently facing high demand for this model. … (trace ID: acb60788…)
+ *
+ * That is a far better signal than scraping the TUI, and the session→log mapping is exact:
+ * `session_locks/<id>.lock` holds the owning PID and the log is `logs/devin_<stamp>_<pid>.log`.
+ */
+
+import { readdirSync, readFileSync, statSync } from 'fs'
+import { join } from 'path'
+
+/** The ACP translator line Devin logs when a turn dies. WARN-level, but terminal for the turn. */
+const AGENT_ERROR_RE = /\bACP: agent error(?:\s*\(([^)]*)\))?:\s*(.+)$/
+/** Every log line starts with an RFC3339 UTC stamp: `2026-07-28T06:38:22.096212Z WARN …`. */
+const LEADING_TIMESTAMP_RE = /^(\d{4}-\d{2}-\d{2}T[\d:.]+Z)\s/
+/** Look-back cap for `scanSince` — the failure we heal is always at the very tail of the log. */
+const SCAN_BACK_BYTES = 256 * 1024
+
+/** Resolve a session's current log file through its lock PID; null when either is missing. */
+export function devinLogPathForSession(devinHome: string, sessionId: string): string | null {
+ let pid: number
+ try {
+ pid = Number(readFileSync(join(devinHome, 'session_locks', `${sessionId}.lock`), 'utf8').trim())
+ } catch { return null }
+ if (!Number.isInteger(pid) || pid <= 0) return null
+
+ const suffix = `_${pid}.log`
+ let newest: { path: string; mtime: number } | null = null
+ let entries: string[]
+ try { entries = readdirSync(join(devinHome, 'logs')) } catch { return null }
+ for (const name of entries) {
+ if (!name.startsWith('devin_') || !name.endsWith(suffix)) continue
+ const path = join(devinHome, 'logs', name)
+ try {
+ const mtime = statSync(path).mtimeMs
+ if (!newest || mtime > newest.mtime) newest = { path, mtime }
+ } catch { /* rotated away mid-scan */ }
+ }
+ return newest?.path ?? null
+}
+
+/** Strip Devin's doubled prefixes and the trace id so the web/device message stays readable. */
+export function cleanDevinErrorMessage(raw: string): string {
+ let text = raw.trim().replace(/\s*\(trace ID:\s*[0-9a-f]+\)\s*$/i, '')
+ // "Permission denied: Permission denied: …" — the translator wraps the provider message verbatim.
+ let previous = ''
+ while (previous !== text) {
+ previous = text
+ text = text.replace(/^([^:]{3,40}):\s*\1:\s*/, '$1: ')
+ }
+ return text.trim()
+}
+
+/**
+ * Byte-offset tail over one session's Devin log, yielding only agent-error messages.
+ * Starts at EOF so a failure logged before the watcher attached never fires retroactively.
+ */
+export class DevinErrorTail {
+ private path: string | null = null
+ private offset = 0
+
+ constructor(private readonly devinHome: string, private readonly sessionId: string) {}
+
+ /** Bind to the current log file and skip everything already written. */
+ seekToEnd(): void {
+ this.path = devinLogPathForSession(this.devinHome, this.sessionId)
+ if (!this.path) return
+ try { this.offset = statSync(this.path).size } catch { this.offset = 0 }
+ }
+
+ /**
+ * Agent errors logged AFTER `isoTimestamp`, regardless of the tail offset. Used once at attach to heal a
+ * turn that died before the daemon started: its failure sits behind `seekToEnd`, so `poll()` never sees
+ * it and the web would stay on the typing indicator across a restart.
+ */
+ scanSince(isoTimestamp: string): string[] {
+ if (!this.path) this.path = devinLogPathForSession(this.devinHome, this.sessionId)
+ if (!this.path) return []
+ const since = Date.parse(isoTimestamp)
+ if (!Number.isFinite(since)) return []
+
+ let text: string
+ try {
+ const buffer = readFileSync(this.path)
+ // Bounded look-back: a long-lived session's log can be large and only the tail can be relevant.
+ text = buffer.subarray(Math.max(0, buffer.length - SCAN_BACK_BYTES)).toString('utf8')
+ } catch { return [] }
+
+ const out: string[] = []
+ for (const line of text.split('\n')) {
+ const match = AGENT_ERROR_RE.exec(line)
+ if (!match) continue
+ const stamp = Date.parse(LEADING_TIMESTAMP_RE.exec(line)?.[1] ?? '')
+ if (Number.isFinite(stamp) && stamp < since) continue // predates the turn we are healing
+ out.push(cleanDevinErrorMessage(match[2]))
+ }
+ return out
+ }
+
+ /** New agent-error messages since the last call (empty when the log is missing/unchanged). */
+ poll(): string[] {
+ // Re-resolve until found: `devin -r` writes its lock before the log file appears.
+ if (!this.path) {
+ this.seekToEnd()
+ return []
+ }
+ let size: number
+ try { size = statSync(this.path).size } catch { this.path = null; return [] }
+ if (size < this.offset) this.offset = 0 // rotated/truncated
+ if (size === this.offset) return []
+
+ let chunk: string
+ try {
+ const fd = readFileSync(this.path)
+ chunk = fd.subarray(this.offset, size).toString('utf8')
+ } catch { return [] }
+ this.offset = size
+
+ const out: string[] = []
+ for (const line of chunk.split('\n')) {
+ const match = AGENT_ERROR_RE.exec(line)
+ if (match) out.push(cleanDevinErrorMessage(match[2]))
+ }
+ return out
+ }
+}
diff --git a/cli/src/engines/devin/normalizer.spec.ts b/cli/src/engines/devin/normalizer.spec.ts
new file mode 100644
index 000000000..ea2ecdbf0
--- /dev/null
+++ b/cli/src/engines/devin/normalizer.spec.ts
@@ -0,0 +1,167 @@
+import { describe, expect, it } from 'vitest'
+import { newTurnState } from '../../lib/normalize.js'
+import {
+ devinMessageToEvents,
+ devinMessagesToEvents,
+ devinToolName,
+ isDevinTurnEnd,
+ lastDevinTurnText,
+ reshapeMessage,
+ windowDevinMessages,
+ type DvMessage,
+} from './normalizer.js'
+
+/**
+ * Fixtures are the real rows captured from `devin 3000.2.17` session `classy-tourmaline`
+ * (`~/.local/share/devin/cli/sessions.db`, `message_nodes`) — two turns, the second calling `exec`.
+ */
+function msg(over: Partial<DvMessage> & Pick<DvMessage, 'rowId' | 'messageId' | 'role'>): DvMessage {
+ return {
+ content: '',
+ thinking: null,
+ toolCalls: null,
+ toolCallId: null,
+ finishReason: null,
+ ...over,
+ }
+}
+
+const USER_1 = msg({
+ rowId: 37,
+ messageId: '634a2f5b-42af-4102-8986-6bb16e99a381',
+ role: 'user',
+ content: 'Reply with exactly DEVIN-PROBE-OK and nothing else.',
+})
+const ASSISTANT_1 = msg({
+ rowId: 58,
+ messageId: 'a1a1a1a1-0000-4000-8000-000000000001',
+ role: 'assistant',
+ content: 'DEVIN-PROBE-OK',
+ thinking: 'The user is asking me to reply with exactly "DEVIN-PROBE-OK" and nothing else.',
+ finishReason: 'stop',
+})
+const USER_2 = msg({
+ rowId: 60,
+ messageId: 'b2b2b2b2-0000-4000-8000-000000000002',
+ role: 'user',
+ content: 'Run the shell command: echo hello-devin. Then say DEVIN-TOOL-OK.',
+})
+const ASSISTANT_TOOL = msg({
+ rowId: 61,
+ messageId: 'c3c3c3c3-0000-4000-8000-000000000003',
+ role: 'assistant',
+ content: '',
+ thinking: 'The user wants me to run a simple shell command `echo hello-devin`.',
+ toolCalls: JSON.stringify([
+ { id: 'call_d022d4a199c04d298861d6c7', name: 'exec', arguments: { command: 'echo hello-devin' }, index: 0, kind: 'function' },
+ ]),
+ finishReason: 'tool_calls',
+})
+const TOOL_RESULT = msg({
+ rowId: 63,
+ messageId: 'd4d4d4d4-0000-4000-8000-000000000004',
+ role: 'tool',
+ content: 'Output from command in shell f8215f:\nhello-devin\n\n\nExit code: 0',
+ toolCallId: 'call_d022d4a199c04d298861d6c7',
+})
+const ASSISTANT_2 = msg({
+ rowId: 64,
+ messageId: 'e5e5e5e5-0000-4000-8000-000000000005',
+ role: 'assistant',
+ content: 'DEVIN-TOOL-OK',
+ thinking: 'The command executed successfully and output "hello-devin".',
+ finishReason: 'stop',
+})
+const SESSION = [USER_1, ASSISTANT_1, USER_2, ASSISTANT_TOOL, TOOL_RESULT, ASSISTANT_2]
+
+function liveTypes(messages: DvMessage[]): string[] {
+ const state = newTurnState()
+ return messages.flatMap((m) => devinMessageToEvents(m, state)).map((e) => e.type)
+}
+
+describe('devin normalizer', () => {
+ it('emits a full turn lifecycle for a tool-calling turn', () => {
+ const types = liveTypes([USER_2, ASSISTANT_TOOL, TOOL_RESULT, ASSISTANT_2])
+
+ expect(types[0]).toBe('turn_started')
+ expect(types).toContain('thinking_delta')
+ expect(types).toContain('tool_start')
+ expect(types).toContain('tool_end')
+ expect(types).toContain('text_delta')
+ expect(types[types.length - 1]).toBe('turn_ended')
+ })
+
+ it('keeps the turn open while the assistant is still calling tools', () => {
+ const state = newTurnState()
+ devinMessageToEvents(USER_2, state)
+ devinMessageToEvents(ASSISTANT_TOOL, state)
+
+ expect(state.turnOpen).toBe(true)
+ expect(isDevinTurnEnd(ASSISTANT_TOOL)).toBe(false)
+
+ devinMessageToEvents(TOOL_RESULT, state)
+ devinMessageToEvents(ASSISTANT_2, state)
+ expect(state.turnOpen).toBe(false)
+ expect(isDevinTurnEnd(ASSISTANT_2)).toBe(true)
+ })
+
+ it('maps Devin tool ids onto the shared card vocabulary', () => {
+ expect(devinToolName('exec')).toBe('Bash')
+ expect(devinToolName('find_file_by_name')).toBe('Glob')
+ expect(devinToolName('notebook_edit')).toBe('Edit')
+ expect(devinToolName('run_subagent')).toBe('Task')
+ expect(devinToolName('webfetch')).toBe('WebFetch')
+ // Unmapped tools still read well on a card.
+ expect(devinToolName('mcp_call_tool')).toBe('McpCallTool')
+ expect(devinToolName('')).toBe('tool')
+ })
+
+ it('renders the tool card with the mapped name and its real output', () => {
+ const events = devinMessagesToEvents(SESSION)
+ const start = events.find((e) => e.type === 'tool_start')
+ const end = events.find((e) => e.type === 'tool_end')
+
+ expect((start?.payload as { tool?: string })?.tool).toBe('Bash')
+ expect((start?.payload as { input?: { command?: string } })?.input?.command).toBe('echo hello-devin')
+ expect((end?.payload as { tool?: string })?.tool).toBe('Bash')
+ expect(String((end?.payload as { output?: unknown })?.output)).toContain('hello-devin')
+ expect((end?.payload as { isError?: boolean })?.isError).toBe(false)
+ })
+
+ it('drops the system prefix and a tool row with no tool_call_id', () => {
+ expect(reshapeMessage(msg({ rowId: 1, messageId: 's', role: 'system', content: 'You are Devin' }))).toBeNull()
+ expect(reshapeMessage(msg({ rowId: 2, messageId: 't', role: 'tool', content: 'orphan' }))).toBeNull()
+ })
+
+ it('takes the last user prompt and the assistant text that followed it as the recap source', () => {
+ expect(lastDevinTurnText(SESSION)).toEqual({
+ userMessage: 'Run the shell command: echo hello-devin. Then say DEVIN-TOOL-OK.',
+ assistantText: 'DEVIN-TOOL-OK',
+ })
+ })
+
+ it('snaps a pagination window back to a user prompt so a turn is never split', () => {
+ // limit=3 would start mid-turn (at ASSISTANT_TOOL); the window must back up to USER_2.
+ const w = windowDevinMessages(SESSION, { limit: 3 })
+
+ expect(w.window[0]).toBe(USER_2)
+ expect(w.oldestCursor).toBe('devin:2')
+ expect(w.hasMore).toBe(true)
+ })
+
+ it('rejects a malformed or out-of-range window cursor', () => {
+ expect(windowDevinMessages(SESSION, { limit: 2, before: 'hermes:1' }).staleCursor).toBe(true)
+ expect(windowDevinMessages(SESSION, { limit: 2, before: 'devin:999' }).staleCursor).toBe(true)
+ })
+
+ it('survives malformed tool_calls JSON without dropping the message', () => {
+ const broken = msg({
+ rowId: 70, messageId: 'f6', role: 'assistant', content: 'still here',
+ toolCalls: '{not json', finishReason: 'stop',
+ })
+ const events = devinMessagesToEvents([USER_1, broken])
+
+ expect(events.some((e) => e.type === 'text_delta')).toBe(true)
+ expect(events.some((e) => e.type === 'tool_start')).toBe(false)
+ })
+})
diff --git a/cli/src/engines/devin/normalizer.ts b/cli/src/engines/devin/normalizer.ts
new file mode 100644
index 000000000..b0e5ec5e8
--- /dev/null
+++ b/cli/src/engines/devin/normalizer.ts
@@ -0,0 +1,219 @@
+/**
+ * Devin CLI (devin.ai, Cognition) SQLite rows → shared event vocabulary.
+ *
+ * Devin keeps history in `<DEVIN_HOME>/sessions.db` (WAL) rather than a transcript file, so it is polled
+ * like opencode/hermes (see `./reader.ts`). Two properties of that store shape this module — both
+ * verified against real captured sessions (devin 3000.2.17):
+ *
+ * 1. **Each `message_nodes.chat_message` maps 1:1 onto Claude's content blocks**, so instead of
+ * re-implementing a normalizer we reshape a row into the Claude raw shape and hand it to the existing,
+ * battle-tested `lineToEvents`/`messagesToEvents` (`src/lib/normalize.ts`) — which already do thinking
+ * ids, tool-name tracking, `tool_result`→`tool_end` joining, truncation and tool summaries:
+ *
+ * {"message_id":"…","role":"user"|"assistant"|"tool"|"system","content":"…",
+ * "thinking":{"thinking":"…"}, "tool_call_id":"call_…",
+ * "tool_calls":[{"id":"call_…","name":"exec","arguments":{…},"index":0,"kind":"function"}],
+ * "metadata":{"finish_reason":"tool_calls"|"stop", …}}
+ *
+ * `metadata.finish_reason` is authoritative, so unlike Command Code nothing has to be synthesized:
+ * `tool_calls` continues the turn, anything else ends it.
+ *
+ * 2. **Rows repeat.** `message_nodes` is a forest — Devin re-persists the whole prompt chain as fresh
+ * `node_id`s on every inference, so one user prompt showed up 4× and its reply 2× across 29 raw rows
+ * (6 real messages). `message_id` is stable across those copies and is the dedupe key; the reader must
+ * never tail `row_id` alone or the mirror repeats every message.
+ */
+
+import {
+ lastTurnTextFromRawLines,
+ lineToEvents,
+ messagesToEvents,
+ type LastTurnText,
+ type LiveEvent,
+ type SessionEvent,
+ type TurnState,
+} from '../../lib/normalize.js'
+
+/** One deduped row of `message_nodes`, as returned by `readDevinMessages`. */
+export interface DvMessage {
+ rowId: number
+ messageId: string
+ role: string
+ content: string
+ thinking: string | null
+ /** Raw JSON text of the `tool_calls` array, straight out of `json_extract`. */
+ toolCalls: string | null
+ toolCallId: string | null
+ finishReason: string | null
+ /** `metadata.created_at` (RFC3339 UTC) — lets the reader tell a log failure apart from an older one. */
+ createdAt?: string | null
+}
+
+/** Devin tool ids → the vocabulary the web/device cards render. */
+const TOOL_NAMES: Record<string, string> = {
+ exec: 'Bash',
+ shell_command: 'Bash',
+ get_output: 'Bash',
+ kill_shell: 'Bash',
+ write_to_process: 'Bash',
+ read: 'Read',
+ notebook_read: 'Read',
+ read_subagent: 'Read',
+ write: 'Write',
+ edit: 'Edit',
+ apply_patch: 'Edit',
+ notebook_edit: 'Edit',
+ find_file_by_name: 'Glob',
+ grep: 'Grep',
+ web_search: 'WebSearch',
+ webfetch: 'WebFetch',
+ todo_write: 'TodoWrite',
+ update_plan: 'TodoWrite',
+ run_subagent: 'Task',
+ skill: 'Task',
+ ask_user_question: 'AskUserQuestion',
+ exit_plan_mode: 'ExitPlanMode',
+}
+
+export function devinToolName(name: string): string {
+ const key = (name || '').toLowerCase()
+ if (TOOL_NAMES[key]) return TOOL_NAMES[key]
+ if (!name) return 'tool'
+ // `mcp_call_tool` and any new/unmapped tool: snake_case → TitleCase so the card still reads well.
+ return name.split('_').filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join('')
+}
+
+function object(value: unknown): Record<string, unknown> | null {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+ ? value as Record<string, unknown>
+ : null
+}
+
+function str(value: unknown): string {
+ return typeof value === 'string' ? value : ''
+}
+
+/** `tool_calls` JSON text → Claude `tool_use` blocks (tool ids mapped to the shared vocabulary). */
+function toolUseBlocks(toolCalls: string | null): unknown[] {
+ if (!toolCalls) return []
+ let parsed: unknown
+ try { parsed = JSON.parse(toolCalls) } catch { return [] }
+ if (!Array.isArray(parsed)) return []
+ return parsed.flatMap((entry) => {
+ const call = object(entry)
+ if (!call) return []
+ const name = str(call.name)
+ return [{
+ type: 'tool_use',
+ id: str(call.id) || `devin-${str(call.index)}`,
+ name: devinToolName(name),
+ input: object(call.arguments) ?? {},
+ }]
+ })
+}
+
+/**
+ * One Devin row → one Claude-shaped raw line (or null for system prefix / unknown roles).
+ * Exported for tests; the live reader and the replay/recap helpers all funnel through it.
+ */
+export function reshapeMessage(msg: DvMessage): string | null {
+ const common = { uuid: msg.messageId, timestamp: undefined }
+
+ if (msg.role === 'user') {
+ return JSON.stringify({
+ ...common,
+ type: 'user',
+ message: { role: 'user', content: [{ type: 'text', text: msg.content }] },
+ })
+ }
+ // A tool result is a role:"user" message carrying only a tool_result block — Claude's path turns that
+ // into tool_end and never mistakes it for a prompt.
+ if (msg.role === 'tool') {
+ if (!msg.toolCallId) return null
+ return JSON.stringify({
+ ...common,
+ type: 'user',
+ message: {
+ role: 'user',
+ content: [{
+ type: 'tool_result',
+ tool_use_id: msg.toolCallId,
+ content: [{ type: 'text', text: msg.content }],
+ }],
+ },
+ })
+ }
+ if (msg.role === 'assistant') {
+ const content: unknown[] = []
+ if (msg.thinking) content.push({ type: 'thinking', thinking: msg.thinking, signature: '' })
+ if (msg.content) content.push({ type: 'text', text: msg.content })
+ content.push(...toolUseBlocks(msg.toolCalls))
+ return JSON.stringify({
+ ...common,
+ type: 'assistant',
+ message: {
+ role: 'assistant',
+ content,
+ stop_reason: msg.finishReason === 'tool_calls' ? 'tool_use' : 'end_turn',
+ },
+ })
+ }
+ return null // system prefix, and any future role
+}
+
+function reshapeAll(messages: DvMessage[]): string[] {
+ const out: string[] = []
+ for (const msg of messages) {
+ const line = reshapeMessage(msg)
+ if (line) out.push(line)
+ }
+ return out
+}
+
+/** Live path: one row → events, advancing the shared Claude turn state. */
+export function devinMessageToEvents(msg: DvMessage, state: TurnState): LiveEvent[] {
+ const line = reshapeMessage(msg)
+ return line ? lineToEvents(line, state) : []
+}
+
+/** True when this row closes the turn (assistant finished without calling tools). */
+export function isDevinTurnEnd(msg: DvMessage): boolean {
+ return msg.role === 'assistant' && msg.finishReason !== 'tool_calls'
+}
+
+/** Full-session replay (session_get) — same render path as the live stream. */
+export function devinMessagesToEvents(messages: DvMessage[]): SessionEvent[] {
+ return messagesToEvents(reshapeAll(messages))
+}
+
+/** Last user prompt + the assistant text that followed it — the recap source of truth. */
+export function lastDevinTurnText(messages: DvMessage[]): LastTurnText | null {
+ return lastTurnTextFromRawLines(reshapeAll(messages))
+}
+
+/**
+ * Turn-snapped pagination window for `session_get {limit, before}`; cursor `devin:<index>`.
+ * The window start snaps back to a user prompt so a turn is never split (replay is stateful: a
+ * tool_use's name must still be known when its tool_result renders).
+ */
+export function windowDevinMessages(
+ messages: DvMessage[],
+ opts: { limit: number; before?: string },
+): { window: DvMessage[]; hasMore: boolean; oldestCursor: string | null; staleCursor?: boolean } {
+ let endIndex = messages.length
+ if (opts.before) {
+ const match = /^devin:(\d+)$/.exec(opts.before)
+ if (!match) return { window: [], hasMore: false, oldestCursor: null, staleCursor: true }
+ endIndex = Number(match[1])
+ if (!Number.isSafeInteger(endIndex) || endIndex < 0 || endIndex > messages.length) {
+ return { window: [], hasMore: false, oldestCursor: null, staleCursor: true }
+ }
+ }
+ let start = Math.max(0, endIndex - opts.limit)
+ while (start > 0 && messages[start].role !== 'user') start--
+ return {
+ window: messages.slice(start, endIndex),
+ hasMore: start > 0,
+ oldestCursor: `devin:${start}`,
+ }
+}
diff --git a/cli/src/engines/devin/reader.spec.ts b/cli/src/engines/devin/reader.spec.ts
new file mode 100644
index 000000000..8313b277a
--- /dev/null
+++ b/cli/src/engines/devin/reader.spec.ts
@@ -0,0 +1,127 @@
+import { afterEach, describe, expect, it } from 'vitest'
+import { execFileSync } from 'child_process'
+import { appendFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
+import { join } from 'path'
+import { tmpdir } from 'os'
+import { DevinReader, readDevinMessages } from './reader.js'
+
+/**
+ * Integration test for the turn-close path, driven through a real `sqlite3` DB and a real log file —
+ * because the failure mode being guarded is precisely the one where NO new row and NO Stop hook arrive.
+ */
+const AGENT_ERROR = "2026-07-28T06:38:22.096212Z WARN chisel_core::translator: ACP: agent error (Internal):"
+ + " Permission denied: Permission denied: We're currently facing high demand for this model."
+ + " Please try again later. (trace ID: acb60788b786ddfb16a00ddb3d83b053)"
+
+const dirs: string[] = []
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })
+
+function sql(db: string, statement: string): void {
+ execFileSync('sqlite3', [db, statement])
+}
+
+interface Fixture { db: string; home: string; log: string; sessionId: string }
+
+function fixture(sessionId = 'tested-crabapple'): Fixture {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-devin-reader-'))
+ dirs.push(dir)
+ const db = join(dir, 'sessions.db')
+ sql(db, `CREATE TABLE message_nodes (
+ row_id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, node_id INTEGER NOT NULL,
+ parent_node_id INTEGER, chat_message TEXT NOT NULL, created_at INTEGER NOT NULL, metadata TEXT);`)
+
+ const home = join(dir, 'devin')
+ mkdirSync(join(home, 'session_locks'), { recursive: true })
+ mkdirSync(join(home, 'logs'), { recursive: true })
+ writeFileSync(join(home, 'session_locks', `${sessionId}.lock`), '39022')
+ const log = join(home, 'logs', 'devin_20260728-133808_39022.log')
+ writeFileSync(log, '')
+ return { db, home, log, sessionId }
+}
+
+let node = 0
+function insert(f: Fixture, message: Record<string, unknown>): void {
+ const json = JSON.stringify(message).replace(/'/g, "''")
+ sql(f.db, `INSERT INTO message_nodes (session_id, node_id, chat_message, created_at)
+ VALUES ('${f.sessionId}', ${node++}, '${json}', 0);`)
+}
+
+const userRow = (id: string, text: string, at = '2026-07-28T06:38:21.000000Z') =>
+ ({ message_id: id, role: 'user', content: text, metadata: { created_at: at } })
+
+const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
+
+describe('DevinReader turn close', () => {
+ it('deduplicates the repeated rows Devin writes per inference', async () => {
+ const f = fixture()
+ const user = userRow('m-user', 'hi')
+ insert(f, user)
+ insert(f, user) // Devin re-persists the whole chain on the next inference
+ insert(f, { message_id: 'm-asst', role: 'assistant', content: 'hello', metadata: { finish_reason: 'stop' } })
+ insert(f, { message_id: 'm-sys', role: 'system', content: 'You are Devin' })
+
+ const messages = await readDevinMessages(f.db, f.sessionId)
+ expect(messages.map((m) => m.messageId)).toEqual(['m-user', 'm-asst'])
+ })
+
+ it('closes a turn that dies mid-flight, with no new row and no Stop hook', async () => {
+ const f = fixture()
+ const aborted: string[] = []
+ const reader = new DevinReader({
+ dbPath: f.db, devinHome: f.home, sessionId: f.sessionId, pollMs: 30,
+ onEvents: () => {},
+ onTurnAborted: (message) => aborted.push(message),
+ })
+ await reader.start()
+
+ insert(f, userRow('m-1', 'gia btc moi nhat di'))
+ await wait(150)
+ expect(reader.turnOpen).toBe(true) // the user row opened the turn
+
+ appendFileSync(f.log, AGENT_ERROR + '\n') // provider failure — Devin writes nothing else, ever
+ await wait(150)
+ reader.stop()
+
+ expect(aborted).toEqual([
+ "Permission denied: We're currently facing high demand for this model. Please try again later.",
+ ])
+ expect(reader.turnOpen).toBe(false)
+ })
+
+ it('heals a turn that was already stuck when it attached', async () => {
+ const f = fixture()
+ insert(f, userRow('m-1', 'gia btc moi nhat di'))
+ appendFileSync(f.log, AGENT_ERROR + '\n') // failed before the daemon (re)started
+
+ const aborted: string[] = []
+ const reader = new DevinReader({
+ dbPath: f.db, devinHome: f.home, sessionId: f.sessionId, pollMs: 30,
+ onEvents: () => {},
+ onTurnAborted: (message) => aborted.push(message),
+ })
+ await reader.start()
+ reader.stop()
+
+ expect(aborted).toHaveLength(1)
+ expect(reader.turnOpen).toBe(false)
+ })
+
+ it('leaves a healthy in-flight turn alone when the log only holds an older failure', async () => {
+ const f = fixture()
+ appendFileSync(f.log, AGENT_ERROR + '\n') // 06:38:22 — BEFORE this turn's prompt
+ insert(f, userRow('m-1', 'a fresh prompt', '2026-07-28T07:00:00.000000Z'))
+
+ const aborted: string[] = []
+ const reader = new DevinReader({
+ dbPath: f.db, devinHome: f.home, sessionId: f.sessionId, pollMs: 30,
+ onEvents: () => {},
+ onTurnAborted: (message) => aborted.push(message),
+ })
+ await reader.start()
+ await wait(120)
+ reader.stop()
+
+ expect(aborted).toEqual([])
+ expect(reader.turnOpen).toBe(true) // still running — must not be force-closed
+ })
+})
diff --git a/cli/src/engines/devin/reader.ts b/cli/src/engines/devin/reader.ts
new file mode 100644
index 000000000..fbf689771
--- /dev/null
+++ b/cli/src/engines/devin/reader.ts
@@ -0,0 +1,225 @@
+/**
+ * Devin CLI live tailer.
+ *
+ * Devin keeps every session's history in ONE SQLite store (`<DEVIN_HOME>/sessions.db`, WAL) and writes no
+ * transcript file unless the user passes `--export`, so there is nothing to byte-offset-tail. This polls
+ * the DB every ~1s through the `sqlite3` CLI (shelled out, like tmux/git — keeps the adapter's single
+ * pure-JS bundle; no native SQLite dependency) and feeds the same `emitSessionEvents` funnel the
+ * file-based engines use. Same shape as the opencode/hermes readers.
+ *
+ * Two Devin specifics:
+ * - **The store is WAL.** The DB must be read IN PLACE (`file:…?mode=ro`), never from a copy of
+ * `sessions.db` alone — a copy misses everything still in `-wal` (an in-flight session looks empty).
+ * - **Rows repeat.** `message_nodes` is a forest and Devin re-persists the whole chain per inference, so
+ * `row_id` alone is not a safe cursor. `row_id` drives the incremental read, `message_id` deduplicates:
+ * 29 raw rows collapsed to 6 real messages in the captured session.
+ */
+
+import { execFile } from 'child_process'
+import { promisify } from 'util'
+import type { LiveEvent, TurnState } from '../../lib/normalize.js'
+import { newTurnState } from '../../lib/normalize.js'
+import { devinMessageToEvents, type DvMessage } from './normalizer.js'
+import { DevinErrorTail } from './errorLog.js'
+
+const execFileAsync = promisify(execFile)
+
+// Devin session ids are lowercase word slugs (`blue-agustinia`, `classy-tourmaline`). Strict, because the
+// id is interpolated into SQL.
+const SESSION_ID_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
+const MAX_SESSION_ID_LEN = 64
+const POLL_MS = 1_000
+const MAX_BUFFER = 32 * 1024 * 1024
+
+const COLUMNS = [
+ 'row_id',
+ "json_extract(chat_message, '$.message_id') AS message_id",
+ "json_extract(chat_message, '$.role') AS role",
+ "coalesce(json_extract(chat_message, '$.content'), '') AS content",
+ "json_extract(chat_message, '$.thinking.thinking') AS thinking",
+ "json_extract(chat_message, '$.tool_calls') AS tool_calls",
+ "json_extract(chat_message, '$.tool_call_id') AS tool_call_id",
+ "json_extract(chat_message, '$.metadata.finish_reason') AS finish_reason",
+ "json_extract(chat_message, '$.metadata.created_at') AS created_at",
+].join(', ')
+
+export class DevinSqliteMissing extends Error {
+ constructor() { super('sqlite3 CLI not found on PATH — Devin sessions cannot be mirrored') }
+}
+
+function str(value: unknown): string | null {
+ return typeof value === 'string' && value ? value : null
+}
+
+export function isDevinSessionId(sessionId: string): boolean {
+ return sessionId.length <= MAX_SESSION_ID_LEN && SESSION_ID_RE.test(sessionId)
+}
+
+/**
+ * Read a Devin session's messages, optionally only those after `afterRowId`, deduped by `message_id`
+ * (first occurrence wins) and with the system prefix dropped.
+ * Throws `DevinSqliteMissing` when the `sqlite3` binary is absent; returns [] on a transient error.
+ */
+export async function readDevinMessages(
+ dbPath: string,
+ sessionId: string,
+ afterRowId?: number | null,
+): Promise<DvMessage[]> {
+ if (!isDevinSessionId(sessionId)) return []
+ const after = Number.isFinite(afterRowId as number) && (afterRowId as number) > 0
+ ? ` AND row_id > ${Math.trunc(afterRowId as number)}`
+ : ''
+ const sql = `SELECT ${COLUMNS} FROM message_nodes WHERE session_id = '${sessionId}'${after}`
+ + " AND json_extract(chat_message, '$.role') <> 'system' ORDER BY row_id;"
+
+ let stdout: string
+ try {
+ // `.timeout` is the SILENT dot-command form — `PRAGMA busy_timeout=…` prints a row under -json and
+ // would corrupt the single-array parse below. `query_only` is silent and guards against writes.
+ ;({ stdout } = await execFileAsync(
+ 'sqlite3',
+ ['-json', '-cmd', '.timeout 3000', '-cmd', 'PRAGMA query_only=1', `file:${dbPath}?mode=ro`, sql],
+ { maxBuffer: MAX_BUFFER },
+ ))
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') throw new DevinSqliteMissing()
+ return [] // db locked / mid-write — retry next tick
+ }
+
+ const trimmed = stdout.trim()
+ if (!trimmed) return []
+ let rows: Array<Record<string, unknown>>
+ try { rows = JSON.parse(trimmed) } catch { return [] }
+
+ const seen = new Set<string>()
+ const out: DvMessage[] = []
+ for (const row of rows) {
+ const messageId = str(row.message_id)
+ if (!messageId || seen.has(messageId)) continue
+ seen.add(messageId)
+ out.push({
+ rowId: Number(row.row_id) || 0,
+ messageId,
+ role: typeof row.role === 'string' ? row.role : '',
+ content: typeof row.content === 'string' ? row.content : '',
+ thinking: str(row.thinking),
+ toolCalls: str(row.tool_calls),
+ toolCallId: str(row.tool_call_id),
+ finishReason: str(row.finish_reason),
+ createdAt: str(row.created_at),
+ })
+ }
+ return out
+}
+
+export interface DevinReaderDeps {
+ dbPath: string
+ /** Devin state root — used to find this session's log for turn-failure detection. */
+ devinHome: string
+ sessionId: string
+ onEvents: (events: LiveEvent[]) => void
+ /**
+ * A turn died on a provider error. Devin writes no assistant row and fires no Stop hook for this, so
+ * without it the turn never closes and the web spins forever.
+ */
+ onTurnAborted?: (message: string) => void
+ /** Reports the one-time fatal "sqlite3 missing" so the caller can warn + stop the reader. */
+ onFatal?: (err: Error) => void
+ pollMs?: number
+}
+
+export class DevinReader {
+ private timer: NodeJS.Timeout | null = null
+ private polling = false
+ private cursor = 0
+ /** message_ids already emitted — survives across polls, unlike readDevinMessages' per-call dedupe. */
+ private readonly seen = new Set<string>()
+ private state: TurnState = newTurnState()
+ private lastMessageAt: string | null = null
+ private readonly errors: DevinErrorTail
+
+ constructor(private readonly deps: DevinReaderDeps) {
+ this.errors = new DevinErrorTail(deps.devinHome, deps.sessionId)
+ }
+
+ get turnOpen(): boolean { return this.state.turnOpen }
+ closeTurn(): void { this.state.turnOpen = false; this.state.pendingTools.clear() }
+
+ /** Hydrate silently (no replay), then start polling. */
+ async start(): Promise<void> {
+ try {
+ const all = await readDevinMessages(this.deps.dbPath, this.deps.sessionId)
+ this.hydrate(all)
+ } catch (err) {
+ if (err instanceof DevinSqliteMissing) { this.deps.onFatal?.(err); return }
+ }
+ this.errors.seekToEnd() // never replay a failure logged before we attached
+ // …except the one case where replaying matters: we attached to a turn that is ALREADY stuck open
+ // because it died before the daemon (re)started. Its failure is in the log but behind our offset, so
+ // look back explicitly — otherwise a restart leaves the web spinning exactly as it was.
+ this.healStuckTurn()
+ this.timer = setInterval(() => { void this.tick() }, this.deps.pollMs ?? POLL_MS)
+ }
+
+ stop(): void {
+ if (this.timer) { clearInterval(this.timer); this.timer = null }
+ }
+
+ /** Seed state from existing rows without emitting, so only NEW activity streams after attach. */
+ private hydrate(messages: DvMessage[]): void {
+ for (const msg of messages) {
+ this.cursor = Math.max(this.cursor, msg.rowId)
+ this.seen.add(msg.messageId)
+ devinMessageToEvents(msg, this.state) // advances turn/tool state; output discarded
+ }
+ // A trailing user row (or an assistant still calling tools) means we attached mid-turn.
+ const tail = messages[messages.length - 1]
+ if (!tail) return
+ this.lastMessageAt = tail.createdAt ?? null
+ this.state.turnOpen = tail.role === 'user'
+ || this.state.pendingTools.size > 0
+ || (tail.role === 'assistant' && tail.finishReason === 'tool_calls')
+ }
+
+ /** Close a turn that was already dead when we attached (failure logged before our offset). */
+ private healStuckTurn(): void {
+ if (!this.state.turnOpen || !this.lastMessageAt) return
+ const failures = this.errors.scanSince(this.lastMessageAt)
+ if (!failures.length) return
+ this.closeTurn()
+ this.deps.onTurnAborted?.(failures[failures.length - 1])
+ }
+
+ /**
+ * Drain the log tail every tick — even when idle, so a stale failure can never fire into the NEXT turn —
+ * but only act while a turn is actually open.
+ */
+ private checkTurnFailure(): void {
+ const failures = this.errors.poll()
+ if (!failures.length || !this.state.turnOpen) return
+ this.closeTurn()
+ this.deps.onTurnAborted?.(failures[failures.length - 1])
+ }
+
+ private async tick(): Promise<void> {
+ if (this.polling) return
+ this.polling = true
+ try {
+ const batch = await readDevinMessages(this.deps.dbPath, this.deps.sessionId, this.cursor)
+ const events: LiveEvent[] = []
+ for (const msg of batch) {
+ this.cursor = Math.max(this.cursor, msg.rowId)
+ if (this.seen.has(msg.messageId)) continue
+ this.seen.add(msg.messageId)
+ events.push(...devinMessageToEvents(msg, this.state))
+ }
+ if (events.length) this.deps.onEvents(events)
+ // NOT gated on `batch.length`: a failed turn is precisely the case where no new row ever arrives.
+ this.checkTurnFailure()
+ } catch (err) {
+ if (err instanceof DevinSqliteMissing) { this.stop(); this.deps.onFatal?.(err) }
+ } finally {
+ this.polling = false
+ }
+ }
+}
diff --git a/cli/src/engines/devin/runtimeProfile.spec.ts b/cli/src/engines/devin/runtimeProfile.spec.ts
new file mode 100644
index 000000000..01abbc399
--- /dev/null
+++ b/cli/src/engines/devin/runtimeProfile.spec.ts
@@ -0,0 +1,131 @@
+import { describe, expect, it } from 'vitest'
+import {
+ devinFooterModel,
+ devinModelCommandResult,
+ devinModelLabel,
+ parseDevinModelsOutput,
+ splitDevinModelId,
+} from './runtimeProfile.js'
+
+// Copied verbatim from `devin models list` on this computer (devin 3000.3.22) — families with efforts in
+// the id, a Fast tier, a "No Thinking" row, families with no effort at all, and an opaque upper-case id.
+const OUTPUT = [
+ 'Available models (38 families)',
+ '',
+ 'Claude Opus 5 (claude-opus-5)',
+ ' aliases: opus',
+ ' claude-opus-5-medium Claude Opus 5 Medium [$5 / MTok In · $25 / MTok Out]',
+ ' claude-opus-5-xhigh Claude Opus 5 XHigh [$5 / MTok In · $25 / MTok Out]',
+ ' claude-opus-5-max-fast Claude Opus 5 Max Fast [$10 / MTok In · $50 / MTok Out]',
+ '',
+ 'GPT-5.6 Sol (gpt-5.6-sol)',
+ ' gpt-5-6-sol-none GPT-5.6 Sol No Thinking [$5 / MTok In · $30 / MTok Out]',
+ ' gpt-5-6-sol-high GPT-5.6 Sol High Thinking [$5 / MTok In · $30 / MTok Out]',
+ '',
+ 'SWE-1.6 Slow (swe-1.6-slow)',
+ ' swe-1-6-slow SWE-1.6 Slow [200K context, $0.3 / MTok In · $1.5 / MTok Out]',
+ '',
+ 'Gemini 3 Flash (gemini-3-flash)',
+ ' MODEL_GOOGLE_GEMINI_3_0_FLASH_MINIMAL Gemini 3 Flash Minimal [$0.5 / MTok In · $3 / MTok Out]',
+].join('\n')
+
+describe('devin model catalog', () => {
+ it('splits the effort out of a model id, keeping Fast as part of the model', () => {
+ expect(splitDevinModelId('claude-opus-5-medium', 'claude-opus-5')).toEqual({
+ modelKey: 'claude-opus-5', effort: 'medium', fast: false,
+ })
+ expect(splitDevinModelId('claude-opus-5-max-fast', 'claude-opus-5')).toEqual({
+ modelKey: 'claude-opus-5-fast', effort: 'max', fast: true,
+ })
+ // `-priority` is the same premium tier as `-fast` on OpenAI families; missing it collapsed three
+ // distinct models onto one effort-less row when the parser guessed from the trailing token.
+ expect(splitDevinModelId('gpt-5-6-sol-low-priority', 'gpt-5.6-sol')).toEqual({
+ modelKey: 'gpt-5-6-sol-priority', effort: 'low', fast: true,
+ })
+ // `slow` is part of the family name, not an effort — the row must stay a single `auto` option.
+ expect(splitDevinModelId('swe-1-6-slow', 'swe-1.6-slow')).toEqual({
+ modelKey: 'swe-1-6-slow', effort: 'auto', fast: false,
+ })
+ // No family to anchor on (devin's opaque ids) → kept whole, applied verbatim.
+ expect(splitDevinModelId('MODEL_GOOGLE_GEMINI_3_0_FLASH_MINIMAL', 'gemini-3-flash')).toEqual({
+ modelKey: 'MODEL_GOOGLE_GEMINI_3_0_FLASH_MINIMAL', effort: 'auto', fast: false,
+ })
+ })
+
+ it('parses the catalog into model + effort, ignoring the header and alias lines', () => {
+ const targets = parseDevinModelsOutput(OUTPUT)
+
+ expect(targets.map((t) => `${t.label} / ${t.effort}`)).toEqual([
+ 'Claude Opus 5 / medium',
+ 'Claude Opus 5 / xhigh',
+ 'Claude Opus 5 Fast / max',
+ 'GPT-5.6 Sol / none',
+ 'GPT-5.6 Sol / high',
+ // No effort in the id → devin's own display is kept whole, which is what separates the variants
+ // it packs into one family (`GLM-5.2 High` vs `GLM-5.2 High 1M`).
+ 'SWE-1.6 Slow / auto',
+ 'Gemini 3 Flash Minimal / auto',
+ ])
+ // The model key follows the label, so effort never splits one model into two.
+ expect(targets.filter((t) => t.modelKey === 'claude-opus-5')).toHaveLength(2)
+ // The id is what `/model` is given, verbatim.
+ expect(targets.find((t) => t.effort === 'max')?.id).toBe('claude-opus-5-max-fast')
+ })
+
+ it('hoists only the effort the id proves, so a family named after one survives', () => {
+ // `Qwen 3.6 Max Preview` has no effort suffix in its id — "Max" is part of its name.
+ expect(devinModelLabel('Qwen 3.6 Max Preview', 'auto')).toBe('Qwen 3.6 Max Preview')
+ expect(devinModelLabel('GPT-5.6 Sol Low Thinking Fast', 'low')).toBe('GPT-5.6 Sol Fast')
+ expect(devinModelLabel('GPT-5.6 Sol No Thinking', 'none')).toBe('GPT-5.6 Sol')
+ expect(devinModelLabel('GLM-5.2 Max 1M', 'max')).toBe('GLM-5.2 1M')
+ // `Max` inside `MiniMax` is not a word of its own.
+ expect(devinModelLabel('MiniMax M3', 'auto')).toBe('MiniMax M3')
+ })
+
+ it('ignores rows that arrive before any family heading', () => {
+ expect(parseDevinModelsOutput(' orphan-row Orphan [x]\n')).toEqual([])
+ expect(parseDevinModelsOutput('Available models (38 families)\n')).toEqual([])
+ })
+
+ it('reads the outcome devin prints after /model', () => {
+ expect(devinModelCommandResult('❭ /model swe-1-6-slow\n✓ Model set to SWE-1.6 Slow')).toBe('ok')
+ expect(devinModelCommandResult('❭ /model adaptive\n✗ Model not available\n /upgrade to access this model'))
+ .toBe('unavailable')
+ expect(devinModelCommandResult('❭ Ask Devin to build features')).toBeNull()
+ })
+
+ it('reads the current model out of the footer, whichever hint it is showing', () => {
+ const pane = (hint: string) => [
+ '❭ Ask Devin to build features, fix bugs, or work on your code',
+ '─────────────────────────────────────',
+ `SWE-1.6 Slow ${hint}`,
+ '',
+ ].join('\n')
+
+ // The right-hand hint rotates, so it cannot anchor the read — both of these are real footers.
+ expect(devinFooterModel(pane('See all keyboard shortcuts: /shortcuts'))).toBe('SWE-1.6 Slow')
+ expect(devinFooterModel(pane('Type while the agent works to queue messages'))).toBe('SWE-1.6 Slow')
+ expect(devinFooterModel('')).toBeNull()
+ })
+
+ it('reads past an overlay that devin draws BELOW the footer', () => {
+ // Captured from a live pane with `/model` typed: the slash-command menu renders under the footer, so
+ // "the last non-empty line" was the menu, the label never resolved, and the chip stayed blank.
+ const pane = [
+ '❭ /model',
+ '─────────────────────────────────────',
+ 'SWE-1.6 Slow tab next · shift+tab prev · ↵ accept · esc close',
+ '● /model [adaptive|claude-fable-5|claude-haiku-4.5|...] - Interactively choose a model',
+ '',
+ ].join('\n')
+ // The menu line has no second cell; the footer's two-cell shape is what identifies it.
+ expect(devinFooterModel(pane)).toBe('SWE-1.6 Slow')
+ })
+
+ it('reads a footer straight off a raw capture, escape codes and all', () => {
+ // ingestPane strips ANSI before calling, but nothing enforces that on other callers — and a label
+ // carrying SGR codes matches no catalogue entry, which fails silently as "no model".
+ const raw = '\u001b[38;2;124;124;124mSWE-1.6 Slow\u001b[39m \u001b[2mesc close\u001b[0m'
+ expect(devinFooterModel(raw)).toBe('SWE-1.6 Slow')
+ })
+})
diff --git a/cli/src/engines/devin/runtimeProfile.ts b/cli/src/engines/devin/runtimeProfile.ts
new file mode 100644
index 000000000..966d6210b
--- /dev/null
+++ b/cli/src/engines/devin/runtimeProfile.ts
@@ -0,0 +1,194 @@
+/**
+ * Devin model catalog → runtime-profile options.
+ *
+ * `devin models list` prints the account's whole catalog on stdout, grouped by family — no TUI scraping
+ * needed, which makes it the sturdiest of the five late engines:
+ *
+ * Available models (38 families)
+ *
+ * Claude Opus 5 (claude-opus-5)
+ * aliases: opus
+ * claude-opus-5-medium Claude Opus 5 Medium [$5 / MTok In · $25 / MTok Out]
+ * claude-opus-5-max-fast Claude Opus 5 Max Fast [$10 / MTok In · $50 / MTok Out]
+ * GPT-5.6 Sol (gpt-5.6-sol)
+ * gpt-5-6-sol-none GPT-5.6 Sol No Thinking […]
+ *
+ * Two things make it fit the existing vocabulary almost unchanged (verified live, devin 3000.3.22):
+ *
+ * - **Effort is baked into the model id** (`-low|-medium|-high|-xhigh|-max|-none`, optionally trailed by
+ * `-fast`) — exactly cursor's scheme, so a family + an effort is the natural split and the id is
+ * reconstructed at apply time from `DevinModelTarget.id`.
+ * - **Applying is a one-liner**: `/model <id>` takes the id directly and answers in the pane with
+ * `✓ Model set to <Display Name>` or `✗ Model not available`, so there is no picker to drive.
+ *
+ * A family whose id carries no effort token (`adaptive`, `swe-1-6-slow`, and the opaque
+ * `MODEL_GOOGLE_GEMINI_3_0_FLASH_MINIMAL`) is offered as a single `auto` row.
+ */
+
+/** Effort levels devin encodes in a model id. `none` is its "No Thinking" row. */
+export const DEVIN_EFFORTS = new Set(['auto', 'none', 'low', 'medium', 'high', 'xhigh', 'max'])
+
+export interface DevinModelTarget {
+ /** Exact argument for `/model <id>` — e.g. `claude-opus-5-max-fast`. */
+ id: string
+ /** Identity of the model itself, effort removed: `claude-opus-5`, or `claude-opus-5-fast`. */
+ modelKey: string
+ /** Human label without the effort words: `Claude Opus 5`, `Claude Opus 5 Fast`. */
+ label: string
+ effort: string
+}
+
+const FAMILY_RE = /^(\S.*?)\s+\(([^()\s]+)\)\s*$/
+const ROW_RE = /^\s{2,}(\S+)\s{2,}(.+?)\s*$/
+const EFFORT_TOKENS = new Set(['none', 'low', 'medium', 'high', 'xhigh', 'max'])
+/** Suffixes devin appends for its premium-throughput tier; both render as "Fast" in the display name. */
+const FAST_TOKENS = new Set(['fast', 'priority'])
+
+/**
+ * Split a devin model id into the model's own identity and its effort, using the family slug from the
+ * heading as the anchor.
+ *
+ * Anchoring matters: guessing from the trailing token alone broke on the real catalog. `-fast` is not the
+ * only modifier — OpenAI families use `-priority` for the same tier (`gpt-5-6-sol-low-priority`,
+ * displayed "GPT-5.6 Sol Low Thinking Fast") — so a naive rule read three distinct models as one
+ * effort-less row. Conversely a family can legitimately end in something that merely looks like a
+ * modifier (`swe-1.6-slow`). Stripping the known family prefix first removes both guesses.
+ *
+ * Without a usable family (devin also emits opaque ids like `MODEL_GOOGLE_GEMINI_3_0_FLASH_MINIMAL`) the
+ * id is kept whole at `auto`, which is the safe reading: one row, applied verbatim.
+ */
+export function splitDevinModelId(
+ id: string,
+ familySlug?: string | null,
+): { modelKey: string; effort: string; fast: boolean } {
+ const family = familySlug ? familySlug.replace(/\./g, '-') : ''
+ if (family && id !== family && id.startsWith(`${family}-`)) {
+ return split(family, id.slice(family.length + 1).split('-'))
+ }
+ if (family && id === family) return { modelKey: id, effort: 'auto', fast: false }
+
+ // The slug does not always prefix its own ids — devin reorders words in some families
+ // (`Claude Fable 5 (claude-fable-5)` numbers its models `claude-5-fable-medium`). Falling back to a
+ // trailing-token read keeps those families split by effort; without it all five rows collapsed onto one
+ // `auto` key and four of the five options vanished as duplicates.
+ const parts = id.split('-')
+ const trailingFast = parts.length > 1 && FAST_TOKENS.has(parts[parts.length - 1].toLowerCase())
+ const head = trailingFast ? parts.slice(0, -1) : parts
+ const last = head[head.length - 1]?.toLowerCase() ?? ''
+ if (head.length > 1 && EFFORT_TOKENS.has(last)) {
+ return split(head.slice(0, -1).join('-'), [last, ...(trailingFast ? [parts[parts.length - 1]] : [])])
+ }
+ return { modelKey: id, effort: 'auto', fast: trailingFast }
+}
+
+function split(family: string, suffix: string[]): { modelKey: string; effort: string; fast: boolean } {
+ const effortAt = suffix.findIndex((token) => EFFORT_TOKENS.has(token.toLowerCase()))
+ const modifiers = suffix.filter((_, index) => index !== effortAt)
+ return {
+ modelKey: modifiers.length ? `${family}-${modifiers.join('-')}` : family,
+ effort: effortAt >= 0 ? suffix[effortAt].toLowerCase() : 'auto',
+ fast: modifiers.some((token) => FAST_TOKENS.has(token.toLowerCase())),
+ }
+}
+
+/**
+ * Parse `devin models list`. Rows outside a family block, the `aliases:` lines and the header are ignored;
+ * a malformed line can only cost its own row.
+ */
+export function parseDevinModelsOutput(output: string): DevinModelTarget[] {
+ const targets: DevinModelTarget[] = []
+ const seen = new Set<string>()
+ let family: { label: string; slug: string } | null = null
+
+ for (const rawLine of output.split('\n')) {
+ if (!rawLine.trim()) continue
+ if (!/^\s/.test(rawLine)) {
+ // Column-0 lines are family headings; the counter line ("Available models (38 families)") looks like
+ // one too, so it is dropped by the slug shape below.
+ const heading = FAMILY_RE.exec(rawLine)
+ family = heading && /^[a-z0-9][a-z0-9._-]*$/i.test(heading[2])
+ ? { label: heading[1], slug: heading[2] }
+ : null
+ continue
+ }
+ if (!family) continue
+ if (/^\s*aliases:/i.test(rawLine)) continue
+ const row = ROW_RE.exec(rawLine)
+ if (!row) continue
+ const id = row[1]
+ const display = row[2].replace(/\s*\[[^\]]*\]\s*$/, '').trim()
+ const { effort } = splitDevinModelId(id, family.slug)
+ if (seen.has(id)) continue
+ seen.add(id)
+ const label = devinModelLabel(display || family.label, effort)
+ targets.push({ id, modelKey: slug(label), label, effort })
+ }
+ return targets
+}
+
+const EFFORT_WORDS: Record<string, string> = {
+ none: '(?:No\\s+Thinking|None)',
+ low: 'Low',
+ medium: 'Medium',
+ high: 'High',
+ xhigh: 'XHigh',
+ max: 'Max',
+}
+
+/**
+ * The model's human name, taken from devin's own display column with the effort hoisted out — so
+ * `GPT-5.6 Sol Low Thinking Fast` at effort `low` reads `GPT-5.6 Sol Fast`.
+ *
+ * The display, not the family heading, is what distinguishes the variants devin packs into one family:
+ * `GLM-5.2 High`, `GLM-5.2 Max`, `GLM-5.2 High 1M` all sit under "GLM-5.2", and labelling them by family
+ * left three rows that read identically. Only the effort word the *id* proved is removed, which is what
+ * keeps a family genuinely named after one (`Qwen 3.6 Max Preview`) intact.
+ */
+export function devinModelLabel(display: string, effort: string): string {
+ const word = EFFORT_WORDS[effort]
+ if (!word) return display
+ return display
+ .replace(new RegExp(`\\b${word}\\b(?:\\s+Thinking)?`, 'i'), ' ')
+ .replace(/\s{2,}/g, ' ')
+ .trim() || display
+}
+
+function slug(label: string): string {
+ return label.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || label
+}
+
+/** The `✓ Model set to <name>` / `✗ Model not available` line devin prints after `/model <id>`. */
+export function devinModelCommandResult(capture: string): 'ok' | 'unavailable' | null {
+ if (/✗\s*Model not available/i.test(capture)) return 'unavailable'
+ if (/✓\s*Model set to\s+\S/i.test(capture)) return 'ok'
+ return null
+}
+
+/**
+ * Model shown in devin's idle footer — the bottom-left cell, e.g. `SWE-1.6 Slow`. It is the only
+ * per-session record of the current model (the ATIF transcript only exists with `--export`), so it is what
+ * `ingestPane` observes and what confirms an applied profile.
+ */
+export function devinFooterModel(capture: string): string | null {
+ const lines = capture
+ .replace(/\u001b\[[0-9;:]*[A-Za-z]/g, '') // defensive: callers strip ANSI, a raw capture would not match
+ .split('\n')
+ .map((line) => line.replace(/\s+$/, ''))
+ // Scan UP, and require the footer's shape. Taking the last non-empty line was wrong: devin renders its
+ // slash-command menu BELOW the footer, so with `/model` open the "footer" read as
+ // "● /model [adaptive|…] - Interactively choose a model", and nothing resolved.
+ for (let i = lines.length - 1, scanned = 0; i >= 0 && scanned < 12; i--) {
+ const line = lines[i]
+ if (!line.trim()) continue
+ scanned++
+ if (/^[─—\-]+$/.test(line.trim())) continue // the rule above the footer
+ // The footer is one row of TWO cells separated by padding: the model on the left, a hint on the right.
+ // The hint ROTATES ("See all keyboard shortcuts…", "Type while the agent works…"), so it cannot be the
+ // anchor — the two-cell structure is, and it is also what tells the footer apart from an overlay line.
+ // A left cell that names no known model is rejected upstream, in devinModelKeyForLabel.
+ const cells = line.split(/\s{3,}/).map((cell) => cell.trim()).filter(Boolean)
+ if (cells.length < 2) continue
+ return cells[0] || null
+ }
+ return null
+}
diff --git a/cli/src/engines/hermes/delegation.spec.ts b/cli/src/engines/hermes/delegation.spec.ts
new file mode 100644
index 000000000..c0ae0238d
--- /dev/null
+++ b/cli/src/engines/hermes/delegation.spec.ts
@@ -0,0 +1,121 @@
+import { describe, expect, it } from 'vitest'
+import { execFileSync } from 'child_process'
+import { mkdtempSync, readFileSync, rmSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import { fileURLToPath } from 'url'
+import { lastHermesTurnText, messageToEvents, newHermesTurnState, type HmMessage } from './normalizer.js'
+import { hermesSessionSource, isHermesSubagentSession } from './reader.js'
+import type { LiveEvent } from '../../lib/normalize.js'
+
+/**
+ * The six real `messages` rows of one hermes async fan-out (state.db, session 20260731_161017_999143,
+ * ids 284–306): prompt → `delegate_task` with TWO tasks → dispatch ack → "đã launch" → the machine-written
+ * `[ASYNC DELEGATION BATCH COMPLETE — deleg_3c9f8264]` row → the consolidated answer.
+ */
+function rows(): HmMessage[] {
+ const p = fileURLToPath(new URL('../../lib/__fixtures__/hermes-async-delegation.json', import.meta.url))
+ return JSON.parse(readFileSync(p, 'utf-8')) as HmMessage[]
+}
+
+function live(): LiveEvent[] {
+ const state = newHermesTurnState()
+ return rows().flatMap((m) => messageToEvents(m, state, 'live'))
+}
+
+describe('hermes async delegation', () => {
+ it('fans ONE delegate_task call out to one row per task, each with its goal', () => {
+ // Before this, two parallel sub-agents arrived as a single card whose only string was the tool name,
+ // so the device list showed one row labelled "sub-agent" for the pair.
+ const starts = live().filter((e): e is Extract<LiveEvent, { type: 'tool_start' }> =>
+ e.type === 'tool_start' && e.payload.tool === 'Task')
+ expect(starts).toHaveLength(2)
+ const descs = starts.map((e) => String((e.payload.input as { description: string }).description))
+ expect(descs[0]).toContain('.md')
+ expect(descs[1]).toContain('.ts')
+ // Distinct ids, or the second row would collapse onto the first.
+ expect(new Set(starts.map((e) => (e.payload as { id: string }).id)).size).toBe(2)
+ })
+
+ it('does not tick the rows off on the dispatch ack', () => {
+ // The ack is {"status":"dispatched","mode":"background",…} — the same trap as claude's launch ack.
+ const events = live()
+ const ackIndex = events.findIndex((e) => e.type === 'tool_end')
+ expect(ackIndex).toBeGreaterThan(-1)
+ expect(events.slice(0, ackIndex + 1).some((e) => e.type === 'subagent_finished')).toBe(false)
+ // …and the ack's own id is not one of the rows, so nothing downstream can match it either.
+ const rowIds = new Set(events.filter((e) => e.type === 'tool_start').map((e) => (e.payload as { id: string }).id))
+ expect(rowIds.has((events[ackIndex].payload as { id: string }).id)).toBe(false)
+ })
+
+ it('finishes both rows off the batch-complete row, which starts no turn', () => {
+ const events = live()
+ const finished = events.filter((e) => e.type === 'subagent_finished')
+ expect(finished).toHaveLength(2)
+ expect(finished.every((e) => (e.payload as { status: string }).status === 'completed')).toBe(true)
+ const rowIds = events.filter((e) => e.type === 'tool_start').map((e) => (e.payload as { id: string }).id)
+ expect(finished.map((e) => (e.payload as { id: string }).id)).toEqual(rowIds)
+ // ONE turn — the user's. The batch-complete row used to open a second one.
+ const starts = events.filter((e) => e.type === 'turn_started')
+ expect(starts).toHaveLength(1)
+ expect(String((starts[0].payload as { userMessage: string }).userMessage)).not.toContain('ASYNC DELEGATION')
+ })
+
+ it('recaps the answer to what was ASKED, not the batch-complete boilerplate', () => {
+ // Measured before the fix: `[recap] 20260731 summarizing · ask="[ASYNC DELEGATION BATCH COMPLETE …"`.
+ const turn = lastHermesTurnText(rows())
+ expect(turn?.userMessage).toContain('sub-agent SONG SONG')
+ expect(turn?.userMessage).not.toContain('ASYNC DELEGATION')
+ expect(turn?.assistantText).toContain('Tổng hợp kết quả từ 2 sub-agent')
+ })
+
+ it('closes the rows immediately when the dispatch is foreground or fails', () => {
+ const state = newHermesTurnState()
+ const events = [
+ { id: 1, role: 'user', content: 'go', toolCallId: null, toolCalls: null, toolName: null, finishReason: null, reasoning: null },
+ {
+ id: 2, role: 'assistant', content: '', toolCallId: null, toolName: null, finishReason: 'tool_calls', reasoning: null,
+ toolCalls: JSON.stringify([{ id: 'call_x', type: 'function', function: { name: 'delegate_task', arguments: JSON.stringify({ tasks: [{ goal: 'A' }, { goal: 'B' }] }) } }]),
+ },
+ { id: 3, role: 'tool', content: '{"status":"completed","mode":"foreground","count":2}', toolCallId: 'call_x', toolCalls: null, toolName: 'delegate_task', finishReason: null, reasoning: null },
+ ].flatMap((m) => messageToEvents(m as HmMessage, state, 'live'))
+ // No batch-complete row is coming for a foreground run, so nothing else could ever close these rows —
+ // left open they would hold the turn's recap until the 10-minute backstop.
+ expect(events.filter((e) => e.type === 'subagent_finished')).toHaveLength(2)
+ })
+
+ it('keeps the batch-complete row out of history replay too', () => {
+ const state = newHermesTurnState()
+ const replay = rows().flatMap((m) => messageToEvents(m, state, 'replay'))
+ const prompts = replay.filter((e) => e.type === 'user_message').map((e) => String((e.payload as { content: string }).content))
+ expect(prompts).toHaveLength(1)
+ expect(prompts[0]).not.toContain('ASYNC DELEGATION')
+ })
+})
+
+describe('hermes sub-agent sessions are not agents of their own', () => {
+ const has = (() => { try { execFileSync('sqlite3', ['-version'], { stdio: 'ignore' }); return true } catch { return false } })()
+ const t = has ? it : it.skip
+
+ t('tells a delegation child (source=subagent) from the CLI session the user sees', async () => {
+ // Measured: dispatching 2 sub-agents created sessions with source='subagent' whose hooks fired from
+ // the PARENT's pane, so the pane re-bound to them and the parent was `forgotten` mid-turn.
+ const dir = mkdtempSync(join(tmpdir(), 'hm-src-'))
+ const db = join(dir, 'state.db')
+ execFileSync('sqlite3', [db,
+ 'CREATE TABLE sessions (id TEXT PRIMARY KEY, source TEXT NOT NULL);' +
+ "INSERT INTO sessions VALUES ('20260805_111618_8e3027','subagent');" +
+ "INSERT INTO sessions VALUES ('20260805_110520_3e0e44','tool');" +
+ "INSERT INTO sessions VALUES ('20260731_161017_999143','cli');"])
+ expect(await isHermesSubagentSession(db, '20260805_111618_8e3027')).toBe(true)
+ expect(await isHermesSubagentSession(db, '20260805_110520_3e0e44')).toBe(true)
+ expect(await isHermesSubagentSession(db, '20260731_161017_999143')).toBe(false)
+ expect(await isHermesSubagentSession(db, '20260101_000000_abcdef')).toBe(false) // unknown id → not a child
+ // …but the caller can tell "no row YET" from "row says cli" — that distinction is what closes the
+ // 110ms window in which a child's hook arrives before hermes has written its own sessions row.
+ expect(await hermesSessionSource(db, '20260101_000000_abcdef')).toBeNull()
+ expect(await hermesSessionSource(db, '20260731_161017_999143')).toBe('cli')
+ expect(await isHermesSubagentSession(join(dir, 'nope.db'), '20260805_111618_8e3027')).toBe(false)
+ rmSync(dir, { recursive: true, force: true })
+ })
+})
diff --git a/cli/src/engines/hermes/normalizer.spec.ts b/cli/src/engines/hermes/normalizer.spec.ts
new file mode 100644
index 000000000..29569521a
--- /dev/null
+++ b/cli/src/engines/hermes/normalizer.spec.ts
@@ -0,0 +1,163 @@
+import { describe, expect, it } from 'vitest'
+import {
+ clarifyAsQuestions,
+ hermesMessagesToEvents,
+ hermesToolName,
+ isTerminalFinish,
+ lastHermesTurnText,
+ messageToEvents,
+ newHermesTurnState,
+ parseToolCalls,
+ toolResultText,
+ windowHermesMessages,
+ type HmMessage,
+} from './normalizer.js'
+
+function msg(partial: Partial<HmMessage> & { id: number; role: string }): HmMessage {
+ return {
+ content: '', toolCallId: null, toolCalls: null, toolName: null, finishReason: null, reasoning: null,
+ ...partial,
+ }
+}
+
+// Rows copied from a REAL local Hermes session (hermes 0.19.0, schema v23, provider vibe / minimax-m3).
+const CALL_ID = 'call_ba1647ad979d0290'
+const ROWS: HmMessage[] = [
+ msg({ id: 21, role: 'user', content: 'Use your terminal tool to run exactly: ls. Then reply with just DONE.' }),
+ msg({
+ id: 22,
+ role: 'assistant',
+ finishReason: 'tool_calls',
+ reasoning: 'The user wants a directory listing.',
+ toolCalls: `[{"id":"${CALL_ID}","call_id":"${CALL_ID}","response_item_id":"fc_x","type":"function","function":{"name":"terminal","arguments":"{\\"command\\":\\"ls\\"}"}}]`,
+ }),
+ msg({
+ id: 23,
+ role: 'tool',
+ toolName: 'terminal',
+ toolCallId: CALL_ID,
+ content: '{"output": "a.txt\\nb.txt", "exit_code": 0, "error": null}',
+ }),
+ msg({ id: 24, role: 'assistant', content: 'DONE', finishReason: 'stop' }),
+]
+
+function live(rows: HmMessage[]) {
+ const state = newHermesTurnState()
+ const events = rows.flatMap((row) => messageToEvents(row, state, 'live'))
+ return { state, events }
+}
+
+describe('Hermes normalizer — live turn derivation', () => {
+ it('derives the turn lifecycle from role + finish_reason (Hermes stores no turn markers)', () => {
+ const { state, events } = live(ROWS)
+ expect(events.map((e) => e.type)).toEqual([
+ 'turn_started',
+ 'thinking_delta',
+ 'tool_start',
+ 'tool_end',
+ 'text_delta',
+ 'turn_ended',
+ ])
+ expect(events[0]).toMatchObject({ payload: { userMessage: 'Use your terminal tool to run exactly: ls. Then reply with just DONE.' } })
+ expect(state.open).toBe(false)
+ })
+
+ it('keeps the turn OPEN on finish_reason "tool_calls" (the model is still calling tools)', () => {
+ const { state } = live(ROWS.slice(0, 2))
+ expect(state.open).toBe(true)
+ expect(isTerminalFinish('tool_calls')).toBe(false)
+ expect(isTerminalFinish('stop')).toBe(true)
+ expect(isTerminalFinish(null)).toBe(false)
+ })
+
+ it('maps the tool_calls blob + the paired role=tool row onto one tool card', () => {
+ const { events } = live(ROWS)
+ expect(events.find((e) => e.type === 'tool_start')).toMatchObject({
+ payload: { id: CALL_ID, tool: 'Bash', input: { command: 'ls' } },
+ })
+ expect(events.find((e) => e.type === 'tool_end')).toMatchObject({
+ payload: { id: CALL_ID, tool: 'Bash', output: 'a.txt\nb.txt', isError: false },
+ })
+ })
+
+ it('flags a failed tool result from the JSON envelope', () => {
+ const { events } = live([
+ ROWS[0], ROWS[1],
+ msg({ id: 23, role: 'tool', toolName: 'terminal', toolCallId: CALL_ID, content: '{"output": "boom", "exit_code": 2, "error": "nope"}' }),
+ ])
+ expect(events.find((e) => e.type === 'tool_end')).toMatchObject({ payload: { isError: true } })
+ })
+
+ it('parseToolCalls / toolResultText handle malformed payloads without throwing', () => {
+ expect(parseToolCalls(null)).toEqual([])
+ expect(parseToolCalls('not json')).toEqual([])
+ expect(parseToolCalls('{}')).toEqual([])
+ expect(toolResultText('plain text')).toEqual({ output: 'plain text', isError: false })
+ })
+
+ it('maps Hermes tool names onto the shared vocabulary', () => {
+ expect(hermesToolName('terminal')).toBe('Bash')
+ expect(hermesToolName('read_file')).toBe('Read')
+ expect(hermesToolName('write_file')).toBe('Write')
+ expect(hermesToolName('search_files')).toBe('Grep')
+ expect(hermesToolName('delegate_task')).toBe('Task')
+ // `todo`, not `todo_write` — the fallback used to title-case it to `Todo`, which the todo-list path
+ // does not recognise, so hermes silently had no checklist on the web or the device.
+ expect(hermesToolName('todo')).toBe('TodoWrite')
+ expect(hermesToolName('browser_click')).toBe('WebFetch')
+ expect(hermesToolName('mystery')).toBe('Mystery')
+ })
+
+ it('presents `clarify` as AskUserQuestion, in the shape both UIs read', () => {
+ // Hermes asks with ONE question and flat string choices; claude's shape (which the web's question box
+ // and the device's question screen both parse) is a LIST whose options are objects. Renaming the tool
+ // without this translation would put an empty question card on the web.
+ expect(hermesToolName('clarify')).toBe('AskUserQuestion')
+ expect(clarifyAsQuestions({ question: 'Bạn muốn chọn size nào?', choices: ['S', 'M'] })).toEqual({
+ questions: [{
+ question: 'Bạn muốn chọn size nào?',
+ header: '',
+ options: [{ label: 'S', description: '' }, { label: 'M', description: '' }],
+ multiSelect: false,
+ }],
+ })
+ })
+
+ it('leaves an already-shaped or unusable clarify payload alone', () => {
+ const shaped = { questions: [{ question: 'x', options: [] }] }
+ expect(clarifyAsQuestions(shaped)).toBe(shaped) // a replay/newer hermes must not be re-wrapped
+ expect(clarifyAsQuestions({ choices: ['S'] })).toEqual({ choices: ['S'] }) // no question → untouched
+ })
+
+ it('ignores system/unknown roles', () => {
+ const state = newHermesTurnState()
+ expect(messageToEvents(msg({ id: 1, role: 'system', content: 'x' }), state, 'live')).toEqual([])
+ })
+})
+
+describe('Hermes normalizer — replay, recap, window', () => {
+ it('replays a session as user_message + assistant blocks, terminated by done', () => {
+ const events = hermesMessagesToEvents(ROWS)
+ expect(events.map((e) => e.type)).toEqual([
+ 'user_message', 'thinking_delta', 'tool_start', 'tool_end', 'text_delta', 'done',
+ ])
+ })
+
+ it('lastHermesTurnText returns the last prompt + the assistant text that followed', () => {
+ expect(lastHermesTurnText(ROWS)).toEqual({
+ userMessage: 'Use your terminal tool to run exactly: ls. Then reply with just DONE.',
+ assistantText: 'DONE',
+ })
+ })
+
+ it('windowHermesMessages snaps the window start back to a user row', () => {
+ const w = windowHermesMessages(ROWS, { limit: 2 })
+ expect(w.window[0].role).toBe('user')
+ expect(w.hasMore).toBe(false)
+ expect(w.oldestCursor).toBe('hermes:0')
+ })
+
+ it('windowHermesMessages flags a malformed cursor as stale', () => {
+ expect(windowHermesMessages(ROWS, { limit: 2, before: 'nope' }).staleCursor).toBe(true)
+ })
+})
diff --git a/cli/src/engines/hermes/normalizer.ts b/cli/src/engines/hermes/normalizer.ts
new file mode 100644
index 000000000..535c14ac3
--- /dev/null
+++ b/cli/src/engines/hermes/normalizer.ts
@@ -0,0 +1,393 @@
+/**
+ * Hermes Agent (Nous Research) → shared event vocabulary.
+ *
+ * Hermes has no per-session transcript file — every surface (CLI, TUI, gateway, desktop) writes to one
+ * SQLite store at `<HERMES_HOME>/state.db`. `HermesReader` polls it; this module holds the pure
+ * row→event mapping it shares with the replay (`session_get`) and recap paths.
+ *
+ * Verified against a real local session (hermes 0.19.0, schema v23, provider vibe / minimax-m3):
+ *
+ * sessions(id, source, cwd, git_branch, model, …) id = `YYYYMMDD_HHMMSS_<6hex>`, source='cli' for tmux
+ * messages(id INTEGER PK, session_id, role, content, tool_call_id, tool_calls, tool_name,
+ * finish_reason, reasoning, timestamp, active, …)
+ *
+ * role 'user' → content = the prompt, finish_reason NULL
+ * role 'assistant' → content and/or tool_calls JSON:
+ * [{"id":"call_…","call_id":"call_…","type":"function",
+ * "function":{"name":"terminal","arguments":"{\"command\":\"ls\"}"}}]
+ * finish_reason 'tool_calls' → the turn CONTINUES into the tool; 'stop' → the turn is done
+ * role 'tool' → tool_name + tool_call_id, content = a JSON result
+ * (for `terminal`: {"output":"…","exit_code":0,"error":null})
+ *
+ * Turn lifecycle is derived (Hermes records no turn markers), exactly like the claude/pi normalizers:
+ * a user row opens a turn; an assistant row with a terminal finish_reason closes it once every tool
+ * call it made has been answered.
+ */
+
+import type { LastTurnText, LiveEvent, SessionEvent } from '../../lib/normalize.js'
+
+export const MAX_OUTPUT = 2_000
+export const MAX_THINKING = 500
+
+/** One `messages` row, as the reader selects it. */
+export interface HmMessage {
+ id: number
+ role: string
+ content: string
+ toolCallId: string | null
+ toolCalls: string | null
+ toolName: string | null
+ finishReason: string | null
+ reasoning: string | null
+}
+
+/** Hermes tool names → the vocabulary the web/device cards already render. */
+const TOOL_NAMES: Record<string, string> = {
+ terminal: 'Bash',
+ execute_code: 'Bash',
+ read_file: 'Read',
+ write_file: 'Write',
+ patch: 'Edit',
+ edit_file: 'Edit',
+ search_files: 'Grep',
+ find_files: 'Glob',
+ list_files: 'LS',
+ web_search: 'WebSearch',
+ web_extract: 'WebFetch',
+ web_fetch: 'WebFetch',
+ delegate_task: 'Task',
+ // Hermes' planning tool is called `todo` (not `todo_write` like the others), and its items are already
+ // `{id, content, status}` — the exact shape the device's todo list reads. Without this entry the
+ // fallback below title-cased it to `Todo`, so `commander.ts` never recognised it: the checklist simply
+ // never appeared on either UI, for an engine that supports it perfectly well.
+ todo: 'TodoWrite',
+ // Hermes asks the user through `clarify`. Naming it AskUserQuestion is what puts it on both UIs: the web
+ // renders a question box for that tool name (eventHandlers.ts), and the device deliberately DROPS the
+ // tool card for it (commander.ts) because the question belongs on its own screen, not in the tool feed.
+ clarify: 'AskUserQuestion',
+}
+
+export function hermesToolName(name: string): string {
+ const key = (name || '').toLowerCase()
+ if (TOOL_NAMES[key]) return TOOL_NAMES[key]
+ if (key.startsWith('browser')) return 'WebFetch'
+ return name ? name.charAt(0).toUpperCase() + name.slice(1) : 'tool'
+}
+
+function object(value: unknown): Record<string, unknown> | null {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+ ? value as Record<string, unknown>
+ : null
+}
+
+function str(value: unknown): string {
+ return typeof value === 'string' ? value : ''
+}
+
+export function clip(value: string, limit: number): string {
+ return value.length > limit ? `${value.slice(0, limit)}\n…[truncated]` : value
+}
+
+function parseJson(text: string): unknown {
+ try { return JSON.parse(text) } catch { return null }
+}
+
+/** A turn continues while the model is calling tools; anything else terminates it. */
+export function isTerminalFinish(finishReason: string | null): boolean {
+ return !!finishReason && finishReason !== 'tool_calls'
+}
+
+/**
+ * Hermes' `clarify` args → the AskUserQuestion shape both UIs already read.
+ *
+ * Hermes asks ONE question with flat string choices (`{question, choices:["S","M"]}` — read from a real
+ * call in its state.db). Claude's shape is a LIST of questions whose options are objects. Renaming the
+ * tool without reshaping would put the card on the web with nothing inside it, so the translation lives
+ * here, next to the name mapping it belongs to.
+ */
+export function clarifyAsQuestions(input: unknown): unknown {
+ const raw = object(input)
+ if (!raw) return input
+ if (Array.isArray(raw.questions)) return raw // already shaped (a future hermes, or a replay)
+ const question = str(raw.question)
+ if (!question) return input
+ const choices = Array.isArray(raw.choices) ? raw.choices : []
+ return {
+ questions: [{
+ question,
+ header: '',
+ options: choices.map((choice) => ({ label: str(choice) || String(choice ?? ''), description: '' }))
+ .filter((o) => o.label),
+ // `clarify` has no multi-select: its schema is one question, one answer.
+ multiSelect: false,
+ }],
+ }
+}
+
+export interface HmToolCall { id: string; tool: string; input: unknown }
+
+/** Parse an assistant row's `tool_calls` JSON blob into normalized calls. */
+export function parseToolCalls(toolCalls: string | null): HmToolCall[] {
+ if (!toolCalls) return []
+ const parsed = parseJson(toolCalls)
+ if (!Array.isArray(parsed)) return []
+ const out: HmToolCall[] = []
+ for (const entry of parsed) {
+ const call = object(entry)
+ if (!call) continue
+ const fn = object(call.function) ?? {}
+ const id = str(call.id) || str(call.call_id)
+ if (!id) continue
+ const args = str(fn.arguments)
+ const tool = hermesToolName(str(fn.name) || str(call.name))
+ const input = (args ? parseJson(args) : null) ?? (args || {})
+ out.push({ id, tool, input: tool === 'AskUserQuestion' ? clarifyAsQuestions(input) : input })
+ }
+ return out
+}
+
+/** A tool row's payload → display text + error flag. Hermes wraps most results in a JSON envelope. */
+export function toolResultText(content: string): { output: string; isError: boolean } {
+ const parsed = object(parseJson(content))
+ if (!parsed) return { output: content, isError: false }
+ const err = parsed.error
+ const exit = parsed.exit_code
+ const isError = (err !== null && err !== undefined && err !== '') || (typeof exit === 'number' && exit !== 0)
+ const output = typeof parsed.output === 'string'
+ ? parsed.output
+ : typeof parsed.result === 'string'
+ ? parsed.result
+ : content
+ return { output: isError && err ? `${output}${output ? '\n' : ''}${str(err)}`.trim() : output, isError }
+}
+
+export function toolSummary(name: string, output: string, isError: boolean): string {
+ const first = output.split('\n').map((line) => line.trim()).find(Boolean) ?? ''
+ if (isError) return first ? `${name} failed: ${first}` : `${name} failed`
+ return first || `${name} completed`
+}
+
+/** Assistant thinking text (the `reasoning` column). */
+export function reasoningText(msg: HmMessage): string {
+ return (msg.reasoning ?? '').trim()
+}
+
+/**
+ * Events for ONE row, shared by the live reader and the replay path.
+ * `mode: 'live'` derives the turn lifecycle; `'replay'` emits `user_message` instead.
+ * `state` tracks tool names + which calls are still unanswered so a turn closes at the right row.
+ */
+export interface HermesTurnState {
+ open: boolean
+ pendingTools: Set<string>
+ toolNames: Map<string, string>
+ thinkingCounter: number
+ /** `delegate_task` call id → the per-task row ids it fanned out into (see delegateFanout). */
+ fanout: Map<string, string[]>
+ /** `delegation_id` (only known once the dispatch result lands) → those same row ids. */
+ delegations: Map<string, string[]>
+}
+
+export function newHermesTurnState(): HermesTurnState {
+ return {
+ open: false,
+ pendingTools: new Set(),
+ toolNames: new Map(),
+ thinkingCounter: 0,
+ fanout: new Map(),
+ delegations: new Map(),
+ }
+}
+
+/**
+ * Hermes delegation, measured on a live session (`~/.hermes/state.db`, messages 284–306):
+ *
+ * assistant tool_calls delegate_task {"tasks":[{"goal":"Đếm .md","role":"leaf"},{"goal":"Đếm .ts",…}]}
+ * tool result {"status":"dispatched","mode":"background","count":2,"delegation_id":"deleg_3c9f8264",…}
+ * user (later) [ASYNC DELEGATION BATCH COMPLETE — deleg_3c9f8264] … --- ✓ TASK 1/2: … (status=completed…
+ * assistant the consolidated answer
+ *
+ * So ONE tool call carries N sub-agents, its result is a dispatch ACK (same trap as claude's "Async agent
+ * launched successfully"), and the finish arrives as a `user` row. Rendered verbatim that produced: one
+ * row labelled "sub-agent" for two agents, never ticked off, and a fake turn whose "user prompt" was the
+ * batch-complete boilerplate (measured: `[recap] … ask="[ASYNC DELEGATION BATCH COMPLETE — deleg_…"`).
+ */
+const DELEGATION_COMPLETE = /^\[ASYNC DELEGATION BATCH COMPLETE\s*[—-]\s*([A-Za-z0-9_-]+)\]/
+/** Per-task outcome inside that message: `--- ✓ TASK 1/2: <goal> (status=completed, api_calls=3, 18.27s) ---` */
+const DELEGATION_TASK = /---\s*.{0,3}\s*TASK\s+(\d+)\/(\d+):[\s\S]*?\(status=([a-z_]+)[^)]*?(?:,\s*([\d.]+)s)?\)\s*---/g
+
+/** True for the machine-written row that reports an async batch finishing — never a user prompt. */
+export function delegationCompleteId(content: string): string | null {
+ return DELEGATION_COMPLETE.exec(content.trim())?.[1] ?? null
+}
+
+/**
+ * One `delegate_task` call → one row PER task, so two parallel sub-agents render as two lines instead of
+ * one. Ids are the call id with the task index appended; the dispatch ack keeps the bare call id, which is
+ * deliberately NOT one of these — that is what stops the ack ticking the rows off.
+ */
+function delegateFanout(call: HmToolCall): { ids: string[]; events: LiveEvent[] } | null {
+ const tasks = (object(call.input) ?? {}).tasks
+ if (!Array.isArray(tasks) || tasks.length === 0) return null
+ const ids: string[] = []
+ const events: LiveEvent[] = []
+ tasks.forEach((entry, i) => {
+ const task = object(entry) ?? {}
+ const goal = str(task.goal) || str(task.prompt) || `sub-agent ${i + 1}`
+ const id = `${call.id}#${i}`
+ ids.push(id)
+ events.push({ type: 'tool_start', payload: { id, tool: 'Task', input: { description: goal, role: str(task.role) } } })
+ })
+ return { ids, events }
+}
+
+/** Per-task finishes carried by a batch-complete row, in task order. */
+function delegationFinishEvents(content: string, ids: string[]): LiveEvent[] {
+ const events: LiveEvent[] = []
+ const seen = new Set<number>()
+ for (const m of content.matchAll(DELEGATION_TASK)) {
+ const index = Number(m[1]) - 1
+ if (!Number.isInteger(index) || index < 0 || index >= ids.length || seen.has(index)) continue
+ seen.add(index)
+ events.push({ type: 'subagent_finished', payload: { id: ids[index], status: m[3] } })
+ }
+ // A batch reports as a whole: anything the text didn't itemise still finished with it, and a row left
+ // running would hold the turn open until the 10-minute backstop.
+ ids.forEach((id, i) => {
+ if (!seen.has(i)) events.push({ type: 'subagent_finished', payload: { id, status: 'completed' } })
+ })
+ return events
+}
+
+export function messageToEvents(msg: HmMessage, state: HermesTurnState, mode: 'live' | 'replay'): LiveEvent[] {
+ const events: LiveEvent[] = []
+
+ if (msg.role === 'user') {
+ const text = (msg.content || '').trim()
+ if (!text) return []
+ // Async batch finished. This row is written by hermes, not typed by anyone: it must not open a turn
+ // (that recapped the boilerplate as if it were the prompt) and it is the ONLY signal the sub-agents
+ // are done. The assistant's consolidated answer then streams under the turn the mirror is holding.
+ const delegationId = delegationCompleteId(text)
+ if (delegationId) {
+ const ids = state.delegations.get(delegationId) ?? []
+ state.delegations.delete(delegationId)
+ return mode === 'replay' ? [] : delegationFinishEvents(text, ids)
+ }
+ if (mode === 'replay') return [{ type: 'user_message', payload: { content: text } }]
+ if (state.open) events.push({ type: 'turn_ended', payload: {} })
+ state.open = true
+ state.pendingTools.clear()
+ events.push({ type: 'turn_started', payload: { userMessage: text } })
+ return events
+ }
+
+ if (msg.role === 'assistant') {
+ const thinking = reasoningText(msg)
+ if (thinking) {
+ events.push({
+ type: 'thinking_delta',
+ payload: { content: clip(thinking, MAX_THINKING), thinkingId: `thinking-hermes-${state.thinkingCounter++}` },
+ })
+ }
+ const text = (msg.content || '').trim()
+ if (text) events.push({ type: 'text_delta', payload: { content: text } })
+ for (const call of parseToolCalls(msg.toolCalls)) {
+ state.toolNames.set(call.id, call.tool)
+ state.pendingTools.add(call.id)
+ const fan = call.tool === 'Task' ? delegateFanout(call) : null
+ if (fan) {
+ state.fanout.set(call.id, fan.ids)
+ events.push(...fan.events)
+ continue
+ }
+ events.push({ type: 'tool_start', payload: { id: call.id, tool: call.tool, input: call.input } })
+ }
+ if (mode === 'live' && state.open && isTerminalFinish(msg.finishReason) && state.pendingTools.size === 0) {
+ state.open = false
+ events.push({ type: 'turn_ended', payload: {} })
+ }
+ return events
+ }
+
+ if (msg.role === 'tool') {
+ const id = msg.toolCallId || ''
+ if (!id) return []
+ state.pendingTools.delete(id)
+ const tool = state.toolNames.get(id) || hermesToolName(msg.toolName ?? '')
+ state.toolNames.delete(id)
+ const { output, isError } = toolResultText(msg.content || '')
+ const events: LiveEvent[] = [{
+ type: 'tool_end',
+ payload: { id, tool, output: clip(output, MAX_OUTPUT), isError, summary: toolSummary(tool, output, isError) },
+ }]
+ const ids = state.fanout.get(id)
+ if (ids) {
+ state.fanout.delete(id)
+ const result = object(parseJson(msg.content || '')) ?? {}
+ const delegationId = str(result.delegation_id)
+ // Background fan-out: this result is only the dispatch ACK, so hold the rows open and remember which
+ // batch they belong to. Foreground (or a failed dispatch): nothing else is coming — close them now.
+ if (delegationId && str(result.mode) === 'background' && !isError) state.delegations.set(delegationId, ids)
+ else for (const rowId of ids) events.push({ type: 'subagent_finished', payload: { id: rowId, status: isError ? 'failed' : 'completed' } })
+ }
+ return events
+ }
+
+ return [] // system / other roles are not surfaced
+}
+
+/** Full-session replay (session_get) — same render path as the live stream. */
+export function hermesMessagesToEvents(messages: HmMessage[]): SessionEvent[] {
+ const state = newHermesTurnState()
+ const events: SessionEvent[] = []
+ for (const msg of messages) events.push(...messageToEvents(msg, state, 'replay') as SessionEvent[])
+ events.push({ type: 'done', payload: { result: 'success' } })
+ return events
+}
+
+/** Last user prompt + the assistant text that followed it — the recap source of truth. */
+export function lastHermesTurnText(messages: HmMessage[]): LastTurnText | null {
+ let userMessage = ''
+ let assistantText = ''
+ for (const msg of messages) {
+ if (msg.role === 'user') {
+ const text = (msg.content || '').trim()
+ // A batch-complete row is hermes talking to itself. Treating it as a new prompt made the recap lead
+ // with "[ASYNC DELEGATION BATCH COMPLETE — deleg_…]" and threw away the answer to what was ASKED;
+ // the consolidated reply that follows belongs to the prompt that dispatched the batch.
+ if (text && !delegationCompleteId(text)) { userMessage = text; assistantText = '' }
+ } else if (msg.role === 'assistant') {
+ const text = (msg.content || '').trim()
+ if (text) assistantText += `${assistantText ? '\n\n' : ''}${text}`
+ }
+ }
+ return assistantText ? { userMessage, assistantText } : null
+}
+
+/**
+ * Turn-snapped pagination window for `session_get {limit, before}`; cursor `hermes:<index>`.
+ * The start snaps back to a user row so a window never splits a turn (a tool_start's name must still
+ * be known when its tool_end renders).
+ */
+export function windowHermesMessages(
+ messages: HmMessage[],
+ opts: { limit: number; before?: string },
+): { window: HmMessage[]; hasMore: boolean; oldestCursor: string | null; staleCursor?: boolean } {
+ let endIndex = messages.length
+ if (opts.before) {
+ const match = /^hermes:(\d+)$/.exec(opts.before)
+ if (!match) return { window: [], hasMore: false, oldestCursor: null, staleCursor: true }
+ endIndex = Number(match[1])
+ if (!Number.isSafeInteger(endIndex) || endIndex < 0 || endIndex > messages.length) {
+ return { window: [], hasMore: false, oldestCursor: null, staleCursor: true }
+ }
+ }
+ let start = Math.max(0, endIndex - opts.limit)
+ while (start > 0 && messages[start].role !== 'user') start--
+ return {
+ window: messages.slice(start, endIndex),
+ hasMore: start > 0,
+ oldestCursor: `hermes:${start}`,
+ }
+}
diff --git a/cli/src/engines/hermes/reader.spec.ts b/cli/src/engines/hermes/reader.spec.ts
new file mode 100644
index 000000000..df7d8bfc3
--- /dev/null
+++ b/cli/src/engines/hermes/reader.spec.ts
@@ -0,0 +1,92 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { execFileSync } from 'child_process'
+import { mkdtempSync, rmSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import { HermesReader, readHermesMessages } from './reader.js'
+import type { LiveEvent } from '../../lib/normalize.js'
+
+const hasSqlite = (() => {
+ try { execFileSync('sqlite3', ['-version'], { stdio: 'ignore' }); return true } catch { return false }
+})()
+const d = hasSqlite ? describe : describe.skip
+
+const SID = '20260727_162325_e25264' // the real Hermes id shape: YYYYMMDD_HHMMSS_<hex>
+const CALL = 'call_ba1647ad979d0290'
+
+function run(db: string, sql: string): void {
+ execFileSync('sqlite3', [db, sql], { stdio: ['ignore', 'ignore', 'inherit'] })
+}
+function q(v: string | null): string {
+ return v === null ? 'NULL' : `'${v.replace(/'/g, "''")}'`
+}
+function insert(
+ db: string,
+ row: { id: number; role: string; content?: string; toolCallId?: string; toolCalls?: string; toolName?: string; finishReason?: string; reasoning?: string },
+): void {
+ run(db,
+ `INSERT INTO messages (id, session_id, role, content, tool_call_id, tool_calls, tool_name, finish_reason, reasoning, timestamp) VALUES (` +
+ `${row.id}, '${SID}', '${row.role}', ${q(row.content ?? '')}, ${q(row.toolCallId ?? null)}, ${q(row.toolCalls ?? null)}, ` +
+ `${q(row.toolName ?? null)}, ${q(row.finishReason ?? null)}, ${q(row.reasoning ?? null)}, ${row.id});`)
+}
+const wait = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))
+
+d('HermesReader (sqlite3 CLI)', () => {
+ let dir = ''
+ let db = ''
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'hermes-reader-'))
+ db = join(dir, 'state.db')
+ run(db,
+ 'CREATE TABLE messages (id INTEGER PRIMARY KEY, session_id TEXT, role TEXT, content TEXT, tool_call_id TEXT,' +
+ ' tool_calls TEXT, tool_name TEXT, finish_reason TEXT, reasoning TEXT, timestamp REAL);')
+ })
+ afterEach(() => { rmSync(dir, { recursive: true, force: true }) })
+
+ it('reads rows in id order with the columns the normalizer needs', async () => {
+ insert(db, { id: 1, role: 'user', content: 'hi' })
+ insert(db, { id: 2, role: 'assistant', content: 'hello', finishReason: 'stop' })
+ const rows = await readHermesMessages(db, SID)
+ expect(rows.map((r) => r.role)).toEqual(['user', 'assistant'])
+ expect(rows[1]).toMatchObject({ id: 2, content: 'hello', finishReason: 'stop' })
+ })
+
+ it('rejects a session id that is not the Hermes shape (no injection surface)', async () => {
+ expect(await readHermesMessages(db, "x'; DROP TABLE messages;--")).toEqual([])
+ })
+
+ it('hydrates silently, then streams a new turn incrementally', async () => {
+ insert(db, { id: 1, role: 'user', content: 'old' })
+ insert(db, { id: 2, role: 'assistant', content: 'done', finishReason: 'stop' })
+
+ const events: LiveEvent[] = []
+ const reader = new HermesReader({ dbPath: db, sessionId: SID, onEvents: (e) => events.push(...e), pollMs: 30 })
+ await reader.start()
+ expect(events).toHaveLength(0) // hydrate = no replay
+ expect(reader.turnOpen).toBe(false) // last row was a terminal assistant
+
+ insert(db, { id: 3, role: 'user', content: 'who won?' })
+ insert(db, { id: 4, role: 'assistant', finishReason: 'tool_calls', toolCalls: `[{"id":"${CALL}","type":"function","function":{"name":"terminal","arguments":"{\\"command\\":\\"ls\\"}"}}]` })
+ await wait(120)
+ expect(reader.turnOpen).toBe(true) // still calling a tool
+
+ insert(db, { id: 5, role: 'tool', toolName: 'terminal', toolCallId: CALL, content: '{"output": "a.txt", "exit_code": 0, "error": null}' })
+ insert(db, { id: 6, role: 'assistant', content: 'Spain', finishReason: 'stop' })
+ await wait(150)
+ reader.stop()
+
+ const types = events.map((e) => e.type)
+ expect(types).toEqual(['turn_started', 'tool_start', 'tool_end', 'text_delta', 'turn_ended'])
+ expect(events[0]).toMatchObject({ payload: { userMessage: 'who won?' } })
+ expect(events[2]).toMatchObject({ payload: { tool: 'Bash', output: 'a.txt', isError: false } })
+ expect(reader.turnOpen).toBe(false)
+ })
+
+ it('reports a mid-turn attach as an open turn', async () => {
+ insert(db, { id: 1, role: 'user', content: 'working on it' })
+ const reader = new HermesReader({ dbPath: db, sessionId: SID, onEvents: () => {}, pollMs: 1_000 })
+ await reader.start()
+ expect(reader.turnOpen).toBe(true)
+ reader.stop()
+ })
+})
diff --git a/cli/src/engines/hermes/reader.ts b/cli/src/engines/hermes/reader.ts
new file mode 100644
index 000000000..7a64c0c40
--- /dev/null
+++ b/cli/src/engines/hermes/reader.ts
@@ -0,0 +1,196 @@
+/**
+ * Hermes live tailer.
+ *
+ * Hermes keeps every surface's history in ONE SQLite store (`<HERMES_HOME>/state.db`, WAL), so there is
+ * no file to byte-offset-tail. This polls the DB every ~1s through the `sqlite3` CLI (shelled out, like
+ * tmux/git — keeps the adapter's single pure-JS bundle; no native SQLite dependency) and feeds the same
+ * `emitSessionEvents` funnel the file-based engines use.
+ *
+ * `messages.id` is an INTEGER primary key, which makes the incremental cursor trivial (`id > lastSeen`).
+ * The connection is opened READ-ONLY: Hermes retries writes ~15 times on contention, and a long-held
+ * reader would eat into that budget.
+ */
+
+import { execFile } from 'child_process'
+import { promisify } from 'util'
+import type { LiveEvent } from '../../lib/normalize.js'
+import {
+ messageToEvents, newHermesTurnState, isTerminalFinish,
+ type HermesTurnState, type HmMessage,
+} from './normalizer.js'
+
+const execFileAsync = promisify(execFile)
+
+// `YYYYMMDD_HHMMSS_<hex>` — CLI/TUI use 6 hex chars, the gateway 8.
+const SESSION_ID_RE = /^[0-9]{8}_[0-9]{6}_[0-9a-fA-F]{4,16}$/
+const POLL_MS = 1_000
+const MAX_BUFFER = 32 * 1024 * 1024
+
+const COLUMNS =
+ 'id, role, coalesce(content, \'\') AS content, tool_call_id, tool_calls, tool_name, finish_reason, reasoning'
+
+export class HermesSqliteMissing extends Error {
+ constructor() { super('sqlite3 CLI not found on PATH — Hermes sessions cannot be mirrored') }
+}
+
+function str(value: unknown): string | null {
+ return typeof value === 'string' && value ? value : null
+}
+
+/**
+ * Read a Hermes session's messages, optionally only those after `afterId`.
+ * Throws `HermesSqliteMissing` when the `sqlite3` binary is absent; returns [] on a transient error.
+ */
+export async function readHermesMessages(
+ dbPath: string,
+ sessionId: string,
+ afterId?: number | null,
+): Promise<HmMessage[]> {
+ if (!SESSION_ID_RE.test(sessionId)) return []
+ const after = Number.isFinite(afterId as number) && (afterId as number) > 0 ? ` AND id > ${Math.trunc(afterId as number)}` : ''
+ const sql = `SELECT ${COLUMNS} FROM messages WHERE session_id = '${sessionId}'${after} ORDER BY id;`
+
+ let stdout: string
+ try {
+ // `.timeout` is the SILENT dot-command form — `PRAGMA busy_timeout=…` prints a row under -json and
+ // would corrupt the single-array parse below. `query_only` is silent and guards against writes.
+ ;({ stdout } = await execFileAsync(
+ 'sqlite3',
+ ['-json', '-cmd', '.timeout 3000', '-cmd', 'PRAGMA query_only=1', `file:${dbPath}?mode=ro`, sql],
+ { maxBuffer: MAX_BUFFER },
+ ))
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') throw new HermesSqliteMissing()
+ return [] // db locked / mid-write — retry next tick
+ }
+
+ const trimmed = stdout.trim()
+ if (!trimmed) return []
+ let rows: Array<Record<string, unknown>>
+ try { rows = JSON.parse(trimmed) } catch { return [] }
+
+ return rows.map((row) => ({
+ id: Number(row.id) || 0,
+ role: typeof row.role === 'string' ? row.role : '',
+ content: typeof row.content === 'string' ? row.content : '',
+ toolCallId: str(row.tool_call_id),
+ toolCalls: str(row.tool_calls),
+ toolName: str(row.tool_name),
+ finishReason: str(row.finish_reason),
+ reasoning: str(row.reasoning),
+ }))
+}
+
+/**
+ * True when this session id belongs to a DELEGATION CHILD rather than to the CLI the user is looking at.
+ *
+ * A hermes sub-agent is a full hermes session of its own and runs the same shell hooks, so it announces
+ * itself to the adapter from the parent's pane. Measured live: dispatching two sub-agents fired
+ * `on_session_start` for `20260805_111618_8e3027` / `…_0777bc` 0.2s after the parent's rows appeared, the
+ * pane re-bound to them, and the parent was `forgotten` mid-turn — taking its delegation bookkeeping and
+ * its sub-agent list with it. `sessions.source` separates them: 'cli' for the real one, 'subagent'/'tool'
+ * for the children (`cwd` also points into `/tmp`, but source is the explicit marker).
+ *
+ */
+export async function isHermesSubagentSession(dbPath: string, sessionId: string): Promise<boolean> {
+ const source = await hermesSessionSource(dbPath, sessionId)
+ return source !== null && source !== '' && source !== 'cli'
+}
+
+/**
+ * `sessions.source` for one id, or null when the row is not there YET — which is a real state, not an
+ * error: measured, a delegation child's `on_session_start` hook reached the adapter 110ms BEFORE hermes
+ * inserted its row, so an immediate lookup said "not a sub-agent" and the child took over the pane.
+ * Callers that can afford to wait should treat null as "ask again shortly".
+ *
+ * Async, like every other query against this store: `.timeout 3000` means a contended read can park for
+ * seconds, and hermes writes to this DB constantly — a synchronous spawn here would freeze the whole
+ * daemon (every engine's poll, every socket, the device stream) for as long as the lock is held.
+ */
+export async function hermesSessionSource(dbPath: string, sessionId: string): Promise<string | null> {
+ if (!SESSION_ID_RE.test(sessionId)) return ''
+ try {
+ const { stdout: raw } = await execFileAsync(
+ 'sqlite3',
+ ['-json', '-cmd', '.timeout 3000', '-cmd', 'PRAGMA query_only=1', `file:${dbPath}?mode=ro`,
+ `SELECT source FROM sessions WHERE id = '${sessionId}';`],
+ { maxBuffer: 1 << 20, timeout: 5_000 },
+ )
+ const stdout = raw.trim()
+ if (!stdout) return null
+ const rows = JSON.parse(stdout) as Array<{ source?: unknown }>
+ if (rows.length === 0) return null
+ return typeof rows[0]?.source === 'string' ? rows[0].source : ''
+ } catch {
+ return '' // sqlite3 missing / db locked — treat as a normal session, exactly as before
+ }
+}
+
+export interface HermesReaderDeps {
+ dbPath: string
+ sessionId: string
+ onEvents: (events: LiveEvent[]) => void
+ /** Reports the one-time fatal "sqlite3 missing" so the caller can warn + stop the reader. */
+ onFatal?: (err: Error) => void
+ pollMs?: number
+}
+
+export class HermesReader {
+ private timer: NodeJS.Timeout | null = null
+ private polling = false
+ private cursor = 0
+ private state: HermesTurnState = newHermesTurnState()
+
+ constructor(private readonly deps: HermesReaderDeps) {}
+
+ get turnOpen(): boolean { return this.state.open }
+ closeTurn(): void { this.state.open = false; this.state.pendingTools.clear() }
+
+ /** Hydrate silently (no replay), then start polling. */
+ async start(): Promise<void> {
+ try {
+ const all = await readHermesMessages(this.deps.dbPath, this.deps.sessionId)
+ this.hydrate(all)
+ } catch (err) {
+ if (err instanceof HermesSqliteMissing) { this.deps.onFatal?.(err); return }
+ }
+ this.timer = setInterval(() => { void this.tick() }, this.deps.pollMs ?? POLL_MS)
+ }
+
+ stop(): void {
+ if (this.timer) { clearInterval(this.timer); this.timer = null }
+ }
+
+ /** Seed state from existing rows without emitting, so only NEW activity streams after attach. */
+ private hydrate(messages: HmMessage[]): void {
+ for (const msg of messages) {
+ this.cursor = Math.max(this.cursor, msg.id)
+ messageToEvents(msg, this.state, 'live') // advances turn/tool state; output discarded
+ }
+ // A trailing user row (or an assistant still calling tools) means we attached mid-turn.
+ const tail = messages[messages.length - 1]
+ if (!tail) return
+ this.state.open = tail.role === 'user'
+ || this.state.pendingTools.size > 0
+ || (tail.role === 'assistant' && !isTerminalFinish(tail.finishReason))
+ }
+
+ private async tick(): Promise<void> {
+ if (this.polling) return
+ this.polling = true
+ try {
+ const batch = await readHermesMessages(this.deps.dbPath, this.deps.sessionId, this.cursor)
+ if (batch.length === 0) return
+ const events: LiveEvent[] = []
+ for (const msg of batch) {
+ this.cursor = Math.max(this.cursor, msg.id)
+ events.push(...messageToEvents(msg, this.state, 'live'))
+ }
+ if (events.length) this.deps.onEvents(events)
+ } catch (err) {
+ if (err instanceof HermesSqliteMissing) { this.stop(); this.deps.onFatal?.(err) }
+ } finally {
+ this.polling = false
+ }
+ }
+}
diff --git a/cli/src/engines/hermes/runtimeProfile.spec.ts b/cli/src/engines/hermes/runtimeProfile.spec.ts
new file mode 100644
index 000000000..546579e31
--- /dev/null
+++ b/cli/src/engines/hermes/runtimeProfile.spec.ts
@@ -0,0 +1,90 @@
+import { describe, expect, it } from 'vitest'
+import {
+ hermesStatusModel,
+ parseHermesConfig,
+ parseHermesModelsCache,
+ parseHermesPickerPage,
+} from './runtimeProfile.js'
+
+describe('hermes model catalog', () => {
+ it('reads every provider page out of the picker cache', () => {
+ // Shape of the real ~/.hermes/provider_models_cache.json.
+ expect(parseHermesModelsCache({
+ copilot: { fp: 'dd7c', at: 1785424593, models: ['gpt-5.4', 'gpt-5.4-mini'] },
+ anthropic: { fp: 'bd6c', at: 1785424596, models: ['claude-fable-5', 'gpt-5.4'] },
+ broken: { models: 'not a list' },
+ alsoBroken: null,
+ })).toEqual([
+ { id: 'gpt-5.4', provider: 'copilot' },
+ { id: 'gpt-5.4-mini', provider: 'copilot' },
+ // Same id under a second provider is one model, kept where it was first seen.
+ { id: 'claude-fable-5', provider: 'anthropic' },
+ ])
+ expect(parseHermesModelsCache(null)).toEqual([])
+ expect(parseHermesModelsCache([])).toEqual([])
+ })
+
+ it('reads the two scalars it needs from config.yaml and nothing else', () => {
+ const yaml = [
+ 'model:',
+ ' default: minimax/minimax-m3',
+ ' provider: custom',
+ ' api_key: ${HERMES_SECRET}',
+ 'agent:',
+ ' max_turns: 150',
+ ' reasoning_effort: medium',
+ ' personalities:',
+ ' helpful: You are a helpful assistant.',
+ 'voice:',
+ ' model: whisper-1', // a `model` key in another section must not win
+ ].join('\n')
+
+ expect(parseHermesConfig(yaml)).toEqual({ model: 'minimax/minimax-m3', effort: 'medium' })
+ expect(parseHermesConfig('model:\n default: x\nagent:\n reasoning_effort: nonsense'))
+ .toEqual({ model: 'x', effort: null })
+ expect(parseHermesConfig('')).toEqual({ model: null, effort: null })
+ })
+
+ it('reads the model out of the status line', () => {
+ expect(hermesStatusModel(' ⚕ minimax-m3 │ ctx -- │ [░░░░░░░░░░] -- │ 4s │ ⏲ 0s'))
+ .toBe('minimax-m3')
+ expect(hermesStatusModel('no status here')).toBeNull()
+ })
+})
+
+describe('hermes model picker pages', () => {
+ it('reads the rows and the cursor of the provider page', () => {
+ const capture = [
+ '╭─ ⚙ Model Picker — Select Provider ─────────────╮',
+ '│ │',
+ '│ Current: minimax/minimax-m3 on custom │',
+ '│ │',
+ '│ Mixture of Agents (1 model) │',
+ '│ ❯ vibe (1 model) ← current │',
+ '│ GitHub Copilot (17 models) │',
+ '│ Cancel │',
+ '╰────────────────────────────────────────────────╯',
+ ].join('\n')
+
+ expect(parseHermesPickerPage(capture)).toEqual({
+ rows: ['Mixture of Agents (1 model)', 'vibe (1 model)', 'GitHub Copilot (17 models)', 'Cancel'],
+ selected: 'vibe (1 model)',
+ })
+ })
+
+ it('reads the model page, and refuses a capture with no picker in it', () => {
+ const capture = [
+ '╭─ ⚙ Model Picker — Anthropic ───────────────────╮',
+ '│ ❯ claude-fable-5 │',
+ '│ claude-sonnet-5 │',
+ '│ ← Back │',
+ '╰────────────────────────────────────────────────╯',
+ ].join('\n')
+
+ expect(parseHermesPickerPage(capture)).toEqual({
+ rows: ['claude-fable-5', 'claude-sonnet-5', '← Back'],
+ selected: 'claude-fable-5',
+ })
+ expect(parseHermesPickerPage('❯ just a prompt')).toBeNull()
+ })
+})
diff --git a/cli/src/engines/hermes/runtimeProfile.ts b/cli/src/engines/hermes/runtimeProfile.ts
new file mode 100644
index 000000000..1514032ca
--- /dev/null
+++ b/cli/src/engines/hermes/runtimeProfile.ts
@@ -0,0 +1,120 @@
+/**
+ * Hermes model catalog + reasoning effort → runtime-profile options.
+ *
+ * Hermes is the only one of the eight with no way to print its catalog: `hermes model` is interactive and
+ * has no list flag. What it does have is the picker's own **disk cache** — the file `hermes model
+ * --refresh` exists to wipe — so the catalog is read from there rather than by driving a TUI:
+ *
+ * ~/.hermes/provider_models_cache.json
+ * { "copilot": { "fp": …, "at": …, "models": ["gpt-5.4", …] },
+ * "anthropic": { "fp": …, "at": …, "models": ["claude-fable-5", …] } }
+ *
+ * Verified against the live picker (hermes 2026.07): its "Anthropic (13 models)" page lists exactly the
+ * 13 ids this file holds, in the same order. The provider actually in use may be absent from the cache
+ * (a `custom` gateway is configured here, and the picker shows it as its own one-model page), so the
+ * model named by `config.yaml` is always offered too — see hermesConfigProfile.
+ *
+ * Both axes live in `~/.hermes/config.yaml`, and both are GLOBAL to the computer rather than per session:
+ *
+ * model: { default: minimax/minimax-m3, provider: custom }
+ * agent: { reasoning_effort: medium }
+ */
+
+/** Levels hermes accepts for `agent.reasoning_effort`. */
+export const HERMES_EFFORTS = new Set(['auto', 'low', 'medium', 'high'])
+export const HERMES_EFFORT_LEVELS = ['low', 'medium', 'high'] as const
+
+export interface HermesModelTarget {
+ /** Model id as the picker lists it. */
+ id: string
+ /** Cache key of the provider page it belongs to (`anthropic`, `copilot`, …). */
+ provider: string
+}
+
+function str(value: unknown): string {
+ return typeof value === 'string' ? value : ''
+}
+
+/**
+ * Read `provider_models_cache.json`. Each provider contributes its `models` array; anything that is not a
+ * list of non-empty strings is skipped, so a half-written cache cannot invent models.
+ */
+export function parseHermesModelsCache(raw: unknown): HermesModelTarget[] {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return []
+ const targets: HermesModelTarget[] = []
+ const seen = new Set<string>()
+ for (const [provider, blob] of Object.entries(raw as Record<string, unknown>)) {
+ if (!blob || typeof blob !== 'object') continue
+ const models = (blob as Record<string, unknown>).models
+ if (!Array.isArray(models)) continue
+ for (const entry of models) {
+ const id = str(entry).trim()
+ if (!id || seen.has(id)) continue
+ seen.add(id)
+ targets.push({ id, provider })
+ }
+ }
+ return targets
+}
+
+/**
+ * Model + reasoning effort out of `config.yaml`. Parsed by hand rather than with a YAML library: these are
+ * two scalars at known paths, the adapter ships no YAML dependency, and the file is the user's — a parser
+ * that only ever reads two keys cannot damage it.
+ */
+export function parseHermesConfig(yaml: string): { model: string | null; effort: string | null } {
+ let section = ''
+ let model: string | null = null
+ let effort: string | null = null
+ for (const rawLine of yaml.split('\n')) {
+ const line = rawLine.replace(/\s+$/, '')
+ if (!line.trim() || line.trimStart().startsWith('#')) continue
+ if (!/^\s/.test(line)) {
+ section = line.replace(/:.*$/, '').trim()
+ continue
+ }
+ // Only the top nesting level of a section, so a `models:` block elsewhere cannot be mistaken for it.
+ const entry = /^\s{2}([a-z_]+):\s*(.+?)\s*$/i.exec(line)
+ if (!entry) continue
+ const value = entry[2].replace(/^["']|["']$/g, '')
+ if (section === 'model' && entry[1] === 'default') model = value || null
+ if (section === 'agent' && entry[1] === 'reasoning_effort') {
+ const level = value.toLowerCase()
+ effort = HERMES_EFFORTS.has(level) ? level : null
+ }
+ }
+ return { model, effort }
+}
+
+/**
+ * The model hermes shows in its status line (`⚕ minimax-m3 │ ctx -- │ …`). It is the SHORT name — the
+ * config says `minimax/minimax-m3` while the status line says `minimax-m3` — so it is only used to notice
+ * that a switch landed, never as the identity itself.
+ */
+export function hermesStatusModel(capture: string): string | null {
+ const lines = capture.split('\n')
+ for (let i = lines.length - 1; i >= 0; i--) {
+ const match = /⚕\s*([^\s│|]+)/.exec(lines[i])
+ if (match) return match[1]
+ }
+ return null
+}
+
+/** The row hermes marks with `❯` in a picker page, and every selectable row on that page. */
+export function parseHermesPickerPage(capture: string): { rows: string[]; selected: string | null } | null {
+ const lines = capture.split('\n')
+ const top = lines.findLastIndex((line) => /Model Picker/i.test(line))
+ if (top < 0) return null
+ const rows: string[] = []
+ let selected: string | null = null
+ for (const line of lines.slice(top)) {
+ // Rows live inside a box: `│ ❯ claude-fable-5 │`.
+ const match = /^\s*│\s*(❯)?\s*(\S.*?)\s*│\s*$/.exec(line)
+ if (!match) continue
+ const label = match[2].replace(/\s*←\s*current\s*$/i, '').trim()
+ if (!label || /^Current:/i.test(label)) continue
+ rows.push(label)
+ if (match[1]) selected = label
+ }
+ return rows.length ? { rows, selected } : null
+}
diff --git a/cli/src/engines/opencode/normalizer.spec.ts b/cli/src/engines/opencode/normalizer.spec.ts
new file mode 100644
index 000000000..50865c14c
--- /dev/null
+++ b/cli/src/engines/opencode/normalizer.spec.ts
@@ -0,0 +1,131 @@
+import { describe, expect, it } from 'vitest'
+import {
+ opencodeMessagesToEvents,
+ lastOpencodeTurnText,
+ windowOpencodeMessages,
+ taskStartEvent,
+ taskEndEvent,
+ extractTaskResult,
+ isTaskPart,
+ type OcMessage,
+ type OcPart,
+} from './normalizer.js'
+
+function part(type: string, data: Record<string, unknown>, id = `prt_${type}_${Math.round(Math.random() * 1e6)}`): OcPart {
+ return { id, type, data: { type, ...data } }
+}
+function msg(role: string, parts: OcPart[], id = `msg_${role}`, timeCreated = 1): OcMessage {
+ return { id, role, timeCreated, data: { role }, parts }
+}
+
+describe('opencode normalizer — replay', () => {
+ it('maps a user + assistant (text, reasoning) turn to the shared event shapes', () => {
+ const events = opencodeMessagesToEvents([
+ msg('user', [part('text', { text: 'what is the BTC price?' })], 'msg_u', 1),
+ msg('assistant', [
+ part('step-start', {}),
+ part('reasoning', { text: 'The user wants the BTC price.' }),
+ part('text', { text: '65,374 USD' }),
+ part('step-finish', { reason: 'stop' }),
+ ], 'msg_a', 2),
+ ])
+ expect(events.map((e) => e.type)).toEqual(['user_message', 'thinking_delta', 'text_delta', 'done'])
+ expect(events[0]).toMatchObject({ type: 'user_message', payload: { content: 'what is the BTC price?' } })
+ expect(events[2]).toMatchObject({ type: 'text_delta', payload: { content: '65,374 USD' } })
+ })
+
+ it('maps a completed tool part to a Claude-vocabulary tool_start + tool_end', () => {
+ const events = opencodeMessagesToEvents([
+ msg('assistant', [
+ part('tool', { tool: 'webfetch', state: { status: 'completed', input: { url: 'https://x' }, output: 'ok' } }, 'prt_t'),
+ ]),
+ ])
+ const tool = events.filter((e) => e.type === 'tool_start' || e.type === 'tool_end')
+ expect(tool[0]).toMatchObject({ type: 'tool_start', payload: { id: 'prt_t', tool: 'WebFetch', input: { url: 'https://x' } } })
+ expect(tool[1]).toMatchObject({ type: 'tool_end', payload: { id: 'prt_t', tool: 'WebFetch', output: 'ok', isError: false } })
+ })
+
+ it('maps a todowrite tool part to TodoWrite with the todo list intact', () => {
+ const todos = [
+ { content: 'Fetch BTC price', status: 'completed', priority: 'high' },
+ { content: 'Report all prices', status: 'pending', priority: 'high' },
+ ]
+ const events = opencodeMessagesToEvents([
+ msg('assistant', [part('tool', { tool: 'todowrite', state: { status: 'completed', input: { todos }, output: '[]' } }, 'prt_todo')]),
+ ])
+ const start = events.find((e) => e.type === 'tool_start')
+ expect(start).toMatchObject({ type: 'tool_start', payload: { tool: 'TodoWrite', input: { todos } } })
+ })
+
+ it('renders a task tool part as a Task card with a sub-agent summary', () => {
+ const taskPart = part('tool', {
+ tool: 'task',
+ state: {
+ status: 'completed',
+ input: { description: 'Fetch BNB price', prompt: 'fetch BNB', subagent_type: 'general' },
+ output: '<task id="ses_child" state="completed">\n<task_result>\n573.92\n</task_result>\n</task>',
+ metadata: { sessionId: 'ses_child', parentSessionId: 'ses_parent' },
+ time: { start: 1000, end: 3000 },
+ },
+ }, 'prt_task')
+ expect(isTaskPart(taskPart)).toBe(true)
+
+ const start = taskStartEvent(taskPart)
+ expect(start).toMatchObject({ type: 'tool_start', payload: { id: 'prt_task', tool: 'Task', input: { subagent_type: 'general', description: 'Fetch BNB price' } } })
+
+ const end = taskEndEvent(taskPart, { totalToolUseCount: 1, totalTokens: 42 })
+ expect(end).toMatchObject({
+ type: 'tool_end',
+ payload: {
+ id: 'prt_task',
+ tool: 'Task',
+ output: '573.92',
+ isError: false,
+ subagent: { agentId: 'ses_child', agentType: 'general', totalToolUseCount: 1, totalTokens: 42, totalDurationMs: 2000 },
+ },
+ })
+ })
+
+ it('extractTaskResult pulls the <task_result> body, else the raw text', () => {
+ expect(extractTaskResult('<task_result>\n42\n</task_result>')).toBe('42')
+ expect(extractTaskResult('plain output')).toBe('plain output')
+ })
+
+ it('an in-flight tool part emits only tool_start', () => {
+ const events = opencodeMessagesToEvents([
+ msg('assistant', [part('tool', { tool: 'bash', state: { status: 'running', input: { command: 'ls' } } }, 'prt_r')]),
+ ])
+ expect(events.filter((e) => e.type === 'tool_start')).toHaveLength(1)
+ expect(events.filter((e) => e.type === 'tool_end')).toHaveLength(0)
+ })
+})
+
+describe('opencode normalizer — recap + window', () => {
+ it('lastOpencodeTurnText returns the last user prompt + following assistant text', () => {
+ const turn = lastOpencodeTurnText([
+ msg('user', [part('text', { text: 'first' })], 'm1', 1),
+ msg('assistant', [part('text', { text: 'ignored' })], 'm2', 2),
+ msg('user', [part('text', { text: 'who won?' })], 'm3', 3),
+ msg('assistant', [part('text', { text: 'Spain won.' })], 'm4', 4),
+ ])
+ expect(turn).toEqual({ userMessage: 'who won?', assistantText: 'Spain won.' })
+ })
+
+ it('windowOpencodeMessages snaps the window start back to a user message', () => {
+ const messages = [
+ msg('user', [part('text', { text: 'u1' })], 'm1', 1),
+ msg('assistant', [part('text', { text: 'a1' })], 'm2', 2),
+ msg('user', [part('text', { text: 'u2' })], 'm3', 3),
+ msg('assistant', [part('text', { text: 'a2' })], 'm4', 4),
+ ]
+ const w = windowOpencodeMessages(messages, { limit: 2 })
+ expect(w.window[0].role).toBe('user') // snapped back to m3
+ expect(w.hasMore).toBe(true)
+ expect(w.oldestCursor).toBe('opencode:2')
+ })
+
+ it('windowOpencodeMessages flags a malformed cursor as stale', () => {
+ const w = windowOpencodeMessages([], { limit: 2, before: 'not-a-cursor' })
+ expect(w.staleCursor).toBe(true)
+ })
+})
diff --git a/cli/src/engines/opencode/normalizer.ts b/cli/src/engines/opencode/normalizer.ts
new file mode 100644
index 000000000..d5a3ff8cb
--- /dev/null
+++ b/cli/src/engines/opencode/normalizer.ts
@@ -0,0 +1,253 @@
+/**
+ * OpenCode → web ServerEvent conversion.
+ *
+ * Unlike claude/codex/cursor, OpenCode does NOT write a per-session transcript file — it persists
+ * `session`/`message`/`part` rows in a SQLite DB (`~/.local/share/opencode/opencode.db`). The live
+ * tailer is `OpencodeReader` (polls the DB); this module holds the pure row→event mapping it shares
+ * with the replay / recap paths (`session_get`, device recap).
+ *
+ * On-disk shapes (validated against opencode 1.18.6):
+ * message.data = { role:'user'|'assistant', model:{providerID,modelID}, parentID?, path:{cwd,root}, tokens{…} }
+ * part.data = discriminated by `type`:
+ * text{text} · reasoning{text} · step-start{} · step-finish{reason:'stop',…} ·
+ * tool{tool, state:{status:'pending'|'running'|'completed'|'error', input, output, title}}
+ */
+
+import type { LastTurnText, SessionEvent, SubagentSummary } from '../../lib/normalize.js'
+
+export const MAX_OUTPUT = 2_000
+export const MAX_THINKING = 500
+
+export interface OcPart {
+ id: string
+ type: string
+ data: Record<string, unknown>
+}
+
+export interface OcMessage {
+ id: string
+ role: string
+ timeCreated: number
+ data: Record<string, unknown>
+ parts: OcPart[]
+}
+
+export function object(value: unknown): Record<string, unknown> | null {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+ ? value as Record<string, unknown>
+ : null
+}
+
+export function str(value: unknown): string {
+ return typeof value === 'string' ? value : ''
+}
+
+export function clip(value: string, limit: number): string {
+ return value.length > limit ? `${value.slice(0, limit)}\n…[truncated]` : value
+}
+
+/** OpenCode tool ids are lowercase (`bash`, `edit`, …). Map to the Claude vocabulary the UI renders. */
+const TOOL_NAMES: Record<string, string> = {
+ bash: 'Bash',
+ edit: 'Edit',
+ multiedit: 'Edit',
+ patch: 'Edit',
+ write: 'Write',
+ read: 'Read',
+ grep: 'Grep',
+ glob: 'Glob',
+ list: 'LS',
+ ls: 'LS',
+ webfetch: 'WebFetch',
+ websearch: 'WebSearch',
+ todowrite: 'TodoWrite',
+ todoread: 'TodoRead',
+ task: 'Task',
+ // OpenCode asks the user through `question`, and its arguments are already the claude shape
+ // (`{questions:[{question, header, options:[{label, description}]}]}` — read from its own DB), so the
+ // name is the only translation needed for the web's question box and the device's question screen.
+ question: 'AskUserQuestion',
+}
+
+export function opencodeToolName(name: string): string {
+ const key = name.toLowerCase()
+ if (TOOL_NAMES[key]) return TOOL_NAMES[key]
+ return name ? name.charAt(0).toUpperCase() + name.slice(1) : 'tool'
+}
+
+export function toolOutputText(value: unknown): string {
+ if (typeof value === 'string') return value
+ if (value == null) return ''
+ const o = object(value)
+ if (o && typeof o.text === 'string') return o.text
+ try { return JSON.stringify(value) ?? '' } catch { return String(value) }
+}
+
+export function toolSummary(name: string, output: string, isError: boolean): string {
+ const first = output.split('\n').map((line) => line.trim()).find(Boolean) ?? ''
+ if (isError) return first ? `${name} failed: ${first}` : `${name} failed`
+ return first || `${name} completed`
+}
+
+/** The plain text of a user message (its `text` parts joined). */
+export function userMessageText(msg: OcMessage): string {
+ return msg.parts
+ .filter((p) => p.type === 'text')
+ .map((p) => str(p.data.text))
+ .filter(Boolean)
+ .join('\n')
+ .trim()
+}
+
+/** Assistant text (its `text` parts joined) — for recap. */
+export function assistantMessageText(msg: OcMessage): string {
+ return msg.parts
+ .filter((p) => p.type === 'text')
+ .map((p) => str(p.data.text))
+ .filter(Boolean)
+ .join('')
+ .trim()
+}
+
+/** A completed assistant message has a `step-finish` part with reason `stop`. */
+export function isAssistantDone(msg: OcMessage): boolean {
+ return msg.parts.some((p) => p.type === 'step-finish' && str(p.data.reason) === 'stop')
+}
+
+/** Aggregates read from a sub-agent's OWN (child) opencode session. */
+export interface ChildStats { totalToolUseCount: number; totalTokens?: number }
+
+export function isTaskPart(part: OcPart): boolean {
+ return part.type === 'tool' && str(part.data.tool).toLowerCase() === 'task'
+}
+
+/** The `<task_result>…</task_result>` body of a Task tool's output, else the raw text. */
+export function extractTaskResult(output: string): string {
+ const m = /<task_result>\s*([\s\S]*?)\s*<\/task_result>/.exec(output)
+ return (m ? m[1] : output).trim()
+}
+
+/** OpenCode's `task` tool spawns a sub-agent (a child session). Render it like Claude/Codex Task cards. */
+export function taskStartEvent(part: OcPart): SessionEvent {
+ const input = object((object(part.data.state) ?? {}).input) ?? {}
+ const description = str(input.description) || str(input.prompt).slice(0, 80) || 'Delegated task'
+ const subagentType = str(input.subagent_type) || 'agent'
+ return { type: 'tool_start', payload: { id: part.id, tool: 'Task', input: { subagent_type: subagentType, description } } }
+}
+
+export function taskEndEvent(part: OcPart, childStats?: ChildStats): SessionEvent {
+ const state = object(part.data.state) ?? {}
+ const input = object(state.input) ?? {}
+ const meta = object(state.metadata) ?? {}
+ const time = object(state.time) ?? {}
+ const durationMs = (Number(time.end) || 0) - (Number(time.start) || 0)
+ const output = extractTaskResult(toolOutputText(state.output))
+ const isError = str(state.status) === 'error'
+ const subagent: SubagentSummary = {
+ agentId: str(meta.sessionId) || undefined,
+ agentType: str(input.subagent_type) || 'agent',
+ totalToolUseCount: childStats?.totalToolUseCount ?? 0,
+ totalTokens: childStats?.totalTokens ?? 0,
+ totalDurationMs: durationMs > 0 ? durationMs : 0,
+ }
+ return {
+ type: 'tool_end',
+ payload: { id: part.id, tool: 'Task', output: clip(output, MAX_OUTPUT), isError, summary: toolSummary('Task', output, isError), subagent },
+ }
+}
+
+/** Replay events for one assistant `tool` part. In-flight tools emit only `tool_start`. */
+export function toolPartEvents(part: OcPart): SessionEvent[] {
+ const state = object(part.data.state) ?? {}
+ const status = str(state.status)
+ const done = status === 'completed' || status === 'error'
+ if (isTaskPart(part)) return done ? [taskStartEvent(part), taskEndEvent(part)] : [taskStartEvent(part)]
+ const name = opencodeToolName(str(part.data.tool))
+ const id = part.id
+ const start: SessionEvent = {
+ type: 'tool_start',
+ payload: { id, tool: name, input: state.input ?? {} },
+ }
+ if (!done) return [start]
+ const output = toolOutputText(state.output)
+ const isError = status === 'error'
+ return [start, {
+ type: 'tool_end',
+ payload: { id, tool: name, output: clip(output, MAX_OUTPUT), isError, summary: toolSummary(name, output, isError) },
+ }]
+}
+
+/** Replay events for one part (assistant blocks only). */
+function partReplayEvents(part: OcPart, thinking: { n: number }): SessionEvent[] {
+ if (part.type === 'text') {
+ const text = str(part.data.text)
+ return text ? [{ type: 'text_delta', payload: { content: text } }] : []
+ }
+ if (part.type === 'reasoning') {
+ const text = str(part.data.text)
+ return text
+ ? [{ type: 'thinking_delta', payload: { content: clip(text, MAX_THINKING), thinkingId: `thinking-opencode-${thinking.n++}` } }]
+ : []
+ }
+ if (part.type === 'tool') return toolPartEvents(part)
+ return []
+}
+
+/** Full-session replay (session_get) — same render path as the live stream. */
+export function opencodeMessagesToEvents(messages: OcMessage[]): SessionEvent[] {
+ const events: SessionEvent[] = []
+ const thinking = { n: 0 }
+ for (const msg of messages) {
+ if (msg.role === 'user') {
+ const text = userMessageText(msg)
+ if (text) events.push({ type: 'user_message', payload: { content: text } })
+ continue
+ }
+ for (const part of msg.parts) events.push(...partReplayEvents(part, thinking))
+ }
+ events.push({ type: 'done', payload: { result: 'success' } })
+ return events
+}
+
+/** Last user prompt + the assistant text that followed it — the recap source of truth. */
+export function lastOpencodeTurnText(messages: OcMessage[]): LastTurnText | null {
+ let userMessage = ''
+ let assistantText = ''
+ for (const msg of messages) {
+ if (msg.role === 'user') {
+ const text = userMessageText(msg)
+ if (text) { userMessage = text; assistantText = '' }
+ continue
+ }
+ const text = assistantMessageText(msg)
+ if (text) assistantText += `${assistantText ? '\n\n' : ''}${text}`
+ }
+ return assistantText ? { userMessage, assistantText } : null
+}
+
+/**
+ * Turn-snapped pagination window over the message list, for `session_get {limit, before}`.
+ * `before` = `opencode:<index>` (exclusive upper bound = message index the client already holds).
+ * The window start snaps back to a user message so a turn is never split.
+ */
+export function windowOpencodeMessages(
+ messages: OcMessage[],
+ opts: { limit: number; before?: string },
+): { window: OcMessage[]; hasMore: boolean; oldestCursor: string | null; staleCursor?: boolean } {
+ let endIndex = messages.length
+ if (opts.before) {
+ const match = /^opencode:(\d+)$/.exec(opts.before)
+ if (!match) return { window: [], hasMore: false, oldestCursor: null, staleCursor: true }
+ endIndex = Number(match[1])
+ if (!Number.isSafeInteger(endIndex) || endIndex < 0 || endIndex > messages.length) {
+ return { window: [], hasMore: false, oldestCursor: null, staleCursor: true }
+ }
+ }
+ let start = Math.max(0, endIndex - opts.limit)
+ while (start > 0 && messages[start].role !== 'user') start--
+ return {
+ window: messages.slice(start, endIndex),
+ hasMore: start > 0,
+ oldestCursor: `opencode:${start}`,
+ }
+}
diff --git a/cli/src/engines/opencode/reader.spec.ts b/cli/src/engines/opencode/reader.spec.ts
new file mode 100644
index 000000000..4a339cafe
--- /dev/null
+++ b/cli/src/engines/opencode/reader.spec.ts
@@ -0,0 +1,133 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { execFileSync } from 'child_process'
+import { mkdtempSync, rmSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import { OpencodeReader, readOpencodeMessages } from './reader.js'
+import type { LiveEvent } from '../../lib/normalize.js'
+
+const hasSqlite = (() => {
+ try { execFileSync('sqlite3', ['-version'], { stdio: 'ignore' }); return true } catch { return false }
+})()
+const d = hasSqlite ? describe : describe.skip
+
+const SID = 'ses_testABC123'
+
+function run(db: string, sql: string): void {
+ execFileSync('sqlite3', [db, sql], { stdio: ['ignore', 'ignore', 'inherit'] })
+}
+function esc(v: unknown): string {
+ return JSON.stringify(v).replace(/'/g, "''")
+}
+function schema(db: string): void {
+ run(db,
+ 'CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, time_created INTEGER, data TEXT);' +
+ 'CREATE TABLE part (id TEXT PRIMARY KEY, message_id TEXT, session_id TEXT, time_created INTEGER, data TEXT);')
+}
+function insertMessage(
+ db: string, mid: string, tc: number, data: Record<string, unknown>,
+ parts: Array<{ id: string; tc: number; data: Record<string, unknown> }>,
+): void {
+ let sql = `INSERT INTO message VALUES ('${mid}','${SID}',${tc},'${esc(data)}');`
+ for (const p of parts) sql += `INSERT INTO part VALUES ('${p.id}','${mid}','${SID}',${p.tc},'${esc(p.data)}');`
+ run(db, sql)
+}
+const wait = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))
+
+d('OpencodeReader (sqlite3 CLI)', () => {
+ let dir = ''
+ let db = ''
+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'oc-reader-')); db = join(dir, 'opencode.db'); schema(db) })
+ afterEach(() => { rmSync(dir, { recursive: true, force: true }) })
+
+ it('reads messages grouped with their parts, ordered', async () => {
+ insertMessage(db, 'm1', 1, { role: 'user' }, [{ id: 'p1', tc: 1, data: { type: 'text', text: 'hi' } }])
+ insertMessage(db, 'm2', 2, { role: 'assistant' }, [
+ { id: 'p2', tc: 2, data: { type: 'text', text: 'hello' } },
+ { id: 'p3', tc: 3, data: { type: 'step-finish', reason: 'stop' } },
+ ])
+ const messages = await readOpencodeMessages(db, SID)
+ expect(messages.map((m) => m.role)).toEqual(['user', 'assistant'])
+ expect(messages[1].parts.map((p) => p.type)).toEqual(['text', 'step-finish'])
+ expect(messages[0].parts[0].data.text).toBe('hi')
+ })
+
+ it('rejects a non-id session (no injection surface)', async () => {
+ expect(await readOpencodeMessages(db, "x'; DROP TABLE message;--")).toEqual([])
+ })
+
+ it('hydrates silently, then streams a new turn incrementally', async () => {
+ // A pre-existing, completed turn: the reader must NOT replay it on attach.
+ insertMessage(db, 'm1', 1, { role: 'user' }, [{ id: 'p1', tc: 1, data: { type: 'text', text: 'old' } }])
+ insertMessage(db, 'm2', 2, { role: 'assistant' }, [
+ { id: 'p2', tc: 2, data: { type: 'text', text: 'done' } },
+ { id: 'p3', tc: 3, data: { type: 'step-finish', reason: 'stop' } },
+ ])
+ const events: LiveEvent[] = []
+ const reader = new OpencodeReader({ dbPath: db, sessionId: SID, onEvents: (e) => events.push(...e), pollMs: 30 })
+ await reader.start()
+ expect(events).toHaveLength(0) // hydrate = no replay
+
+ // A fresh turn arrives — a new user prompt, an assistant text, a tool, then a terminal step-finish.
+ insertMessage(db, 'm3', 10, { role: 'user' }, [{ id: 'p4', tc: 10, data: { type: 'text', text: 'who won?' } }])
+ insertMessage(db, 'm4', 11, { role: 'assistant' }, [
+ { id: 'p5', tc: 11, data: { type: 'text', text: 'Spain' } },
+ { id: 'p6', tc: 12, data: { type: 'tool', tool: 'webfetch', state: { status: 'completed', input: { url: 'u' }, output: 'ok' } } },
+ { id: 'p7', tc: 13, data: { type: 'step-finish', reason: 'stop' } },
+ ])
+ await wait(200)
+ reader.stop()
+
+ const types = events.map((e) => e.type)
+ expect(types).toContain('turn_started')
+ expect(types).toContain('text_delta')
+ expect(types).toContain('tool_start')
+ expect(types).toContain('tool_end')
+ expect(types).toContain('turn_ended')
+ const started = events.find((e) => e.type === 'turn_started')
+ expect(started).toMatchObject({ payload: { userMessage: 'who won?' } })
+ expect(reader.turnOpen).toBe(false) // closed by step-finish reason:stop
+ })
+
+ it('waits for a task part\'s input before announcing the sub-agent', async () => {
+ // opencode creates the `task` part when the call STARTS streaming, with `state.input` still empty, and
+ // fills the arguments in a moment later. Announcing on first sight gave every sub-agent the same
+ // `Delegated task` placeholder — measured live, two parallel sub-agents produced two identical rows.
+ insertMessage(db, 'm1', 1, { role: 'user' }, [{ id: 'p1', tc: 1, data: { type: 'text', text: 'old' } }])
+ insertMessage(db, 'm2', 2, { role: 'assistant' }, [{ id: 'p2', tc: 2, data: { type: 'step-finish', reason: 'stop' } }])
+ const events: LiveEvent[] = []
+ const reader = new OpencodeReader({ dbPath: db, sessionId: SID, onEvents: (e) => events.push(...e), pollMs: 30 })
+ await reader.start()
+
+ insertMessage(db, 'm3', 10, { role: 'user' }, [{ id: 'p3', tc: 10, data: { type: 'text', text: 'spawn two' } }])
+ insertMessage(db, 'm4', 11, { role: 'assistant' }, [
+ { id: 'p4', tc: 11, data: { type: 'tool', tool: 'task', state: { status: 'running', input: {} } } },
+ ])
+ await wait(120)
+ expect(events.filter((e) => e.type === 'tool_start')).toHaveLength(0) // nothing worth showing yet
+
+ run(db, `UPDATE part SET data='${esc({ type: 'tool', tool: 'task', state: { status: 'running', input: { description: 'Count .md files', subagent_type: 'general' } } })}' WHERE id='p4';`)
+ await wait(120)
+ reader.stop()
+
+ const start = events.find((e) => e.type === 'tool_start')
+ expect(start).toMatchObject({ payload: { tool: 'Task', input: { description: 'Count .md files' } } })
+ })
+
+ it('emits text deltas incrementally as an assistant message grows', async () => {
+ const events: LiveEvent[] = []
+ const reader = new OpencodeReader({ dbPath: db, sessionId: SID, onEvents: (e) => events.push(...e), pollMs: 30 })
+ await reader.start()
+ insertMessage(db, 'm1', 5, { role: 'user' }, [{ id: 'p1', tc: 5, data: { type: 'text', text: 'go' } }])
+ insertMessage(db, 'm2', 6, { role: 'assistant' }, [{ id: 'p2', tc: 6, data: { type: 'text', text: 'Hel' } }])
+ await wait(120)
+ // The same part grows (streaming) — only the NEW suffix should be emitted.
+ run(db, `UPDATE part SET data='${esc({ type: 'text', text: 'Hello world' })}' WHERE id='p2';`)
+ await wait(120)
+ reader.stop()
+ const deltas = events.filter((e) => e.type === 'text_delta').map((e) => (e as { payload: { content: string } }).payload.content)
+ expect(deltas.join('')).toBe('Hello world')
+ expect(deltas).toContain('Hel')
+ expect(deltas).toContain('lo world')
+ })
+})
diff --git a/cli/src/engines/opencode/reader.ts b/cli/src/engines/opencode/reader.ts
new file mode 100644
index 000000000..2ece65229
--- /dev/null
+++ b/cli/src/engines/opencode/reader.ts
@@ -0,0 +1,297 @@
+/**
+ * OpenCode live tailer.
+ *
+ * OpenCode has no per-session transcript file — it writes `message`/`part` rows to a SQLite DB. We
+ * cannot byte-offset-tail it, so this reader **polls** the DB every ~1s via the `sqlite3` CLI (shelled
+ * out, like tmux/git — keeps the adapter's single pure-JS bundle intact; no native SQLite dependency)
+ * and diffs against per-part state to emit incremental `LiveEvent`s into the same
+ * `emitSessionEvents` funnel the file-based engines use.
+ *
+ * opencode 1.18.6 writes the legacy `message`/`part` tables (the newer `session_message`/`seq` tables
+ * exist but are empty), so those are the primary cursor.
+ */
+
+import { execFile } from 'child_process'
+import { promisify } from 'util'
+import type { LiveEvent } from '../../lib/normalize.js'
+import {
+ MAX_OUTPUT, MAX_THINKING, clip, object, str,
+ opencodeToolName, toolOutputText, toolSummary, userMessageText,
+ isTaskPart, taskStartEvent, taskEndEvent,
+ type OcMessage, type OcPart, type ChildStats,
+} from './normalizer.js'
+
+const execFileAsync = promisify(execFile)
+
+const ID_RE = /^[A-Za-z0-9_]+$/
+const POLL_MS = 1_000
+const MAX_BUFFER = 32 * 1024 * 1024
+
+function parseJson(text: unknown): Record<string, unknown> {
+ if (typeof text !== 'string') return object(text) ?? {}
+ try { return object(JSON.parse(text)) ?? {} } catch { return {} }
+}
+
+interface Cursor { tc: number; id: string }
+
+/**
+ * Read messages (+ their parts) for one session from opencode.db via the `sqlite3` CLI.
+ * `after` restricts to messages strictly after that boundary (for incremental polling).
+ * Opens the DB with `query_only` + a busy timeout so it never contends with opencode's writer.
+ * Throws `OpencodeSqliteMissing` if the `sqlite3` binary is absent.
+ */
+export async function readOpencodeMessages(
+ dbPath: string,
+ sessionId: string,
+ after?: Cursor | null,
+): Promise<OcMessage[]> {
+ if (!ID_RE.test(sessionId)) return []
+ const cond = after && ID_RE.test(after.id) && Number.isFinite(after.tc)
+ ? `AND (m.time_created > ${Math.trunc(after.tc)} OR (m.time_created = ${Math.trunc(after.tc)} AND m.id > '${after.id}'))`
+ : ''
+ const sql =
+ `SELECT m.id AS mid, m.time_created AS mtc, m.data AS mdata, p.id AS pid, p.data AS pdata ` +
+ `FROM message m LEFT JOIN part p ON p.message_id = m.id ` +
+ `WHERE m.session_id = '${sessionId}' ${cond} ` +
+ `ORDER BY m.time_created, m.id, p.time_created, p.id;`
+
+ let stdout: string
+ try {
+ // `.timeout` is the silent dot-command form (the `PRAGMA busy_timeout=…` form prints a JSON row
+ // under -json, which would corrupt the single-array parse below). query_only guards against writes.
+ ({ stdout } = await execFileAsync(
+ 'sqlite3',
+ ['-json', '-cmd', '.timeout 3000', '-cmd', 'PRAGMA query_only=1', dbPath, sql],
+ { maxBuffer: MAX_BUFFER },
+ ))
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') throw new OpencodeSqliteMissing()
+ return [] // db locked / transient — retry next tick
+ }
+
+ const trimmed = stdout.trim()
+ if (!trimmed) return []
+ let rows: Array<Record<string, unknown>>
+ try { rows = JSON.parse(trimmed) } catch { return [] }
+
+ const byId = new Map<string, OcMessage>()
+ const order: string[] = []
+ for (const row of rows) {
+ const mid = str(row.mid)
+ if (!mid) continue
+ let msg = byId.get(mid)
+ if (!msg) {
+ const mdata = parseJson(row.mdata)
+ msg = { id: mid, role: str(mdata.role), timeCreated: Number(row.mtc) || 0, data: mdata, parts: [] }
+ byId.set(mid, msg)
+ order.push(mid)
+ }
+ const pid = str(row.pid)
+ if (pid) {
+ const pdata = parseJson(row.pdata)
+ msg.parts.push({ id: pid, type: str(pdata.type), data: pdata })
+ }
+ }
+ return order.map((id) => byId.get(id)!)
+}
+
+export class OpencodeSqliteMissing extends Error {
+ constructor() { super('sqlite3 CLI not found on PATH — OpenCode sessions cannot be mirrored') }
+}
+
+export interface OpencodeReaderDeps {
+ dbPath: string
+ sessionId: string
+ onEvents: (events: LiveEvent[]) => void
+ /** Reports the one-time fatal "sqlite3 missing" so the caller can warn + stop the reader. */
+ onFatal?: (err: Error) => void
+ pollMs?: number
+}
+
+/** Is a message a closed boundary? user messages always are; assistants when `step-finish reason:stop`. */
+function isDone(msg: OcMessage): boolean {
+ if (msg.role !== 'assistant') return true
+ return msg.parts.some((p) => p.type === 'step-finish' && str(p.data.reason) === 'stop')
+}
+
+export class OpencodeReader {
+ private timer: NodeJS.Timeout | null = null
+ private polling = false
+ private open = false
+ private thinking = 0
+ private cursor: Cursor | null = null
+ private readonly emittedText = new Map<string, number>() // partId → chars already emitted
+ private readonly thinkingIds = new Map<string, string>() // reasoning partId → stable thinkingId
+ private readonly toolStarted = new Set<string>()
+ private readonly toolEnded = new Set<string>()
+ private readonly seenUser = new Set<string>()
+
+ constructor(private readonly deps: OpencodeReaderDeps) {}
+
+ get turnOpen(): boolean { return this.open }
+ closeTurn(): void { this.open = false }
+
+ /** Hydrate silently (no replay), then start polling. */
+ async start(): Promise<void> {
+ try {
+ const all = await readOpencodeMessages(this.deps.dbPath, this.deps.sessionId, null)
+ this.hydrate(all)
+ } catch (err) {
+ if (err instanceof OpencodeSqliteMissing) { this.deps.onFatal?.(err); return }
+ }
+ this.timer = setInterval(() => { void this.tick() }, this.deps.pollMs ?? POLL_MS)
+ }
+
+ stop(): void {
+ if (this.timer) { clearInterval(this.timer); this.timer = null }
+ }
+
+ /** Seed state from existing rows without emitting, so we only stream NEW activity after attach. */
+ private hydrate(messages: OcMessage[]): void {
+ if (messages.length === 0) return
+ // Find the last closed boundary; everything up to it is "already seen".
+ let boundary = -1
+ for (let i = messages.length - 1; i >= 0; i--) { if (isDone(messages[i])) { boundary = i; break } }
+ const done = boundary >= 0 ? messages[boundary] : null
+ this.cursor = done ? { tc: done.timeCreated, id: done.id } : null
+ for (const msg of messages) {
+ if (msg.role === 'user') this.seenUser.add(msg.id)
+ for (const part of msg.parts) this.seedPart(part)
+ }
+ // A trailing in-flight assistant means a turn is open (attached mid-turn).
+ const tail = messages[messages.length - 1]
+ this.open = tail.role === 'assistant' && !isDone(tail)
+ }
+
+ private seedPart(part: OcPart): void {
+ if (part.type === 'text' || part.type === 'reasoning') {
+ this.emittedText.set(part.id, str(part.data.text).length)
+ } else if (part.type === 'tool') {
+ this.toolStarted.add(part.id)
+ const status = str((object(part.data.state) ?? {}).status)
+ if (status === 'completed' || status === 'error') this.toolEnded.add(part.id)
+ }
+ }
+
+ private async tick(): Promise<void> {
+ if (this.polling) return
+ this.polling = true
+ try {
+ const batch = await readOpencodeMessages(this.deps.dbPath, this.deps.sessionId, this.cursor)
+ if (batch.length === 0) return
+ const events: LiveEvent[] = []
+ for (const msg of batch) events.push(...await this.processMessage(msg))
+ // Advance the cursor past the trailing run of closed messages; keep an in-flight tail for re-read.
+ for (let i = batch.length - 1; i >= 0; i--) {
+ if (isDone(batch[i])) { this.cursor = { tc: batch[i].timeCreated, id: batch[i].id }; break }
+ }
+ if (events.length) this.deps.onEvents(events)
+ } catch (err) {
+ if (err instanceof OpencodeSqliteMissing) { this.stop(); this.deps.onFatal?.(err) }
+ } finally {
+ this.polling = false
+ }
+ }
+
+ private async processMessage(msg: OcMessage): Promise<LiveEvent[]> {
+ if (msg.role === 'user') {
+ if (this.seenUser.has(msg.id)) return []
+ this.seenUser.add(msg.id)
+ const events: LiveEvent[] = []
+ if (this.open) events.push({ type: 'turn_ended', payload: {} })
+ this.open = true
+ events.push({ type: 'turn_started', payload: { userMessage: userMessageText(msg) } })
+ return events
+ }
+ const events: LiveEvent[] = []
+ for (const part of msg.parts) {
+ if (isTaskPart(part)) events.push(...await this.processTaskPart(part))
+ else events.push(...this.processPart(part))
+ }
+ return events
+ }
+
+ /** A `task` tool part spawns a sub-agent child session — emit Task start/end, reading the child
+ * session for its tool-call count so the device/web Task card shows "N toolcalls" like the others. */
+ private async processTaskPart(part: OcPart): Promise<LiveEvent[]> {
+ const state = object(part.data.state) ?? {}
+ const events: LiveEvent[] = []
+ const status = str(state.status)
+ // opencode writes the part as soon as the tool call starts streaming, BEFORE its arguments are
+ // filled in — so announcing on first sight labelled every sub-agent with the `Delegated task`
+ // fallback (measured live: two parallel sub-agents, two identical rows). Wait for the input; the row
+ // is worth nothing without its description, and it lands within the same poll or the next.
+ const described = Object.keys(object(state.input) ?? {}).length > 0
+ const settled = status === 'completed' || status === 'error'
+ if (!this.toolStarted.has(part.id) && (described || settled)) {
+ this.toolStarted.add(part.id)
+ events.push(taskStartEvent(part))
+ }
+ if (settled && !this.toolEnded.has(part.id)) {
+ this.toolEnded.add(part.id)
+ const childId = str((object(state.metadata) ?? {}).sessionId)
+ const childStats = childId ? await this.childStats(childId) : undefined
+ events.push(taskEndEvent(part, childStats))
+ }
+ return events
+ }
+
+ private async childStats(childId: string): Promise<ChildStats> {
+ try {
+ const msgs = await readOpencodeMessages(this.deps.dbPath, childId)
+ let tools = 0
+ let tokens = 0
+ for (const m of msgs) {
+ for (const p of m.parts) if (p.type === 'tool' && !isTaskPart(p)) tools++
+ const t = object(m.data.tokens) ?? {}
+ tokens += (Number(t.input) || 0) + (Number(t.output) || 0)
+ }
+ return { totalToolUseCount: tools, totalTokens: tokens || undefined }
+ } catch { return { totalToolUseCount: 0 } }
+ }
+
+ private processPart(part: OcPart): LiveEvent[] {
+ if (part.type === 'text') {
+ const full = str(part.data.text)
+ const seen = this.emittedText.get(part.id) ?? 0
+ if (full.length <= seen) return []
+ this.emittedText.set(part.id, full.length)
+ return [{ type: 'text_delta', payload: { content: full.slice(seen) } }]
+ }
+ if (part.type === 'reasoning') {
+ const full = str(part.data.text)
+ const seen = this.emittedText.get(part.id) ?? 0
+ if (full.length <= seen) return []
+ this.emittedText.set(part.id, full.length)
+ let thinkingId = this.thinkingIds.get(part.id)
+ if (!thinkingId) { thinkingId = `thinking-opencode-${this.thinking++}`; this.thinkingIds.set(part.id, thinkingId) }
+ return [{ type: 'thinking_delta', payload: { content: clip(full.slice(seen), MAX_THINKING), thinkingId } }]
+ }
+ if (part.type === 'tool') {
+ const events: LiveEvent[] = []
+ const state = object(part.data.state) ?? {}
+ const name = opencodeToolName(str(part.data.tool))
+ if (!this.toolStarted.has(part.id)) {
+ this.toolStarted.add(part.id)
+ events.push({ type: 'tool_start', payload: { id: part.id, tool: name, input: state.input ?? {} } })
+ }
+ const status = str(state.status)
+ if ((status === 'completed' || status === 'error') && !this.toolEnded.has(part.id)) {
+ this.toolEnded.add(part.id)
+ const output = toolOutputText(state.output)
+ const isError = status === 'error'
+ events.push({
+ type: 'tool_end',
+ payload: { id: part.id, tool: name, output: clip(output, MAX_OUTPUT), isError, summary: toolSummary(name, output, isError) },
+ })
+ }
+ return events
+ }
+ if (part.type === 'step-finish' && str(part.data.reason) === 'stop') {
+ if (!this.open) return []
+ this.open = false
+ return [{ type: 'turn_ended', payload: {} }]
+ }
+ return []
+ }
+}
diff --git a/cli/src/engines/opencode/runtimeProfile.spec.ts b/cli/src/engines/opencode/runtimeProfile.spec.ts
new file mode 100644
index 000000000..11e18cfbf
--- /dev/null
+++ b/cli/src/engines/opencode/runtimeProfile.spec.ts
@@ -0,0 +1,109 @@
+import { describe, expect, it } from 'vitest'
+import {
+ countOpencodePickers,
+ opencodeFooterModelId,
+ opencodeRowMatches,
+ parseOpencodeModelsOutput,
+ parseOpencodePickerRows,
+} from './runtimeProfile.js'
+
+// Real `opencode models` lines from this computer (opencode 1.18.7), including the nested-model form.
+const OUTPUT = [
+ 'opencode/ling-3.0-flash-free',
+ 'opencode-go/kimi-k3',
+ 'opencode-go/minimax-m3',
+ 'opencode-go/mimo-v2.5',
+ 'opencode-go/mimo-v2.5-pro',
+ 'vibe/minimax/minimax-m3',
+ 'not a model line',
+].join('\n')
+
+const catalog = parseOpencodeModelsOutput(OUTPUT)
+
+describe('opencode model catalog', () => {
+ it('reads provider/model and builds a picker filter from the model leaf plus provider', () => {
+ expect(catalog.map((t) => t.id)).toEqual([
+ 'opencode/ling-3.0-flash-free',
+ 'opencode-go/kimi-k3',
+ 'opencode-go/minimax-m3',
+ 'opencode-go/mimo-v2.5',
+ 'opencode-go/mimo-v2.5-pro',
+ 'vibe/minimax/minimax-m3',
+ ])
+ // The picker renders the model's LAST segment, so that is what the filter is built from.
+ expect(catalog.find((t) => t.id === 'vibe/minimax/minimax-m3')?.filter).toBe('minimax m3 vibe')
+ expect(catalog.find((t) => t.id === 'opencode-go/kimi-k3')?.filter).toBe('kimi k3 opencode go')
+ })
+
+ it('parses the picker rows between its header and the hint line', () => {
+ // Verbatim from the live picker, filtered to "minimax m3": two rows that differ only by provider.
+ const capture = [
+ ' Select model esc',
+ ' minimax m3',
+ ' MiniMax-M3 OpenCode Go',
+ ' ● MiniMax M3 (vibe) Vibe Gateway (Minimax)',
+ ' Connect provider ctrl+a Favorite ctrl+f',
+ ' ┃ Ask anything...',
+ ].join('\n')
+
+ const rows = parseOpencodePickerRows(capture)
+ // The filter box ("minimax m3") sits between the header and the rows and must not be counted as one.
+ expect(rows).toEqual([
+ { display: 'MiniMax-M3', provider: 'OpenCode Go', current: false },
+ { display: 'MiniMax M3 (vibe)', provider: 'Vibe Gateway (Minimax)', current: true },
+ ])
+ expect(parseOpencodePickerRows('no picker here')).toBeNull()
+ })
+
+ it('reads the CURRENT picker, not an earlier one left in the scrollback', () => {
+ // A tmux capture carries history; the pane really does hold several openings of the same picker.
+ const stale = [
+ ' Select model esc',
+ ' kimi',
+ ' Kimi K3 (2x usage) OpenCode Go',
+ ' Kimi K2.6 OpenCode Go',
+ ' Connect provider ctrl+a Favorite ctrl+f',
+ ' Select model esc',
+ ' kimi k3 opencode go',
+ ' Kimi K3 (2x usage) OpenCode Go',
+ ' Connect provider ctrl+a Favorite ctrl+f',
+ ].join('\n')
+
+ expect(parseOpencodePickerRows(stale)).toEqual([
+ { display: 'Kimi K3 (2x usage)', provider: 'OpenCode Go', current: false },
+ ])
+ })
+
+ it('counts picker openings so a stale one cannot pass for a fresh one', () => {
+ const two = [' Select model esc', ' kimi', ' Select model esc', ' kimi k3'].join('\n')
+ expect(countOpencodePickers(two)).toBe(2)
+ expect(countOpencodePickers('nothing')).toBe(0)
+ })
+
+ it('tells two same-named models apart by provider', () => {
+ const rows = parseOpencodePickerRows([
+ ' Select model esc',
+ ' minimax m3',
+ ' MiniMax-M3 OpenCode Go',
+ ' ● MiniMax M3 (vibe) Vibe Gateway (Minimax)',
+ ' Connect provider ctrl+a',
+ ].join('\n'))!
+ const go = catalog.find((t) => t.id === 'opencode-go/minimax-m3')!
+ const vibe = catalog.find((t) => t.id === 'vibe/minimax/minimax-m3')!
+
+ expect(rows.filter((r) => opencodeRowMatches(go, r))).toEqual([rows[0]])
+ expect(rows.filter((r) => opencodeRowMatches(vibe, r))).toEqual([rows[1]])
+ })
+
+ it('resolves the footer back to a catalog id, longest model name first', () => {
+ // Both footers are real: before and after the probe switched the model.
+ expect(opencodeFooterModelId('┃ Build · MiniMax M3 (vibe) Vibe Gateway (Minimax)', catalog))
+ .toBe('vibe/minimax/minimax-m3')
+ expect(opencodeFooterModelId('┃ Build · Ling-3.0-flash Free OpenCode Zen', catalog))
+ .toBe('opencode/ling-3.0-flash-free')
+ // `MiMo V2.5 Pro` must not collapse onto `mimo-v2.5`.
+ expect(opencodeFooterModelId('┃ Build · MiMo V2.5 Pro OpenCode Go', catalog))
+ .toBe('opencode-go/mimo-v2.5-pro')
+ expect(opencodeFooterModelId('┃ Ask anything...', catalog)).toBeNull()
+ })
+})
diff --git a/cli/src/engines/opencode/runtimeProfile.ts b/cli/src/engines/opencode/runtimeProfile.ts
new file mode 100644
index 000000000..275fa6a4c
--- /dev/null
+++ b/cli/src/engines/opencode/runtimeProfile.ts
@@ -0,0 +1,124 @@
+/**
+ * OpenCode model catalog → runtime-profile options.
+ *
+ * `opencode models` prints one `provider/model` per line on stdout, and that is the whole catalog:
+ *
+ * opencode/ling-3.0-flash-free
+ * opencode-go/kimi-k3
+ * vibe/minimax/minimax-m3
+ *
+ * OpenCode has **no effort axis** — every option is `@auto`, and the label is the model alone.
+ *
+ * Switching is a picker (`/models`), but unlike Command Code's it accepts typed input, which is what
+ * makes it safe to drive: type a filter, and act only once the list has narrowed to exactly ONE row.
+ * Never arrow blindly through it — that is what the Command Code revert (2026-07-30) was about.
+ * The filter matches across the model AND provider columns, which is how two rows that share a model
+ * name (`MiniMax-M3` on OpenCode Go vs `MiniMax M3 (vibe)` on Vibe Gateway) are told apart.
+ */
+
+export interface OpencodeModelTarget {
+ /** `<provider>/<model>` exactly as `opencode models` prints it. */
+ id: string
+ provider: string
+ model: string
+ /** What the picker filter is fed: model words, then provider words to disambiguate. */
+ filter: string
+}
+
+export interface OpencodePickerRow {
+ display: string
+ provider: string
+ /** OpenCode marks the running model with `●`. */
+ current: boolean
+}
+
+function words(value: string): string {
+ return value.replace(/[^a-z0-9.]+/gi, ' ').trim().toLowerCase()
+}
+
+function squash(value: string): string {
+ return value.replace(/[^a-z0-9]+/gi, '').toLowerCase()
+}
+
+/** Parse `opencode models`; anything that is not a `provider/model` line is ignored. */
+export function parseOpencodeModelsOutput(output: string): OpencodeModelTarget[] {
+ const targets: OpencodeModelTarget[] = []
+ const seen = new Set<string>()
+ for (const rawLine of output.split('\n')) {
+ const id = rawLine.trim()
+ if (!/^[a-z0-9][\w.-]*\/[\w./-]+$/i.test(id) || seen.has(id)) continue
+ seen.add(id)
+ const slash = id.indexOf('/')
+ const provider = id.slice(0, slash)
+ const model = id.slice(slash + 1)
+ // The picker shows the model's LAST segment (`minimax/minimax-m3` renders as "MiniMax M3"), so the
+ // filter is built from that plus the provider.
+ const leaf = model.slice(model.lastIndexOf('/') + 1)
+ targets.push({ id, provider, model, filter: `${words(leaf)} ${words(provider)}`.trim() })
+ }
+ return targets
+}
+
+/**
+ * Rows currently listed by the `/models` picker. The list is bounded above by its own header and below by
+ * the "Connect provider" hint; reading only between them keeps the composer and the banner out.
+ */
+export function parseOpencodePickerRows(capture: string): OpencodePickerRow[] | null {
+ const lines = capture.split('\n').map((line) => line.replace(/\s+$/, ''))
+ // LAST header, not the first: a capture carries scrollback, so an earlier opening of the same picker is
+ // usually still up there — reading from it parsed a stale, differently-filtered row set.
+ const header = lines.findLastIndex((line) => /\bSelect model\b/.test(line))
+ if (header < 0) return null
+ const end = lines.findIndex((line, index) => index > header && /Connect provider/i.test(line))
+ const rows: OpencodePickerRow[] = []
+ for (const line of lines.slice(header + 1, end < 0 ? lines.length : end)) {
+ const text = line.trim()
+ if (!text) continue
+ const current = text.startsWith('●')
+ const cells = text.replace(/^●\s*/, '').split(/\s{3,}/).map((cell) => cell.trim()).filter(Boolean)
+ // A model row is TWO cells — model and provider. Counting by position instead put the filter box
+ // (one cell, the text just typed) in the row set, so a list narrowed to one model read as two rows
+ // and every switch was refused. Provider group headings are single-cell too, and drop out here.
+ if (cells.length < 2) continue
+ rows.push({ display: cells[0], provider: cells[1], current })
+ }
+ return rows
+}
+
+/**
+ * How many times the `/models` picker appears in a capture. A tmux capture includes scrollback, so the
+ * only way to tell "the picker I just opened" from "a picker I opened a minute ago" is that the count went
+ * up — see setOpencode.
+ */
+export function countOpencodePickers(capture: string): number {
+ return capture.split('\n').filter((line) => /\bSelect model\b/.test(line)).length
+}
+
+/** True when a picker row is the catalog entry we are trying to select. */
+export function opencodeRowMatches(target: OpencodeModelTarget, row: OpencodePickerRow): boolean {
+ const leaf = target.model.slice(target.model.lastIndexOf('/') + 1)
+ return squash(row.display).startsWith(squash(leaf))
+ && squash(`${row.display} ${row.provider}`).includes(squash(target.provider))
+}
+
+/**
+ * Resolve OpenCode's footer (`Build · MiniMax M3 (vibe) Vibe Gateway (Minimax)`) back to a catalog id.
+ * Both halves are needed: the model name alone is ambiguous across providers, and the provider alone
+ * cannot name a model. The longest model match wins so `MiMo V2.5 Pro` never resolves to `mimo-v2.5`.
+ */
+export function opencodeFooterModelId(capture: string, catalog: OpencodeModelTarget[]): string | null {
+ const line = capture.split('\n').map((l) => l.trim()).reverse()
+ .find((l) => /·/.test(l) && /\b(Build|Plan)\b/i.test(l))
+ if (!line) return null
+ const tail = squash(line.slice(line.indexOf('·') + 1))
+ if (!tail) return null
+
+ let best: { id: string; length: number } | null = null
+ for (const entry of catalog) {
+ const leaf = squash(entry.model.slice(entry.model.lastIndexOf('/') + 1))
+ if (!leaf || !tail.startsWith(leaf)) continue
+ if (!tail.includes(squash(entry.provider))) continue
+ if (!best || leaf.length > best.length) best = { id: entry.id, length: leaf.length }
+ }
+ return best?.id ?? null
+}
diff --git a/cli/src/engines/pi/normalizer.spec.ts b/cli/src/engines/pi/normalizer.spec.ts
new file mode 100644
index 000000000..7c4f62778
--- /dev/null
+++ b/cli/src/engines/pi/normalizer.spec.ts
@@ -0,0 +1,122 @@
+import { describe, expect, it } from 'vitest'
+import {
+ PiNormalizer,
+ piMessagesToEvents,
+ lastPiTurnText,
+ piSessionMeta,
+ piToolName,
+ windowPiLines,
+} from './normalizer.js'
+
+// Fixtures copied from a REAL local Pi session (pi 0.82.1, provider vibe / minimax-m3):
+// header → model_change → thinking_level_change → user → assistant(toolUse) → toolResult → assistant(stop).
+const CALL_ID = 'chatcmpl-tool-873e31c30f939d10'
+const LINES = [
+ '{"type":"session","version":3,"id":"019fa2a5-a26d-700c-bf8c-97af19ae3d5f","timestamp":"2026-07-27T08:16:31.854Z","cwd":"/tmp/pi-probe"}',
+ '{"type":"model_change","id":"45215278","parentId":null,"model":"minimax/minimax-m3"}',
+ '{"type":"thinking_level_change","id":"1da16955","parentId":"45215278","level":"medium"}',
+ '{"type":"message","id":"b0ecca48","parentId":"1da16955","message":{"role":"user","content":[{"type":"text","text":"list the files here"}]}}',
+ `{"type":"message","id":"0fc9ca48","parentId":"b0ecca48","message":{"role":"assistant","content":[{"type":"thinking","thinking":"I should run ls."},{"type":"toolCall","id":"${CALL_ID}","name":"bash","arguments":{"command":"ls"}}],"stopReason":"toolUse","model":"minimax/minimax-m3","provider":"vibe"}}`,
+ `{"type":"message","id":"1a2b3c4d","parentId":"0fc9ca48","message":{"role":"toolResult","toolCallId":"${CALL_ID}","toolName":"bash","content":[{"type":"text","text":"a.txt\\nb.txt\\n"}],"isError":false}}`,
+ '{"type":"message","id":"9f8e7d6c","parentId":"1a2b3c4d","message":{"role":"assistant","content":[{"type":"thinking","thinking":"Files listed."},{"type":"text","text":"DONE"}],"stopReason":"stop","model":"minimax/minimax-m3"}}',
+]
+
+function live(lines: string[]) {
+ const normalizer = new PiNormalizer('live')
+ return { normalizer, events: lines.flatMap((line) => normalizer.ingest(line)) }
+}
+
+describe('PiNormalizer — live turn derivation', () => {
+ it('derives the turn lifecycle from message roles + stopReason (no turn markers on disk)', () => {
+ const { normalizer, events } = live(LINES)
+ expect(events.map((e) => e.type)).toEqual([
+ 'turn_started', // user message
+ 'thinking_delta',
+ 'tool_start',
+ 'tool_end', // toolResult
+ 'thinking_delta',
+ 'text_delta',
+ 'turn_ended', // assistant stopReason 'stop' with no pending tools
+ ])
+ expect(events[0]).toMatchObject({ type: 'turn_started', payload: { userMessage: 'list the files here' } })
+ expect(normalizer.turnOpen).toBe(false)
+ })
+
+ it('keeps the turn OPEN while the assistant is calling a tool (stopReason "toolUse")', () => {
+ const { normalizer } = live(LINES.slice(0, 5)) // header … assistant(toolUse)
+ expect(normalizer.turnOpen).toBe(true)
+ })
+
+ it('maps a toolCall/toolResult pair onto the shared tool vocabulary, joined by toolCallId', () => {
+ const { events } = live(LINES)
+ const start = events.find((e) => e.type === 'tool_start')
+ const end = events.find((e) => e.type === 'tool_end')
+ expect(start).toMatchObject({ type: 'tool_start', payload: { id: CALL_ID, tool: 'Bash', input: { command: 'ls' } } })
+ expect(end).toMatchObject({ type: 'tool_end', payload: { id: CALL_ID, tool: 'Bash', output: 'a.txt\nb.txt\n', isError: false } })
+ })
+
+ it('ignores the header and non-message entries, and never throws on a malformed line', () => {
+ const normalizer = new PiNormalizer('live')
+ expect(normalizer.ingest(LINES[0])).toEqual([]) // session header
+ expect(normalizer.ingest(LINES[1])).toEqual([]) // model_change
+ expect(normalizer.ingest(LINES[2])).toEqual([]) // thinking_level_change
+ expect(normalizer.ingest('not json')).toEqual([])
+ expect(normalizer.ingest('null')).toEqual([])
+ expect(normalizer.ingest('')).toEqual([])
+ })
+
+ it('emits a context_compact indicator for a compaction entry', () => {
+ const normalizer = new PiNormalizer('live')
+ expect(normalizer.ingest('{"type":"compaction","id":"x"}').map((e) => e.type)).toEqual(['context_compact'])
+ })
+
+ it('closeTurn() clears the open turn and any pending tools', () => {
+ const { normalizer } = live(LINES.slice(0, 5))
+ normalizer.closeTurn()
+ expect(normalizer.turnOpen).toBe(false)
+ })
+
+ it('renders a `!cmd` bashExecution entry as a Bash card', () => {
+ const normalizer = new PiNormalizer('live')
+ const events = normalizer.ingest('{"type":"message","id":"be1","message":{"role":"bashExecution","command":"git status","output":"clean","exitCode":0}}')
+ expect(events.map((e) => e.type)).toEqual(['tool_start', 'tool_end'])
+ expect(events[0]).toMatchObject({ payload: { tool: 'Bash', input: { command: 'git status' } } })
+ })
+})
+
+describe('PiNormalizer — replay, recap, window', () => {
+ it('replays a session as user_message + assistant blocks, terminated by done', () => {
+ const events = piMessagesToEvents(LINES)
+ expect(events.map((e) => e.type)).toEqual([
+ 'user_message', 'thinking_delta', 'tool_start', 'tool_end', 'thinking_delta', 'text_delta', 'done',
+ ])
+ expect(events[0]).toMatchObject({ type: 'user_message', payload: { content: 'list the files here' } })
+ })
+
+ it('lastPiTurnText returns the last user prompt + the assistant text that followed', () => {
+ expect(lastPiTurnText(LINES)).toEqual({ userMessage: 'list the files here', assistantText: 'DONE' })
+ })
+
+ it('piSessionMeta reads the id + cwd from the header line', () => {
+ expect(piSessionMeta(LINES)).toEqual({ id: '019fa2a5-a26d-700c-bf8c-97af19ae3d5f', cwd: '/tmp/pi-probe' })
+ })
+
+ it('maps Pi lowercase tool names onto the shared vocabulary', () => {
+ expect(piToolName('bash')).toBe('Bash')
+ expect(piToolName('read')).toBe('Read')
+ expect(piToolName('find')).toBe('Glob')
+ expect(piToolName('ls')).toBe('LS')
+ expect(piToolName('somethingElse')).toBe('SomethingElse')
+ })
+
+ it('windowPiLines snaps the window start back to a user message', () => {
+ const w = windowPiLines(LINES, { limit: 2 })
+ expect(w.window[0]).toContain('"role":"user"')
+ expect(w.hasMore).toBe(true)
+ expect(w.oldestCursor).toBe('pi:3')
+ })
+
+ it('windowPiLines flags a malformed cursor as stale', () => {
+ expect(windowPiLines(LINES, { limit: 2, before: 'nope' }).staleCursor).toBe(true)
+ })
+})
diff --git a/cli/src/engines/pi/normalizer.ts b/cli/src/engines/pi/normalizer.ts
new file mode 100644
index 000000000..adb6d8828
--- /dev/null
+++ b/cli/src/engines/pi/normalizer.ts
@@ -0,0 +1,292 @@
+/**
+ * Pi (pi.dev) JSONL → shared event vocabulary.
+ *
+ * Pi writes one append-only JSONL per session under
+ * `<PI_HOME>/agent/sessions/--<mangled-cwd>--/<ISO-ts>_<uuid>.jsonl`, so it uses the same byte-offset
+ * tail as claude/codex — no custom reader. Verified against a real local session (pi 0.82.1):
+ *
+ * line 1 {"type":"session","version":3,"id":"<uuid>","cwd":"/abs/path"}
+ * then {"type":"message","id":"<8hex>","parentId":"<8hex>","message":{…}}
+ * {"type":"model_change"|"thinking_level_change"|"compaction"|"label"|…}
+ *
+ * message.role "user" content: string | [{type:'text',text}]
+ * "assistant" content: [{type:'thinking',thinking} | {type:'text',text}
+ * | {type:'toolCall',id,name,arguments}]
+ * + stopReason: 'toolUse' (continues) | 'stop' (done) | …
+ * "toolResult" {toolCallId, toolName, content:[{type:'text',text}], isError}
+ *
+ * Pi records NO turn markers in the file, so the lifecycle is derived exactly like the Claude
+ * normalizer: a user message opens a turn; an assistant message whose stopReason is not `toolUse`
+ * closes it once every tool call it made has been answered.
+ *
+ * NOTE: entries form a TREE (`id`/`parentId`) — `/tree` and `/fork` can branch the conversation. v1
+ * reads in file order, which matches the linear case (the overwhelming majority); a leaf→root walk is
+ * a follow-up.
+ */
+
+import type { EngineNormalizer } from '../types.js'
+import type { LastTurnText, LiveEvent, SessionEvent } from '../../lib/normalize.js'
+
+type JsonObject = Record<string, unknown>
+
+const MAX_OUTPUT = 2_000
+const MAX_THINKING = 500
+
+/** Pi's built-in tools are lowercase; map them onto the vocabulary the web/device cards render. */
+const TOOL_NAMES: Record<string, string> = {
+ read: 'Read',
+ write: 'Write',
+ edit: 'Edit',
+ bash: 'Bash',
+ grep: 'Grep',
+ find: 'Glob',
+ ls: 'LS',
+ list: 'LS',
+ webfetch: 'WebFetch',
+ websearch: 'WebSearch',
+ todowrite: 'TodoWrite',
+ todoread: 'TodoRead',
+ task: 'Task',
+}
+
+export function piToolName(name: string): string {
+ const key = name.toLowerCase()
+ if (TOOL_NAMES[key]) return TOOL_NAMES[key]
+ return name ? name.charAt(0).toUpperCase() + name.slice(1) : 'tool'
+}
+
+function object(value: unknown): JsonObject | null {
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value as JsonObject : null
+}
+
+function str(value: unknown): string {
+ return typeof value === 'string' ? value : ''
+}
+
+function parse(line: string): JsonObject | null {
+ try { return object(JSON.parse(line)) } catch { return null }
+}
+
+function clip(value: string, limit: number): string {
+ return value.length > limit ? `${value.slice(0, limit)}\n…[truncated]` : value
+}
+
+/** `content` is either a plain string or an array of typed parts — flatten the text of both. */
+function contentText(content: unknown): string {
+ if (typeof content === 'string') return content
+ if (!Array.isArray(content)) return ''
+ return content
+ .map((part) => {
+ const p = object(part)
+ return p && p.type === 'text' ? str(p.text) : ''
+ })
+ .filter(Boolean)
+ .join('')
+}
+
+function contentParts(content: unknown): JsonObject[] {
+ if (Array.isArray(content)) return content.map(object).filter((p): p is JsonObject => p !== null)
+ if (typeof content === 'string') return [{ type: 'text', text: content }]
+ return []
+}
+
+function toolSummary(name: string, output: string, isError: boolean): string {
+ const first = output.split('\n').map((line) => line.trim()).find(Boolean) ?? ''
+ if (isError) return first ? `${name} failed: ${first}` : `${name} failed`
+ return first || `${name} completed`
+}
+
+function compactEvent(): LiveEvent {
+ return {
+ type: 'context_compact',
+ payload: { message: 'Context was compacted — the previous conversation has been summarized to free up space.' },
+ }
+}
+
+/** A turn ends on any stop reason other than `toolUse` (which means the assistant is calling a tool). */
+function isTerminalStop(stopReason: string): boolean {
+ return !!stopReason && stopReason !== 'toolUse'
+}
+
+export class PiNormalizer implements EngineNormalizer {
+ private open = false
+ private pendingTools = new Set<string>()
+ private toolNames = new Map<string, string>()
+ private thinkingCounter = 0
+
+ constructor(private readonly mode: 'live' | 'replay') {}
+
+ get turnOpen(): boolean { return this.open }
+
+ closeTurn(): void { this.open = false; this.pendingTools.clear() }
+
+ ingest(line: string): LiveEvent[] {
+ const raw = parse(line)
+ if (!raw) return []
+ const type = str(raw.type)
+ if (type === 'compaction') return [compactEvent()]
+ if (type !== 'message') return [] // session header, model_change, thinking_level_change, label, …
+ const message = object(raw.message)
+ if (!message) return []
+
+ const role = str(message.role)
+ if (role === 'user') return this.userMessage(message)
+ if (role === 'assistant') return this.assistantMessage(message)
+ if (role === 'toolResult') return this.toolResult(message)
+ if (role === 'bashExecution') return this.bashExecution(raw, message)
+ return []
+ }
+
+ finishReplay(): LiveEvent[] {
+ return this.mode === 'replay' ? [{ type: 'done', payload: { result: 'success' } }] : []
+ }
+
+ private userMessage(message: JsonObject): LiveEvent[] {
+ const text = contentText(message.content).trim()
+ if (!text) return []
+ if (this.mode === 'replay') return [{ type: 'user_message', payload: { content: text } }]
+ const events: LiveEvent[] = []
+ if (this.open) events.push({ type: 'turn_ended', payload: {} })
+ this.open = true
+ this.pendingTools.clear()
+ events.push({ type: 'turn_started', payload: { userMessage: text } })
+ return events
+ }
+
+ private assistantMessage(message: JsonObject): LiveEvent[] {
+ const events: LiveEvent[] = []
+ for (const part of contentParts(message.content)) {
+ const type = str(part.type)
+ if (type === 'thinking') {
+ const thinking = str(part.thinking)
+ if (!thinking) continue
+ events.push({
+ type: 'thinking_delta',
+ payload: { content: clip(thinking, MAX_THINKING), thinkingId: `thinking-pi-${this.thinkingCounter++}` },
+ })
+ } else if (type === 'text') {
+ const text = str(part.text)
+ if (text) events.push({ type: 'text_delta', payload: { content: text } })
+ } else if (type === 'toolCall') {
+ const id = str(part.id)
+ if (!id) continue
+ const tool = piToolName(str(part.name))
+ this.toolNames.set(id, tool)
+ this.pendingTools.add(id)
+ events.push({ type: 'tool_start', payload: { id, tool, input: part.arguments ?? {} } })
+ }
+ }
+ if (this.mode !== 'replay' && this.open && isTerminalStop(str(message.stopReason)) && this.pendingTools.size === 0) {
+ this.open = false
+ events.push({ type: 'turn_ended', payload: {} })
+ }
+ return events
+ }
+
+ private toolResult(message: JsonObject): LiveEvent[] {
+ const id = str(message.toolCallId)
+ if (!id) return []
+ this.pendingTools.delete(id)
+ const tool = this.toolNames.get(id) || piToolName(str(message.toolName))
+ this.toolNames.delete(id)
+ const output = contentText(message.content)
+ const isError = message.isError === true
+ return [{
+ type: 'tool_end',
+ payload: { id, tool, output: clip(output, MAX_OUTPUT), isError, summary: toolSummary(tool, output, isError) },
+ }]
+ }
+
+ /** `!cmd` typed directly in the TUI — render it as a Bash card so the remote sees what ran. */
+ private bashExecution(raw: JsonObject, message: JsonObject): LiveEvent[] {
+ const command = str(message.command)
+ if (!command) return []
+ const id = `bash-${str(raw.id) || this.thinkingCounter++}`
+ const output = str(message.output)
+ const isError = typeof message.exitCode === 'number' && message.exitCode !== 0
+ return [
+ { type: 'tool_start', payload: { id, tool: 'Bash', input: { command } } },
+ {
+ type: 'tool_end',
+ payload: { id, tool: 'Bash', output: clip(output, MAX_OUTPUT), isError, summary: toolSummary('Bash', output, isError) },
+ },
+ ]
+ }
+}
+
+/** Full-session replay (session_get) — same render path as the live stream. */
+export function piMessagesToEvents(rawLines: string[]): SessionEvent[] {
+ const normalizer = new PiNormalizer('replay')
+ const events: SessionEvent[] = []
+ for (const line of rawLines) events.push(...normalizer.ingest(line) as SessionEvent[])
+ events.push(...normalizer.finishReplay() as SessionEvent[])
+ return events
+}
+
+/** Last user prompt + the assistant text that followed it — the recap source of truth. */
+export function lastPiTurnText(rawLines: string[]): LastTurnText | null {
+ let userMessage = ''
+ let assistantText = ''
+ for (const line of rawLines) {
+ const raw = parse(line)
+ if (!raw || str(raw.type) !== 'message') continue
+ const message = object(raw.message)
+ if (!message) continue
+ const role = str(message.role)
+ if (role === 'user') {
+ const text = contentText(message.content).trim()
+ if (text) { userMessage = text; assistantText = '' }
+ } else if (role === 'assistant') {
+ const text = contentParts(message.content)
+ .filter((part) => str(part.type) === 'text')
+ .map((part) => str(part.text))
+ .join('')
+ .trim()
+ if (text) assistantText += `${assistantText ? '\n\n' : ''}${text}`
+ }
+ }
+ return assistantText ? { userMessage, assistantText } : null
+}
+
+/** Session id + cwd from the header line, for registration/repair. */
+export function piSessionMeta(rawLines: string[]): { id: string; cwd: string } | null {
+ for (const line of rawLines) {
+ const raw = parse(line)
+ if (!raw || str(raw.type) !== 'session') continue
+ const id = str(raw.id)
+ if (id) return { id, cwd: str(raw.cwd) }
+ }
+ return null
+}
+
+/**
+ * Turn-snapped pagination window for `session_get {limit, before}`; cursor format `pi:<lineIndex>`.
+ * The start snaps back to a user message so a window never splits a turn (the replay is stateful:
+ * a tool_start's name must still be known when its tool_end is rendered).
+ */
+export function windowPiLines(
+ rawLines: string[],
+ opts: { limit: number; before?: string },
+): { window: string[]; hasMore: boolean; oldestCursor: string | null; staleCursor?: boolean } {
+ let endIndex = rawLines.length
+ if (opts.before) {
+ const match = /^pi:(\d+)$/.exec(opts.before)
+ if (!match) return { window: [], hasMore: false, oldestCursor: null, staleCursor: true }
+ endIndex = Number(match[1])
+ if (!Number.isSafeInteger(endIndex) || endIndex < 0 || endIndex > rawLines.length) {
+ return { window: [], hasMore: false, oldestCursor: null, staleCursor: true }
+ }
+ }
+
+ let start = Math.max(0, endIndex - opts.limit)
+ while (start > 0) {
+ const raw = parse(rawLines[start])
+ if (raw && str(raw.type) === 'message' && str(object(raw.message)?.role) === 'user') break
+ start--
+ }
+ return {
+ window: rawLines.slice(start, endIndex),
+ hasMore: start > 0,
+ oldestCursor: `pi:${start}`,
+ }
+}
diff --git a/cli/src/engines/pi/runtimeProfile.spec.ts b/cli/src/engines/pi/runtimeProfile.spec.ts
new file mode 100644
index 000000000..ea9ceaed9
--- /dev/null
+++ b/cli/src/engines/pi/runtimeProfile.spec.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from 'vitest'
+import {
+ parsePiFooterProfile,
+ parsePiModelsOutput,
+ parsePiThinkingSelection,
+ piThinkingSteps,
+} from './runtimeProfile.js'
+
+// The real `pi --list-models` table on this computer (pi 0.82), plus a second row with thinking off to
+// prove the column is read rather than assumed.
+const OUTPUT = [
+ 'provider model context max-out thinking images',
+ 'vibe minimax/minimax-m3 500K 65.5K yes no ',
+ 'openai gpt-5.6 400K 100K no yes ',
+].join('\n')
+
+describe('pi model catalog', () => {
+ it('reads provider, model and the thinking column', () => {
+ expect(parsePiModelsOutput(OUTPUT)).toEqual([
+ { id: 'vibe/minimax/minimax-m3', provider: 'vibe', model: 'minimax/minimax-m3', thinking: true },
+ { id: 'openai/gpt-5.6', provider: 'openai', model: 'gpt-5.6', thinking: false },
+ ])
+ })
+
+ it('skips the header and any short or noisy line', () => {
+ expect(parsePiModelsOutput('provider model context max-out thinking images')).toEqual([])
+ expect(parsePiModelsOutput(' Warning: tmux extended-keys is off.')).toEqual([])
+ expect(parsePiModelsOutput('')).toEqual([])
+ })
+})
+
+describe('pi footer + thinking ladder', () => {
+ it('reads model and thinking level from the idle footer', () => {
+ const capture = [
+ '/private/tmp/rp-probe/pi',
+ '0.0%/500k (auto) minimax/minimax-m3 • high',
+ ].join('\n')
+
+ expect(parsePiFooterProfile(capture)).toEqual({ model: 'minimax/minimax-m3', effort: 'high' })
+ })
+
+ it('refuses a footer whose level is not on the ladder', () => {
+ expect(parsePiFooterProfile('0.0%/500k (auto) minimax/minimax-m3 • nonsense')).toBeNull()
+ expect(parsePiFooterProfile('nothing here')).toBeNull()
+ })
+
+ it('counts arrow steps along the ladder, and refuses to guess off it', () => {
+ expect(piThinkingSteps('medium', 'high')).toBe(1)
+ expect(piThinkingSteps('medium', 'off')).toBe(-3)
+ expect(piThinkingSteps('max', 'max')).toBe(0)
+ expect(piThinkingSteps('auto', 'high')).toBeNull()
+ })
+
+ it('reads the level pi marks as current in the Thinking Level list', () => {
+ const capture = [
+ 'Thinking Level',
+ 'Select reasoning depth for thinking-capable models',
+ ' off No reasoning',
+ ' low Light reasoning (~2k tokens)',
+ '→ medium Moderate reasoning (~8k tokens)',
+ ' high Deep reasoning (~16k tokens)',
+ ].join('\n')
+
+ expect(parsePiThinkingSelection(capture)).toBe('medium')
+ expect(parsePiThinkingSelection('no selection marker here')).toBeNull()
+ })
+})
diff --git a/cli/src/engines/pi/runtimeProfile.ts b/cli/src/engines/pi/runtimeProfile.ts
new file mode 100644
index 000000000..91821fdb0
--- /dev/null
+++ b/cli/src/engines/pi/runtimeProfile.ts
@@ -0,0 +1,98 @@
+/**
+ * Pi model catalog + thinking level → runtime-profile options.
+ *
+ * `pi --list-models` prints a fixed-width table on stdout (columns separated by runs of spaces):
+ *
+ * provider model context max-out thinking images
+ * vibe minimax/minimax-m3 500K 65.5K yes no
+ *
+ * The `thinking` column is what makes pi's effort axis honest: only a model marked `yes` accepts a
+ * reasoning depth, so effort rows are attached per model rather than assumed (verified live, pi 0.82).
+ *
+ * Pi separates the two axes in its UI, and both were driven end to end during the probe:
+ * - **model** — `/model <provider/model>` takes the target directly (its own autocomplete documents
+ * `<provider/model> — Select model (opens selector UI)`).
+ * - **thinking** — `/settings` → filter `thinking` → the "Thinking Level" list, a fixed ladder navigated
+ * with the arrow keys. There is no slash command for it.
+ *
+ * The idle footer carries **both**: `minimax/minimax-m3 • high`. That single line is the observation
+ * source, and watching it flip `medium` → `high` is how the applied profile is confirmed.
+ */
+
+/** Pi's thinking ladder, in the order its settings list renders — the step count drives the arrow keys. */
+export const PI_THINKING_LEVELS = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const
+export const PI_EFFORTS = new Set<string>(['auto', ...PI_THINKING_LEVELS])
+
+export interface PiModelTarget {
+ /** `<provider>/<model>` as printed — also the argument for `/model`. */
+ id: string
+ provider: string
+ /** The model column verbatim; it can itself contain a slash (`minimax/minimax-m3`). */
+ model: string
+ /** True when the `thinking` column says `yes`; only then are effort rows offered. */
+ thinking: boolean
+}
+
+const HEADER_RE = /^\s*provider\s+model\s/i
+
+/**
+ * Parse `pi --list-models`. The header row and anything that does not have at least the provider, model
+ * and thinking columns are skipped, so a future column or a wrapped warning line cannot invent a model.
+ */
+export function parsePiModelsOutput(output: string): PiModelTarget[] {
+ const targets: PiModelTarget[] = []
+ const seen = new Set<string>()
+ for (const rawLine of output.split('\n')) {
+ if (!rawLine.trim() || HEADER_RE.test(rawLine)) continue
+ const cells = rawLine.trim().split(/\s{2,}/)
+ if (cells.length < 5) continue
+ const [provider, model] = cells
+ if (!/^[\w.-]+$/.test(provider) || !model) continue
+ // `thinking` is the second-to-last column (`images` closes the row).
+ const thinking = /^yes$/i.test(cells[cells.length - 2] ?? '')
+ const id = `${provider}/${model}`
+ if (seen.has(id)) continue
+ seen.add(id)
+ targets.push({ id, provider, model, thinking })
+ }
+ return targets
+}
+
+/**
+ * Model + thinking level out of pi's idle footer (`minimax/minimax-m3 • high`). Returns null rather than a
+ * half-read pair, so a redraw mid-capture can never be mistaken for a profile change.
+ */
+export function parsePiFooterProfile(capture: string): { model: string; effort: string } | null {
+ const lines = capture.split('\n')
+ for (let i = lines.length - 1; i >= 0; i--) {
+ // Two shapes in the wild: `minimax/minimax-m3 • high`, and `… • thinking off` once the level is off.
+ const match = /(\S+)\s+•\s+(?:thinking\s+)?([a-z]+)\s*$/i.exec(lines[i].replace(/\s+$/, ''))
+ if (!match) continue
+ const effort = match[2].toLowerCase()
+ if (!PI_EFFORTS.has(effort)) continue
+ return { model: match[1], effort }
+ }
+ return null
+}
+
+/**
+ * Steps to walk pi's "Thinking Level" list from one level to another: positive means Down. Null when
+ * either end is not on the ladder, which the caller must treat as "do not drive the list blind".
+ */
+export function piThinkingSteps(from: string, to: string): number | null {
+ const start = PI_THINKING_LEVELS.indexOf(from as typeof PI_THINKING_LEVELS[number])
+ const end = PI_THINKING_LEVELS.indexOf(to as typeof PI_THINKING_LEVELS[number])
+ if (start < 0 || end < 0) return null
+ return end - start
+}
+
+/** The level pi marks as current in its Thinking Level list (`→ medium Moderate reasoning`). */
+export function parsePiThinkingSelection(capture: string): string | null {
+ for (const line of capture.split('\n')) {
+ const match = /^\s*[→>]\s+([a-z]+)\b/i.exec(line)
+ if (!match) continue
+ const level = match[1].toLowerCase()
+ if (PI_EFFORTS.has(level) && level !== 'auto') return level
+ }
+ return null
+}
diff --git a/cli/src/engines/types.ts b/cli/src/engines/types.ts
new file mode 100644
index 000000000..8c68b61a3
--- /dev/null
+++ b/cli/src/engines/types.ts
@@ -0,0 +1,15 @@
+import type { LiveEvent } from '../lib/normalize.js'
+import type { RegisteredSession } from '../lib/registry.js'
+
+export type AgentEngine = 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin'
+
+export interface EngineNormalizer {
+ ingest(line: string): LiveEvent[]
+ finishReplay(): LiveEvent[]
+ readonly turnOpen: boolean
+}
+
+export interface EngineAdapter {
+ readonly engine: AgentEngine
+ createNormalizer(session: RegisteredSession, mode: 'live' | 'replay'): EngineNormalizer
+}
diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.ts
new file mode 100644
index 000000000..159145aee
--- /dev/null
+++ b/cli/src/hookNotify.spec.ts
@@ -0,0 +1,644 @@
+import { spawn } from 'child_process'
+import { createServer } from 'http'
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
+import { 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 tmpDirs: string[] = []
+
+afterEach(async () => {
+ await Promise.all(servers.splice(0).map((server) => new Promise<void>((resolve) => server.close(() => resolve()))))
+ for (const dir of tmpDirs.splice(0)) rmSync(dir, { recursive: true, force: true })
+})
+
+interface RunHookOpts {
+ port: number
+ tmuxPane?: string
+ /** The launcher id `harness <engine>` exports. Defaults to a live-looking one; pass null to simulate a
+ * CLI the user started by hand (no machine → the hook must ignore the event entirely). */
+ launcherId?: string | null
+ engine?: 'claude' | 'codex' | 'cursor' | 'devin' | 'commandcode'
+ env?: Record<string, string>
+ dataDir?: string
+ claudeProjectsDir?: string
+ codexHome?: string
+ cursorHome?: string
+ devinHome?: string
+ input?: Record<string, unknown>
+}
+
+function runHook(opts: RunHookOpts): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const env = { ...process.env }
+ if (opts.env) Object.assign(env, opts.env)
+ delete env.TMUX_PANE
+ if (opts.tmuxPane) env.TMUX_PANE = opts.tmuxPane
+ delete env.MACHINE_ID
+ if (opts.launcherId !== null) env.MACHINE_ID = opts.launcherId ?? '11111111-2222-4333-8444-555555555555'
+ const args = [HOOK, '--port', String(opts.port)]
+ if (opts.engine && opts.engine !== 'claude') args.push('--engine', opts.engine)
+ if (opts.dataDir) args.push('--data-dir', opts.dataDir)
+ if (opts.claudeProjectsDir) args.push('--claude-projects-dir', opts.claudeProjectsDir)
+ if (opts.codexHome) args.push('--codex-home', opts.codexHome)
+ if (opts.cursorHome) args.push('--cursor-home', opts.cursorHome)
+ if (opts.devinHome) args.push('--devin-home', opts.devinHome)
+ const child = spawn(process.execPath, args, {
+ env,
+ stdio: ['pipe', 'pipe', 'inherit'],
+ })
+ let stdout = ''
+ child.stdout.setEncoding('utf8')
+ child.stdout.on('data', (chunk) => { stdout += chunk })
+ child.on('error', reject)
+ child.on('close', (code) => code === 0 ? resolve(stdout) : reject(new Error(`notify.mjs exited ${code}`)))
+ child.stdin.end(JSON.stringify(opts.input ?? {
+ hook_event_name: 'SessionEnd',
+ session_id: 'session-test',
+ reason: 'logout',
+ }))
+ })
+}
+
+/** A throwaway localhost adapter that records every hook POST. */
+async function collect(): Promise<{ port: number; requests: Array<{ url: string; body: Record<string, unknown> }> }> {
+ const requests: Array<{ url: string; body: Record<string, unknown> }> = []
+ const server = createServer((req, res) => {
+ let raw = ''
+ req.on('data', (chunk) => { raw += chunk.toString() })
+ req.on('end', () => {
+ requests.push({ url: req.url ?? '', body: JSON.parse(raw) as Record<string, unknown> })
+ res.end('{}')
+ })
+ })
+ servers.push(server)
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', () => resolve()))
+ const address = server.address()
+ if (!address || typeof address === 'string') throw new Error('test server did not bind a TCP port')
+ return { port: address.port, requests }
+}
+
+describe('hook notify tmux scope', () => {
+ 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)
+ const dataDir = join(dir, 'data')
+ const cursorHome = join(dir, 'cursor')
+ const requests: Array<{ url: string; body: Record<string, unknown> }> = []
+ const server = createServer((req, res) => {
+ let raw = ''
+ req.on('data', (chunk) => { raw += chunk.toString() })
+ req.on('end', () => {
+ requests.push({ url: req.url ?? '', body: JSON.parse(raw) as Record<string, unknown> })
+ res.end('{}')
+ })
+ })
+ servers.push(server)
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', () => resolve()))
+ const address = server.address()
+ if (!address || typeof address === 'string') throw new Error('test server did not bind a TCP port')
+
+ const stdout = await runHook({
+ port: address.port,
+ tmuxPane: '%21',
+ engine: 'cursor',
+ dataDir,
+ cursorHome,
+ input: {
+ hook_event_name: 'preToolUse',
+ session_id: 'cursor-session',
+ tool_name: 'Task',
+ tool_use_id: 'call-1',
+ tool_input: { description: 'Inspect', prompt: 'Read code', model: 'inherit' },
+ user_email: '[email protected]',
+ },
+ })
+ expect(stdout).toBe('{}\n')
+ expect(requests).toEqual([{
+ url: '/api/hook/tool-start',
+ body: {
+ sessionId: 'cursor-session',
+ toolUseId: 'call-1',
+ toolName: 'Task',
+ input: { description: 'Inspect', prompt: 'Read code', model: 'inherit' },
+ },
+ }])
+ expect(JSON.parse(readFileSync(join(dataDir, 'cursor-pending-tasks.json'), 'utf8'))).toMatchObject([{
+ sessionId: 'cursor-session',
+ toolUseId: 'call-1',
+ }])
+
+ requests.splice(0)
+ await runHook({
+ port: address.port,
+ tmuxPane: '%21',
+ engine: 'cursor',
+ dataDir,
+ cursorHome,
+ input: {
+ hook_event_name: 'stop',
+ session_id: 'cursor-session',
+ workspace_roots: ['/tmp/cursor-workspace'],
+ cursor_version: '2026.07.20-8cc9c0b',
+ },
+ })
+ expect(requests.map((request) => request.url)).toEqual([
+ '/api/hook/session-start',
+ '/api/hook/turn-stop',
+ ])
+ expect(() => readFileSync(join(dataDir, 'cursor-pending-tasks.json'), 'utf8')).toThrow()
+ })
+
+ it('ignores Cursor background agents without leaking them into the registry', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-cursor-background-'))
+ tmpDirs.push(dir)
+ const dataDir = join(dir, 'data')
+ const output = await runHook({
+ port: 9,
+ tmuxPane: '%22',
+ engine: 'cursor',
+ dataDir,
+ cursorHome: join(dir, 'cursor'),
+ input: {
+ hook_event_name: 'sessionStart',
+ session_id: 'background',
+ is_background_agent: true,
+ },
+ })
+ expect(output).toBe('{}\n')
+ expect(() => readFileSync(join(dataDir, 'registry.json'), 'utf8')).toThrow()
+ })
+
+ it('ignores Codex subagent rollouts instead of replacing the parent transcript', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-codex-subagent-'))
+ tmpDirs.push(dir)
+ const dataDir = join(dir, 'data')
+ const codexHome = join(dir, 'codex')
+ const childId = '019f8dae-e5f4-7c11-90d1-600854063b2c'
+ const parentId = '019f7f1b-195d-70f2-861b-de5d54a3e141'
+ const transcriptPath = join(codexHome, 'sessions', '2026', '07', `rollout-${childId}.jsonl`)
+ mkdirSync(join(transcriptPath, '..'), { recursive: true })
+ writeFileSync(transcriptPath, JSON.stringify({
+ type: 'session_meta',
+ payload: {
+ id: childId,
+ source: { subagent: { thread_spawn: { parent_thread_id: parentId, depth: 1 } } },
+ },
+ }) + '\n')
+ const requests: string[] = []
+ const server = createServer((req, res) => {
+ requests.push(req.url ?? '')
+ req.resume()
+ res.end('{}')
+ })
+ servers.push(server)
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', () => resolve()))
+ const address = server.address()
+ if (!address || typeof address === 'string') throw new Error('test server did not bind a TCP port')
+
+ await runHook({
+ port: address.port,
+ tmuxPane: '%8',
+ engine: 'codex',
+ dataDir,
+ codexHome,
+ input: {
+ hook_event_name: 'SessionStart',
+ session_id: parentId,
+ transcript_path: transcriptPath,
+ cwd: '/tmp/codex',
+ },
+ })
+
+ expect(requests).toEqual([])
+ expect(() => readFileSync(join(dataDir, 'registry.json'), 'utf8')).toThrow()
+ })
+
+ it('ignores every event when the CLI was not started by `harness <engine>` (no MACHINE_ID)', async () => {
+ const requests: Array<{ url: string; body: Record<string, unknown> }> = []
+ const server = createServer((req, res) => {
+ let raw = ''
+ req.on('data', (chunk) => { raw += chunk.toString() })
+ req.on('end', () => {
+ requests.push({ url: req.url ?? '', body: JSON.parse(raw) as Record<string, unknown> })
+ res.end('{}')
+ })
+ })
+ servers.push(server)
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', () => resolve()))
+ const address = server.address()
+ if (!address || typeof address === 'string') throw new Error('test server did not bind a TCP port')
+
+ // In tmux, but launched by hand: the session has no owning machine, so it is not an agent.
+ await runHook({ port: address.port, tmuxPane: '%42', launcherId: null })
+ expect(requests).toEqual([])
+
+ // Same event, launched through the machine → forwarded, carrying the launcher id.
+ await runHook({ port: address.port, tmuxPane: '%42' })
+ expect(requests).toHaveLength(1)
+ expect(requests[0].url).toBe('/api/hook/session-end')
+ })
+
+ it('drops standalone SessionEnd but forwards tmux SessionEnd', async () => {
+ const requests: Array<{ url: string; body: Record<string, unknown> }> = []
+ const server = createServer((req, res) => {
+ let raw = ''
+ req.on('data', (chunk) => { raw += chunk.toString() })
+ req.on('end', () => {
+ requests.push({ url: req.url ?? '', body: JSON.parse(raw) as Record<string, unknown> })
+ res.end('{}')
+ })
+ })
+ servers.push(server)
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', () => resolve()))
+ const address = server.address()
+ if (!address || typeof address === 'string') throw new Error('test server did not bind a TCP port')
+
+ await runHook({ port: address.port })
+ expect(requests).toEqual([])
+
+ await runHook({ port: address.port, tmuxPane: '%42' })
+ expect(requests).toEqual([{
+ url: '/api/hook/session-end',
+ body: { sessionId: 'session-test', reason: 'logout' },
+ }])
+ })
+
+ it('falls back to registry.json when SessionStart cannot reach the adapter', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-offline-'))
+ tmpDirs.push(dir)
+ const claudeProjectsDir = join(dir, 'claude-projects')
+ const dataDir = join(dir, 'data')
+ const transcriptPath = join(claudeProjectsDir, 'demo', 'session-1.jsonl')
+ mkdirSync(join(claudeProjectsDir, 'demo'), { recursive: true })
+ writeFileSync(transcriptPath, '{}\n')
+
+ await runHook({
+ port: 9,
+ tmuxPane: '%7',
+ dataDir,
+ claudeProjectsDir,
+ input: {
+ hook_event_name: 'SessionStart',
+ session_id: 'session-1',
+ transcript_path: transcriptPath,
+ cwd: '/tmp/demo',
+ session_title: 'Demo',
+ model: 'sonnet',
+ cli_version: '1.0.0',
+ },
+ })
+
+ const registry = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))
+ expect(registry).toMatchObject([{
+ sessionId: 'session-1',
+ engine: 'claude',
+ transcriptPath,
+ projectDir: 'demo',
+ cwd: '/tmp/demo',
+ tmuxPane: '%7',
+ title: 'Demo',
+ model: 'sonnet',
+ cliVersion: '1.0.0',
+ }])
+ })
+
+ it('falls back with Codex engine under CODEX_HOME/sessions', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-codex-'))
+ tmpDirs.push(dir)
+ const codexHome = join(dir, 'codex')
+ const dataDir = join(dir, 'data')
+ const transcriptPath = join(codexHome, 'sessions', '2026', 'rollout.jsonl')
+ mkdirSync(join(codexHome, 'sessions', '2026'), { recursive: true })
+ writeFileSync(transcriptPath, '{}\n')
+
+ await runHook({
+ port: 9,
+ tmuxPane: '%8',
+ engine: 'codex',
+ dataDir,
+ codexHome,
+ input: {
+ hook_event_name: 'SessionStart',
+ session_id: 'codex-session',
+ transcript_path: transcriptPath,
+ cwd: '/tmp/codex',
+ },
+ })
+
+ const registry = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))
+ expect(registry).toMatchObject([{ sessionId: 'codex-session', engine: 'codex', tmuxPane: '%8' }])
+ })
+
+ it('does not fallback when the adapter accepts the hook event', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-online-'))
+ tmpDirs.push(dir)
+ const claudeProjectsDir = join(dir, 'claude-projects')
+ const dataDir = join(dir, 'data')
+ const transcriptPath = join(claudeProjectsDir, 'demo', 'session-online.jsonl')
+ mkdirSync(join(claudeProjectsDir, 'demo'), { recursive: true })
+ writeFileSync(transcriptPath, '{}\n')
+
+ const server = createServer((_req, res) => res.end('{}'))
+ servers.push(server)
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', () => resolve()))
+ const address = server.address()
+ if (!address || typeof address === 'string') throw new Error('test server did not bind a TCP port')
+
+ await runHook({
+ port: address.port,
+ tmuxPane: '%9',
+ dataDir,
+ claudeProjectsDir,
+ input: {
+ hook_event_name: 'SessionStart',
+ session_id: 'session-online',
+ transcript_path: transcriptPath,
+ },
+ })
+
+ expect(() => readFileSync(join(dataDir, 'registry.json'), 'utf-8')).toThrow()
+ })
+
+ it('does not write fallback registry entries outside tmux or outside the transcript root', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-invalid-'))
+ tmpDirs.push(dir)
+ const claudeProjectsDir = join(dir, 'claude-projects')
+ const dataDir = join(dir, 'data')
+ const outside = join(dir, 'outside.jsonl')
+ mkdirSync(claudeProjectsDir, { recursive: true })
+ writeFileSync(outside, '{}\n')
+
+ await runHook({
+ port: 9,
+ dataDir,
+ claudeProjectsDir,
+ input: {
+ hook_event_name: 'SessionStart',
+ session_id: 'no-tmux',
+ transcript_path: outside,
+ },
+ })
+ await runHook({
+ port: 9,
+ tmuxPane: '%10',
+ dataDir,
+ claudeProjectsDir,
+ input: {
+ hook_event_name: 'SessionStart',
+ session_id: 'outside',
+ transcript_path: outside,
+ },
+ })
+
+ expect(() => readFileSync(join(dataDir, 'registry.json'), 'utf-8')).toThrow()
+ })
+
+ it('removes fallback registry entries on offline SessionEnd except clear', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-end-'))
+ tmpDirs.push(dir)
+ const dataDir = join(dir, 'data')
+ mkdirSync(dataDir, { recursive: true })
+ writeFileSync(join(dataDir, 'registry.json'), JSON.stringify([{ sessionId: 'keep' }, { sessionId: 'ended' }]))
+
+ await runHook({
+ port: 9,
+ tmuxPane: '%11',
+ dataDir,
+ input: { hook_event_name: 'SessionEnd', session_id: 'ended', reason: 'logout' },
+ })
+ expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))).toEqual([{ sessionId: 'keep' }])
+
+ await runHook({
+ port: 9,
+ tmuxPane: '%11',
+ dataDir,
+ input: { hook_event_name: 'SessionEnd', session_id: 'keep', reason: 'clear' },
+ })
+ expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))).toEqual([{ sessionId: 'keep' }])
+ })
+
+ it('keeps fallback registry entries when SessionEnd cannot prove the tmux app exited', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-end-unknown-'))
+ tmpDirs.push(dir)
+ const dataDir = join(dir, 'data')
+ const binDir = join(dir, 'bin')
+ mkdirSync(dataDir, { recursive: true })
+ mkdirSync(binDir, { recursive: true })
+ writeFileSync(join(dataDir, 'registry.json'), JSON.stringify([{ sessionId: 'maybe-alive' }]))
+ writeFileSync(join(binDir, 'tmux'), '#!/bin/sh\nexit 1\n', { mode: 0o755 })
+
+ await runHook({
+ port: 9,
+ tmuxPane: '%13',
+ dataDir,
+ env: { PATH: `${binDir}:${process.env.PATH ?? ''}` },
+ input: { hook_event_name: 'SessionEnd', session_id: 'maybe-alive', reason: 'logout' },
+ })
+
+ expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))).toEqual([{ sessionId: 'maybe-alive' }])
+ })
+
+ it('drops stale registry entries when boot marker predates this boot', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-reboot-'))
+ tmpDirs.push(dir)
+ const claudeProjectsDir = join(dir, 'claude-projects')
+ const dataDir = join(dir, 'data')
+ const transcriptPath = join(claudeProjectsDir, 'demo', 'fresh.jsonl')
+ mkdirSync(join(claudeProjectsDir, 'demo'), { recursive: true })
+ mkdirSync(dataDir, { recursive: true })
+ writeFileSync(transcriptPath, '{}\n')
+ writeFileSync(join(dataDir, 'registry-boot'), '1')
+ writeFileSync(join(dataDir, 'registry.json'), JSON.stringify([{ sessionId: 'stale', tmuxPane: '%1' }]))
+
+ await runHook({
+ port: 9,
+ tmuxPane: '%12',
+ dataDir,
+ claudeProjectsDir,
+ input: {
+ hook_event_name: 'SessionStart',
+ session_id: 'fresh',
+ transcript_path: transcriptPath,
+ },
+ })
+
+ expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))).toMatchObject([
+ { sessionId: 'fresh', tmuxPane: '%12' },
+ ])
+ })
+})
+
+/**
+ * Devin's documented user-level hook locations include `~/.claude/settings.json`, so the machine's CLAUDE
+ * hook can fire inside a Devin session and register it under the wrong engine. The claude arm bails out
+ * on a payload whose session id is a Devin slug holding a live `session_locks/<id>.lock`.
+ */
+describe('hook notify Devin/claude disambiguation', () => {
+
+ it('ignores a Devin session that fired the claude hook, but still registers a real claude session', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-devin-'))
+ tmpDirs.push(dir)
+ const devinHome = join(dir, 'devin')
+ const projectsDir = join(dir, 'projects')
+ mkdirSync(join(devinHome, 'session_locks'), { recursive: true })
+ writeFileSync(join(devinHome, 'session_locks', 'classy-tourmaline.lock'), '21988')
+ mkdirSync(projectsDir, { recursive: true })
+ const transcript = join(projectsDir, 'a3f1c2d4-0000-4000-8000-000000000001.jsonl')
+ writeFileSync(transcript, '')
+
+ const { port, requests } = await collect()
+
+ // Devin's SessionStart, arriving on the claude-armed hook → dropped.
+ await runHook({
+ port,
+ tmuxPane: '%30',
+ dataDir: join(dir, 'data'),
+ claudeProjectsDir: projectsDir,
+ devinHome,
+ input: { hook_event_name: 'SessionStart', session_id: 'classy-tourmaline', source: 'startup' },
+ })
+ expect(requests).toEqual([])
+
+ // A genuine claude session is unaffected.
+ await runHook({
+ port,
+ tmuxPane: '%30',
+ dataDir: join(dir, 'data'),
+ claudeProjectsDir: projectsDir,
+ devinHome,
+ input: {
+ hook_event_name: 'SessionStart',
+ session_id: 'a3f1c2d4-0000-4000-8000-000000000001',
+ transcript_path: transcript,
+ cwd: '/tmp/claude-workspace',
+ source: 'startup',
+ },
+ })
+ expect(requests).toHaveLength(1)
+ expect(requests[0].url).toBe('/api/hook/session-start')
+ expect(requests[0].body).toMatchObject({ engine: 'claude', sessionId: 'a3f1c2d4-0000-4000-8000-000000000001' })
+ })
+
+ it('registers a Devin session with no transcript path and the hook process cwd', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-devin2-'))
+ tmpDirs.push(dir)
+ const { port, requests } = await collect()
+
+ await runHook({
+ port,
+ tmuxPane: '%31',
+ engine: 'devin',
+ dataDir: join(dir, 'data'),
+ devinHome: join(dir, 'devin'),
+ input: { hook_event_name: 'SessionStart', session_id: 'blue-agustinia', source: 'startup' },
+ })
+
+ expect(requests).toHaveLength(1)
+ expect(requests[0].url).toBe('/api/hook/session-start')
+ expect(requests[0].body).toMatchObject({
+ engine: 'devin',
+ sessionId: 'blue-agustinia',
+ tmuxPane: '%31',
+ cwd: process.cwd(),
+ })
+ expect(requests[0].body.transcriptPath).toBeUndefined()
+ })
+
+ it('routes a Devin Stop to turn-stop', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-devin3-'))
+ tmpDirs.push(dir)
+ const { port, requests } = await collect()
+
+ await runHook({
+ port,
+ tmuxPane: '%32',
+ engine: 'devin',
+ dataDir: join(dir, 'data'),
+ devinHome: join(dir, 'devin'),
+ input: { hook_event_name: 'Stop', session_id: 'blue-agustinia', stop_hook_active: false, prompt_id: 'p1' },
+ })
+
+ expect(requests).toHaveLength(1)
+ expect(requests[0].url).toBe('/api/hook/turn-stop')
+ expect(requests[0].body).toMatchObject({ sessionId: 'blue-agustinia' })
+ })
+})
+
+describe('hook notify Command Code re-registration', () => {
+ // Command Code's hook set is PreToolUse/PostToolUse/Stop/SessionStart — Stop doubles as its only catch
+ // hook, so it must register as well as close the turn. Without that, a session dropped from the registry
+ // stays invisible on web/device until the user quits and relaunches the CLI.
+ it('re-registers on Stop, with the transcript path, before closing the turn', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-cc-'))
+ tmpDirs.push(dir)
+ const transcript = join(dir, '53955d6d.jsonl')
+ writeFileSync(transcript, '{}\n')
+ const { port, requests } = await collect()
+
+ await runHook({
+ port,
+ tmuxPane: '%3',
+ engine: 'commandcode',
+ dataDir: join(dir, 'data'),
+ input: {
+ hook_event_name: 'Stop',
+ session_id: '53955d6d',
+ transcript_path: transcript,
+ cwd: '/tmp/demo',
+ session_title: 'Greeting',
+ },
+ })
+
+ expect(requests.map((r) => r.url)).toEqual(['/api/hook/session-start', '/api/hook/turn-stop'])
+ expect(requests[0].body).toMatchObject({
+ engine: 'commandcode',
+ hookEvent: 'Stop',
+ sessionId: '53955d6d',
+ transcriptPath: transcript,
+ tmuxPane: '%3',
+ cwd: '/tmp/demo',
+ title: 'Greeting',
+ })
+ expect(requests[1].body).toMatchObject({ sessionId: '53955d6d' })
+ })
+
+ it('omits a transcript path that does not exist yet', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-cc2-'))
+ tmpDirs.push(dir)
+ const { port, requests } = await collect()
+
+ await runHook({
+ port,
+ tmuxPane: '%3',
+ engine: 'commandcode',
+ dataDir: join(dir, 'data'),
+ input: { hook_event_name: 'Stop', session_id: '53955d6d', transcript_path: join(dir, 'nope.jsonl') },
+ })
+
+ expect(requests).toHaveLength(2)
+ expect(requests[0].body.transcriptPath).toBeUndefined()
+ })
+
+ it('leaves the claude Stop path as a turn-stop only', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-cc3-'))
+ tmpDirs.push(dir)
+ const transcript = join(dir, 'projects', 'demo', 'abc.jsonl')
+ mkdirSync(join(dir, 'projects', 'demo'), { recursive: true })
+ writeFileSync(transcript, '{}\n')
+ const { port, requests } = await collect()
+
+ await runHook({
+ port,
+ tmuxPane: '%4',
+ dataDir: join(dir, 'data'),
+ claudeProjectsDir: join(dir, 'projects'),
+ input: { hook_event_name: 'Stop', session_id: 'abc', transcript_path: transcript },
+ })
+
+ expect(requests.map((r) => r.url)).toEqual(['/api/hook/turn-stop'])
+ })
+})
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
new file mode 100644
index 000000000..102b51304
--- /dev/null
+++ b/cli/src/hookServer.ts
@@ -0,0 +1,466 @@
+/**
+ * Tiny localhost HTTP server for the Claude Code hook callbacks. `hook/notify.mjs` POSTs here on
+ * SessionStart/SessionEnd (127.0.0.1:<PORT>). This replaces the old Fastify routes — the browser
+ * UI is gone; only these two endpoints remain local.
+ */
+
+import { existsSync } from 'node:fs'
+import { join } from 'node:path'
+import http from 'node:http'
+import type { AddressInfo } from 'node:net'
+import { WebSocketServer, type WebSocket } from 'ws'
+import { readCodexRolloutMeta } from './engines/codex/rollout.js'
+import { hermesSessionSource } from './engines/hermes/reader.js'
+import { launcherSessions, MACHINE_WS_PATH, type LauncherOpenInput } from './lib/launcherSessions.js'
+import { isRecentlyDeleted } from './lib/deletedSessions.js'
+import { registry, type RegisterInput, type RegisteredSession } from './lib/registry.js'
+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 { engineBin } from './lib/engineBin.js'
+import { installHooksFor } from './lib/hooks.js'
+import {
+ SUPPORTED_PROTOCOLS, frameProtocol, isSupportedProtocol,
+ type LauncherOpenFrame,
+} from './lib/launcherProtocol.js'
+
+export interface PairOutcome {
+ status: number
+ body: Record<string, unknown>
+}
+
+export interface HookServerHandlers {
+ onRegistered: (entry: RegisteredSession, meta: { isNew: boolean; evicted: string | null; rebound: string | null; hookEvent?: string }) => void
+ /** SessionEnd — the caller decides whether to forget (a `/clear` rotation keeps the pane's tile). */
+ onSessionEnd: (sessionId: string, reason: string | undefined) => void
+ /** A `harness <engine>` wrapper exited — drop every session bound to that machine id. */
+ onLauncherClosed?: (launcherId: string) => void
+ /**
+ * A `harness <engine>` wrapper started. The frame cannot say WHICH session is in that pane — only the
+ * engine's own hook knows that, and resuming an existing session fires no hook — so the caller uses
+ * this to go look (see adoptResumedSessions). Without it, a resumed agent stays invisible.
+ */
+ onLauncherOpened?: (session: { launcherId: string; engine: RegisteredSession['engine']; tmuxPane: string; cwd?: string | null }) => void
+ /** 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. */
+ onTurnStart?: (body: { sessionId: string }) => void
+ onToolStart?: (body: {
+ sessionId: string
+ toolUseId: string
+ toolName: string
+ input: unknown
+ }) => void
+ onTurnStop?: (body: {
+ sessionId: string
+ status?: string
+ transcriptPath?: string
+ }) => void
+ /** `harness pair <code>` from a second CLI process: run CPace toward the waiting browser. */
+ onPair?: (code: string) => Promise<PairOutcome>
+ /** `adapter browser-link` — mint a setup-link token from the running daemon. */
+ onSetupLink?: () => PairOutcome
+ /** `harness pairings` — list E2EE-paired browsers. */
+ onListPairs?: () => PairOutcome
+ /** `harness unpair <id>` — unpair one browser (by fingerprint/prefix/index). */
+ onRevoke?: (id: string) => PairOutcome
+ /** `harness unpair --all` — unpair every browser. */
+ onRevokeAll?: () => PairOutcome
+ /** Local dashboard status snapshot (GET /api/status). */
+ onStatus?: () => Record<string, unknown>
+ /** Recent adapter log tail (GET /api/logs). */
+ onLogs?: () => string
+ /** Stop the adapter from the local dashboard (POST /api/stop). */
+ onStop?: () => void
+}
+
+function readBody(req: http.IncomingMessage): Promise<string> {
+ return new Promise((resolve) => {
+ let data = ''
+ req.setEncoding('utf8')
+ req.on('data', (c) => (data += c))
+ req.on('end', () => resolve(data))
+ req.on('error', () => resolve(data))
+ })
+}
+
+/**
+ * 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
+ * CLI reports it as "another adapter already running"). Resolves with the bound port.
+ */
+/** How long to keep waiting for an engine to write the transcript it just announced. */
+const TRANSCRIPT_WAIT_MS = 500
+const HERMES_KIND_TRIES = 6
+const HERMES_KIND_WAIT_MS = 120
+const TRANSCRIPT_WAIT_TRIES = 20
+
+/**
+ * Register once the announced transcript exists.
+ *
+ * Runs detached from the HTTP reply on purpose: this is a SessionStart hook, and the engine is blocked
+ * until the response comes back. Bounded — an announcement whose file never appears is dropped, which is
+ * the same outcome as before, just after giving the engine a fair chance to finish starting up.
+ */
+async function awaitTranscript(body: RegisterInput, handlers: HookServerHandlers): Promise<void> {
+ for (let i = 0; i < TRANSCRIPT_WAIT_TRIES; i++) {
+ await new Promise((resolve) => { const t = setTimeout(resolve, TRANSCRIPT_WAIT_MS); t.unref?.() })
+ if (!launcherSessions.has(body.launcherId)) return // the launcher left while we waited
+ if (isRecentlyDeleted(body.sessionId)) return
+ if (!body.transcriptPath || !existsSync(body.transcriptPath)) continue
+ const result = registry.register(body)
+ if (!result) return
+ console.log(`[hooks] ${sid(result.entry.sessionId)} ${body.hookEvent ?? 'session-start'} · engine=${result.entry.engine}`
+ + ` · isNew=${result.isNew} · after waiting ${((i + 1) * TRANSCRIPT_WAIT_MS) / 1000}s for its transcript`)
+ handlers.onRegistered(result.entry, { isNew: result.isNew, evicted: result.evicted, rebound: result.rebound, hookEvent: body.hookEvent })
+ return
+ }
+ console.warn(`[hooks] ${sid(body.sessionId ?? '?')} announced a transcript that never appeared: ${body.transcriptPath}`)
+}
+
+/**
+ * Re-check a hermes session whose `sessions` row had not landed yet, then register it only if it turns
+ * out to be the user's own CLI session. Bounded: if the row never appears we register anyway, which is
+ * exactly the behaviour before this guard existed.
+ */
+async function awaitHermesKind(body: RegisterInput, handlers: HookServerHandlers): Promise<void> {
+ 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 (!launcherSessions.has(body.launcherId)) return
+ if (isRecentlyDeleted(body.sessionId)) return
+ const source = await hermesSessionSource(dbPath, body.sessionId ?? '')
+ if (source === null) continue
+ if (source !== '' && source !== 'cli') {
+ console.log(`[hooks] ${sid(body.sessionId ?? '?')} ${body.hookEvent ?? 'session-start'} ignored · hermes_subagent`)
+ return
+ }
+ break
+ }
+ const result = registry.register(body)
+ if (!result) return
+ console.log(`[hooks] ${sid(result.entry.sessionId)} ${body.hookEvent ?? 'session-start'} · engine=hermes · isNew=${result.isNew} · after a source check`)
+ handlers.onRegistered(result.entry, { isNew: result.isNew, evicted: result.evicted, rebound: result.rebound, hookEvent: body.hookEvent })
+}
+
+export function startHookServer(
+ port: number,
+ handlers: HookServerHandlers,
+): Promise<{ server: http.Server; port: number }> {
+ const server = http.createServer((req, res) => {
+ void (async () => {
+ const url = (req.url ?? '').split('?')[0]
+ const json = (code: number, body: unknown): void => {
+ res.writeHead(code, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify(body))
+ }
+ // CSRF guard for mutating endpoints: a cross-origin browser page cannot set a custom header on a
+ // simple request (it forces a CORS preflight we never allow), so only our same-origin dashboard
+ // (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'
+
+ // `protocols` is what a launcher gates on — two different BUILDS interoperate fine as long as they
+ // share a protocol version, so `version` here is informational only (the stale-build notice).
+ if (req.method === 'GET' && url === '/api/health') {
+ json(200, { ok: true, version: VERSION, protocols: SUPPORTED_PROTOCOLS }); return
+ }
+
+ // Local dashboard (self-contained page) + its read-only status/logs.
+ if (req.method === 'GET' && (url === '/' || url === '/index.html')) {
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); res.end(LOCAL_WEB_HTML); return
+ }
+ if (req.method === 'GET' && url === '/api/status') {
+ json(200, handlers.onStatus ? handlers.onStatus() : { supported: false }); return
+ }
+ if (req.method === 'GET' && url === '/api/logs') {
+ res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); res.end(handlers.onLogs ? handlers.onLogs() : ''); return
+ }
+ if (req.method === 'POST' && url === '/api/stop') {
+ if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }
+ json(200, { ok: true }); handlers.onStop?.(); return
+ }
+
+ // 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') {
+ let body: RegisterInput
+ try { body = JSON.parse(await readBody(req)) as RegisterInput } 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".
+ const ignore = (reason: string): void => {
+ 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 }
+ // Machine-launched only: a session with no LIVE machine id is not an agent. This is what makes
+ // lifetime deterministic — a CLI the user started outside `harness <engine>` is ignored here,
+ // exactly like a non-tmux one above.
+ if (!launcherSessions.has(body.launcherId)) { ignore('no_machine_id'); return }
+ // Deleting an agent no longer kills its pane, so the engine lives on for a moment and its catch
+ // hook still fires — and this endpoint only checks that the LAUNCHER is alive, which it is. Without
+ // this the tile the user just deleted re-registers itself and comes back.
+ if (isRecentlyDeleted(body.sessionId)) { ignore('deleted'); return }
+ if (body.engine === 'codex' && body.transcriptPath && readCodexRolloutMeta(body.transcriptPath)?.isSubagent) {
+ ignore('codex_subagent')
+ return
+ }
+ // Same story for hermes, which reaches here through its own hooks rather than a transcript file:
+ // every delegated sub-agent is a hermes session that runs those hooks from the parent's pane.
+ if (body.engine === 'hermes' && body.sessionId) {
+ // Settled off the HTTP path entirely: the answer needs a SQLite read, and the row may not even
+ // be written yet (measured: a child's hook beat its own INSERT by 110ms). Registering
+ // optimistically would hand the parent's pane to a sub-agent.
+ json(200, { pending: true })
+ void awaitHermesKind(body, handlers)
+ return
+ }
+ let result = registry.register(body)
+ if (!result && body.transcriptPath && !existsSync(body.transcriptPath)) {
+ // The engine announced the session BEFORE writing its transcript. Measured on claude: the hook
+ // arrived at 13:03:31 and the file appeared at 13:03:34, so registration was refused (a session
+ // is only accepted with a real file behind it) and the agent stayed off the list until something
+ // else noticed it. Wait for the file instead of dropping the announcement — in the background,
+ // because a SessionStart hook blocks the CLI that is waiting on this reply.
+ json(200, { pending: true })
+ void awaitTranscript(body, handlers)
+ return
+ }
+ if (!result) {
+ console.warn(`[hooks] ${sid(body.sessionId ?? '?')} REJECTED · engine=${body.engine} pane=${body.tmuxPane} machine=${sid(body.launcherId ?? '?')}`)
+ json(400, { error: 'invalid session registration' })
+ return
+ }
+ console.log(`[hooks] ${sid(result.entry.sessionId)} ${body.hookEvent ?? 'session-start'} · engine=${result.entry.engine} · isNew=${result.isNew}`)
+ handlers.onRegistered(result.entry, { isNew: result.isNew, evicted: result.evicted, rebound: result.rebound, hookEvent: body.hookEvent })
+ json(200, { ok: true })
+ return
+ }
+
+ 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 (body.sessionId) {
+ console.log(`[hooks] ${sid(body.sessionId)} session-end${body.reason ? ` · reason=${body.reason}` : ''}`)
+ handlers.onSessionEnd(body.sessionId, body.reason)
+ }
+ json(200, { ok: true })
+ return
+ }
+
+ 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 (body.sessionId && body.toolUseId && body.toolName) {
+ console.log(`[hooks] ${sid(body.sessionId)} tool-start · tool=${body.toolName}`)
+ handlers.onToolStart?.({
+ sessionId: body.sessionId,
+ toolUseId: body.toolUseId,
+ toolName: body.toolName,
+ input: body.input,
+ })
+ }
+ json(200, { ok: true })
+ return
+ }
+
+ 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 (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 (body.sessionId) {
+ console.log(`[hooks] ${sid(body.sessionId)} turn-stop${body.status ? ` · status=${body.status}` : ''}`)
+ handlers.onTurnStop?.({
+ sessionId: body.sessionId,
+ status: body.status,
+ transcriptPath: body.transcriptPath,
+ })
+ }
+ json(200, { ok: true })
+ return
+ }
+
+ // `harness pair <code>` → run CPace toward the browser that is waiting to pair. Long-polls until
+ // the handshake completes/fails (bounded by the manager's round timers). Loopback-only; the PAKE
+ // itself is the security (a local process can trigger, but only the real code completes pairing).
+ if (req.method === 'POST' && url === '/api/pair') {
+ if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }
+ if (!handlers.onPair) { json(503, { error: 'PAIRING_UNAVAILABLE' }); return }
+ let body: { code?: string }
+ try { body = JSON.parse(await readBody(req)) as { code?: string } } catch { json(400, { error: 'bad json' }); return }
+ if (!body.code) { json(400, { error: 'MISSING_CODE' }); return }
+ try { const out = await handlers.onPair(body.code); json(out.status, out.body) }
+ catch (e) { json(500, { error: e instanceof Error ? e.message : 'INTERNAL' }) }
+ return
+ }
+
+ // `adapter browser-link` → mint a one-time setup token using the running daemon's E2EE manager
+ // so the nonce is immediately consumable by this process.
+ if (req.method === 'POST' && url === '/api/e2ee/setup-link') {
+ if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }
+ if (!handlers.onSetupLink) { json(503, { error: 'UNAVAILABLE' }); return }
+ const out = handlers.onSetupLink(); json(out.status, out.body); return
+ }
+
+ // `harness pairings` — list paired browsers.
+ if (req.method === 'GET' && url === '/api/pairs') {
+ if (!handlers.onListPairs) { json(503, { error: 'UNAVAILABLE' }); return }
+ const out = handlers.onListPairs(); json(out.status, out.body); return
+ }
+
+ // `harness unpair <id>` — unpair one browser; signals it (if online) to re-pair.
+ if (req.method === 'POST' && url === '/api/revoke') {
+ if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }
+ if (!handlers.onRevoke) { json(503, { error: 'UNAVAILABLE' }); return }
+ let body: { id?: string }
+ try { body = JSON.parse(await readBody(req)) as { id?: string } } catch { json(400, { error: 'bad json' }); return }
+ if (!body.id) { json(400, { error: 'MISSING_ID' }); return }
+ const out = handlers.onRevoke(body.id); json(out.status, out.body); return
+ }
+
+ // `harness unpair --all` — unpair every browser.
+ if (req.method === 'POST' && url === '/api/revoke-all') {
+ if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }
+ if (!handlers.onRevokeAll) { json(503, { error: 'UNAVAILABLE' }); return }
+ const out = handlers.onRevokeAll(); json(out.status, out.body); return
+ }
+
+ json(404, { error: 'not found' })
+ })()
+ })
+
+ attachLauncherWs(server, handlers, port)
+
+ return new Promise((resolve, reject) => {
+ server.once('error', (err: NodeJS.ErrnoException) => {
+ // FIXED port — no OS-assigned fallback. A free-port fallback made the daemon land on an
+ // unpredictable port, so a leftover/zombie couldn't be found by `lsof :<port>`. On a clash we
+ // fail loudly with the exact port instead (the CLI turns this into a clear "already running?").
+ if (err.code === 'EADDRINUSE') {
+ console.error(`[hooks] 127.0.0.1:${port} is already in use — another adapter is probably running.`)
+ console.error(` Stop it: harness stop or find it: lsof -ti :${port} | xargs kill`)
+ } else {
+ console.error('[hooks] listen failed:', err)
+ }
+ reject(err)
+ })
+ server.listen(port, '127.0.0.1', () => {
+ const actual = (server.address() as AddressInfo).port
+ console.log(`[hooks] listening on 127.0.0.1:${actual} (SessionStart/SessionEnd callbacks)`)
+ resolve({ server, port: actual })
+ })
+ })
+}
+
+// ── machine launcher socket ────────────────────────────────────────────────────────────────────────
+/** How often the daemon pings an idle launcher socket. */
+const PING_MS = 10_000
+/**
+ * Missed pongs tolerated before a socket is considered dead.
+ *
+ * NOT 1. The sibling web/device hubs shipped a "one missed pong ⇒ terminate" rule and it killed sockets
+ * that were perfectly alive (a single slow tick under load was enough); sessions died in the 40-60s band
+ * for no reason. Three misses (~30s) is slow enough to ride out a stall and still far faster than the
+ * `ps` polling this replaced.
+ */
+const MAX_MISSED_PONGS = 3
+
+/**
+ * Attach the launcher WebSocket to the existing hook server (same fixed loopback port — no new port, no
+ * firewall change). The socket carries only session lifetime: `{t:'open'}` on connect, and the CLOSE
+ * event is the end-of-session signal. Terminal I/O is not streamed; the adapter still drives the pane
+ * through tmux.
+ */
+function attachLauncherWs(server: http.Server, handlers: HookServerHandlers, port: number): void {
+ const wss = new WebSocketServer({ noServer: true })
+
+ server.on('upgrade', (req, socket, head) => {
+ const path = (req.url ?? '').split('?')[0]
+ // A browser page CAN open a WebSocket to loopback, and unlike fetch() it cannot be stopped by a
+ // custom-header check — but it always sends `Origin`. Our CLI never does. Rejecting any upgrade that
+ // carries one is the WS-side equivalent of the `x-adapter-local` gate on the mutating HTTP routes.
+ if (path !== MACHINE_WS_PATH || req.headers.origin) {
+ socket.destroy()
+ return
+ }
+ wss.handleUpgrade(req, socket, head, (ws) => handleLauncherSocket(ws, handlers, port))
+ })
+
+}
+
+function handleLauncherSocket(ws: WebSocket, handlers: HookServerHandlers, port: number): void {
+ let missed = 0
+ const ping = setInterval(() => {
+ if (missed >= MAX_MISSED_PONGS) {
+ console.log('[machine] launcher socket unresponsive — terminating')
+ try { ws.terminate() } catch { /* already gone */ }
+ return
+ }
+ missed++
+ try { ws.ping() } catch { /* already gone */ }
+ }, PING_MS)
+ ping.unref?.()
+ ws.on('pong', () => { missed = 0 })
+
+ const send = (frame: unknown): void => { try { ws.send(JSON.stringify(frame)) } catch { /* gone */ } }
+
+ ws.on('message', (raw) => {
+ let msg: LauncherOpenFrame
+ try { msg = JSON.parse(raw.toString()) as LauncherOpenFrame } catch { return }
+ if (msg.t !== 'open') return
+
+ // Protocol first: a launcher we cannot understand must be told so explicitly, because everything
+ // below (and the whole session) would otherwise fail silently while its socket stayed happily open.
+ const v = frameProtocol(msg)
+ if (!isSupportedProtocol(v)) {
+ console.warn(`[machine] launcher speaks protocol v${v}; this daemon serves ${SUPPORTED_PROTOCOLS.join(',')}`)
+ send({ t: 'error', reason: 'unsupported_protocol', supported: SUPPORTED_PROTOCOLS })
+ try { ws.close() } catch { /* ignore */ }
+ return
+ }
+
+ const opened = launcherSessions.open(msg as LauncherOpenInput, ws)
+ if (!opened) {
+ console.warn('[machine] rejected launcher socket: invalid open payload')
+ send({ t: 'error', reason: 'invalid_open' })
+ try { ws.close() } catch { /* ignore */ }
+ return
+ }
+ console.log(`[machine] open ${sid(opened.launcherId)} · engine=${opened.engine} · pane=${opened.tmuxPane}`
+ + ` · protocol=v${v}${msg.version && msg.version !== VERSION ? ` · launcher build v${msg.version}` : ''}`)
+
+ // Decided HERE, not in the launcher: both change between builds (hook definitions grow with every
+ // engine; the binary for an engine can be renamed — `commandcode` → `cmd` already happened). A
+ // long-lived launcher from an older build would otherwise install stale hooks and spawn a stale
+ // binary name, so the daemon — always the newest build — owns both.
+ let hooksReady = false
+ if (!env.DISABLE_HOOK_INSTALL) {
+ try { installHooksFor(opened.engine, port); hooksReady = true } catch { /* launcher falls back */ }
+ }
+ send({ t: 'opened', v, version: VERSION, bin: engineBin(opened.engine), hooksReady })
+ // After the ack: adopting a resumed session reads tmux + ps, and the launcher is waiting on this
+ // reply to spawn the engine.
+ handlers.onLauncherOpened?.({
+ launcherId: opened.launcherId, engine: opened.engine, tmuxPane: opened.tmuxPane, cwd: opened.cwd ?? null,
+ })
+ })
+
+ const end = (): void => {
+ clearInterval(ping)
+ // Only evict if THIS socket still owns the id — a reconnect may already have replaced it.
+ const launcherId = launcherSessions.closeBySocket(ws)
+ if (!launcherId) return
+ console.log(`[machine] close ${sid(launcherId)} — launcher socket gone`)
+ handlers.onLauncherClosed?.(launcherId)
+ }
+ ws.on('close', end)
+ ws.on('error', end)
+}
diff --git a/cli/src/launcherProtocol.spec.ts b/cli/src/launcherProtocol.spec.ts
new file mode 100644
index 000000000..b43c75355
--- /dev/null
+++ b/cli/src/launcherProtocol.spec.ts
@@ -0,0 +1,170 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import type { AddressInfo } from 'node:net'
+import { WebSocket } from 'ws'
+import { startHookServer, type HookServerHandlers } from './hookServer.js'
+import { launcherSessions, MACHINE_WS_PATH } from './lib/launcherSessions.js'
+import { SUPPORTED_PROTOCOLS } from './lib/launcherProtocol.js'
+
+/**
+ * THE COMPATIBILITY CONTRACT.
+ *
+ * OTA ships one bundle for both sides, but a running `harness <engine>` keeps its build for hours while
+ * the daemon restarts onto the new one. So every launcher ever released keeps talking to today's daemon.
+ *
+ * The frames below are written out BY HAND on purpose — they are what an old launcher puts on the wire,
+ * not something derived from the current types. If a change to the daemon makes this file red, a
+ * launcher already in someone's terminal just broke; fix the daemon, do not "update" the frame.
+ */
+
+const servers: Array<{ close: () => void }> = []
+afterEach(() => {
+ for (const s of servers.splice(0)) s.close()
+ for (const s of launcherSessions.list()) launcherSessions.close(s.launcherId)
+})
+
+async function boot(over: Partial<HookServerHandlers> = {}): Promise<number> {
+ const { server } = await startHookServer(0, { onRegistered: () => {}, onSessionEnd: () => {}, ...over })
+ servers.push({ close: () => server.close() })
+ return (server.address() as AddressInfo).port
+}
+
+/** Open a socket, send `frame`, and resolve with the daemon's first reply (or null on close). */
+async function exchange(port: number, frame: unknown): Promise<Record<string, unknown> | null> {
+ const ws = new WebSocket(`ws://127.0.0.1:${port}${MACHINE_WS_PATH}`)
+ await new Promise<void>((r) => ws.on('open', () => r()))
+ const reply = new Promise<Record<string, unknown> | null>((resolve) => {
+ ws.on('message', (raw) => resolve(JSON.parse(raw.toString()) as Record<string, unknown>))
+ ws.on('close', () => resolve(null))
+ })
+ ws.send(JSON.stringify(frame))
+ const out = await reply
+ try { ws.close() } catch { /* ignore */ }
+ return out
+}
+
+describe('launcher↔daemon protocol contract', () => {
+ it('accepts a hand-written v1 open frame — the shape released launchers send', async () => {
+ const port = await boot()
+ const reply = await exchange(port, {
+ t: 'open',
+ v: 1,
+ launcherId: '11111111-2222-4333-8444-555555555555',
+ engine: 'claude',
+ tmuxPane: '%3',
+ cwd: '/tmp/demo',
+ version: '0.0.1',
+ })
+ expect(reply?.t).toBe('opened')
+ expect(reply?.v).toBe(1)
+ expect(typeof reply?.version).toBe('string') // the daemon's build, for the stale-build notice
+ expect(launcherSessions.has('11111111-2222-4333-8444-555555555555')).toBe(true)
+ })
+
+ it('accepts a frame with NO version field at all (launchers released before versioning)', async () => {
+ const port = await boot()
+ const reply = await exchange(port, {
+ t: 'open',
+ launcherId: '22222222-2222-4333-8444-555555555555',
+ engine: 'codex',
+ tmuxPane: '%4',
+ cwd: '/tmp/demo',
+ })
+ expect(reply?.t).toBe('opened')
+ expect(launcherSessions.has('22222222-2222-4333-8444-555555555555')).toBe(true)
+ })
+
+ it('answers an unsupported protocol explicitly instead of ignoring it', async () => {
+ const port = await boot()
+ // Silence is the failure mode this replaces: the socket would stay open, so the launcher would see no
+ // disconnect, while the session never registered.
+ const reply = await exchange(port, {
+ t: 'open', v: 99, launcherId: '33333333-2222-4333-8444-555555555555',
+ engine: 'claude', tmuxPane: '%5', cwd: '/tmp/demo',
+ })
+ expect(reply?.t).toBe('error')
+ expect(reply?.reason).toBe('unsupported_protocol')
+ expect(reply?.supported).toEqual([...SUPPORTED_PROTOCOLS])
+ })
+
+ it('tells the launcher which engine binary to run, so binary policy lives in the daemon', async () => {
+ const port = await boot()
+ const reply = await exchange(port, {
+ t: 'open', v: 1, launcherId: '44444444-2222-4333-8444-555555555555',
+ engine: 'commandcode', tmuxPane: '%6', cwd: '/tmp/demo', version: '0.0.1',
+ })
+ // `commandcode` → `cmd` was a real rename; an old launcher must not be left spawning the old name.
+ expect(reply?.bin).toBe('cmd')
+ })
+
+ it('never removes a protocol version — SUPPORTED_PROTOCOLS only grows', () => {
+ // Dropping a version breaks launchers already running in someone's terminal. Adding is fine.
+ expect(SUPPORTED_PROTOCOLS).toContain(1)
+ })
+
+ it('pushes a notice to a live launcher without disturbing its socket', async () => {
+ const port = await boot()
+ const ws = new WebSocket(`ws://127.0.0.1:${port}${MACHINE_WS_PATH}`)
+ await new Promise<void>((r) => ws.on('open', () => r()))
+ const frames: Array<Record<string, unknown>> = []
+ let closed = false
+ ws.on('message', (raw) => { frames.push(JSON.parse(raw.toString()) as Record<string, unknown>) })
+ ws.on('close', () => { closed = true })
+ ws.send(JSON.stringify({
+ t: 'open', v: 1, launcherId: '55555555-2222-4333-8444-555555555555',
+ engine: 'claude', tmuxPane: '%9', cwd: '/tmp/demo', version: '0.0.1',
+ }))
+ await vi.waitFor(() => expect(frames.some((f) => f.t === 'opened')).toBe(true))
+
+ // Unprompted: nothing on the launcher asked for this, which is the whole point of the frame.
+ await launcherSessions.notifyAll({ t: 'notice', level: 'warn', text: 'restarting', durationMs: 8_000 })
+
+ await vi.waitFor(() => expect(frames.some((f) => f.t === 'notice')).toBe(true))
+ const notice = frames.find((f) => f.t === 'notice')
+ expect(notice).toMatchObject({ level: 'warn', text: 'restarting', durationMs: 8_000 })
+ // A notice is not a goodbye: the session stays live and the socket stays open.
+ expect(closed).toBe(false)
+ expect(launcherSessions.has('55555555-2222-4333-8444-555555555555')).toBe(true)
+ ws.close()
+ })
+
+ it('delivers an exit request verbatim, and leaves the socket for the launcher to close', async () => {
+ const port = await boot()
+ const ws = new WebSocket(`ws://127.0.0.1:${port}${MACHINE_WS_PATH}`)
+ await new Promise<void>((r) => ws.on('open', () => r()))
+ const frames: Array<Record<string, unknown>> = []
+ let closed = false
+ ws.on('message', (raw) => { frames.push(JSON.parse(raw.toString()) as Record<string, unknown>) })
+ ws.on('close', () => { closed = true })
+ const launcherId = '77777777-2222-4333-8444-555555555555'
+ ws.send(JSON.stringify({
+ t: 'open', v: 1, launcherId, engine: 'claude', tmuxPane: '%11', cwd: '/tmp/demo', version: '0.0.1',
+ }))
+ await vi.waitFor(() => expect(frames.some((f) => f.t === 'opened')).toBe(true))
+
+ launcherSessions.get(launcherId)?.socket.send(JSON.stringify({ t: 'exit', reason: 'deleted' }))
+
+ await vi.waitFor(() => expect(frames.some((f) => f.t === 'exit')).toBe(true))
+ expect(frames.find((f) => f.t === 'exit')).toMatchObject({ reason: 'deleted' })
+ // The daemon does NOT hang up: the launcher still needs the socket while it stops its engine, and the
+ // close must come from its own child-exit path so teardown stays on one route.
+ expect(closed).toBe(false)
+ ws.close()
+ })
+
+ it('survives notifying a launcher that has already gone', async () => {
+ const port = await boot()
+ const ws = new WebSocket(`ws://127.0.0.1:${port}${MACHINE_WS_PATH}`)
+ await new Promise<void>((r) => ws.on('open', () => r()))
+ ws.send(JSON.stringify({
+ t: 'open', v: 1, launcherId: '66666666-2222-4333-8444-555555555555',
+ engine: 'claude', tmuxPane: '%10', cwd: '/tmp/demo', version: '0.0.1',
+ }))
+ await vi.waitFor(() => expect(launcherSessions.has('66666666-2222-4333-8444-555555555555')).toBe(true))
+ ws.terminate() // the pane's terminal window was closed
+ await vi.waitFor(() => expect(launcherSessions.has('66666666-2222-4333-8444-555555555555')).toBe(false))
+
+ // The only caller so far is the update restart. A dead socket there must never throw, hang, or take
+ // the restart down with it.
+ await expect(launcherSessions.notifyAll({ t: 'notice', text: 'still here?' })).resolves.toBeUndefined()
+ })
+})
diff --git a/cli/src/launcherWs.spec.ts b/cli/src/launcherWs.spec.ts
new file mode 100644
index 000000000..4401fc289
--- /dev/null
+++ b/cli/src/launcherWs.spec.ts
@@ -0,0 +1,185 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import type { AddressInfo } from 'node:net'
+import { WebSocket } from 'ws'
+import { startHookServer, type HookServerHandlers } from './hookServer.js'
+import { launcherSessions, MACHINE_WS_PATH } from './lib/launcherSessions.js'
+import { markDeleted, resetDeleted } from './lib/deletedSessions.js'
+
+/**
+ * The launcher socket is the adapter's liveness signal: while it is open the session exists, and its
+ * close is what drops the tile. These tests pin that contract plus the upgrade gate.
+ */
+
+const servers: Array<{ close: () => void }> = []
+
+afterEach(() => {
+ resetDeleted()
+ for (const s of servers.splice(0)) s.close()
+ for (const s of launcherSessions.list()) launcherSessions.close(s.launcherId)
+})
+
+const noopHandlers = (over: Partial<HookServerHandlers> = {}): HookServerHandlers => ({
+ onRegistered: () => {},
+ onSessionEnd: () => {},
+ ...over,
+})
+
+async function boot(over: Partial<HookServerHandlers> = {}): Promise<number> {
+ const { server } = await startHookServer(0, noopHandlers(over))
+ servers.push({ close: () => server.close() })
+ return (server.address() as AddressInfo).port
+}
+
+function connect(port: number, headers?: Record<string, string>, path = MACHINE_WS_PATH): WebSocket {
+ return new WebSocket(`ws://127.0.0.1:${port}${path}`, { headers })
+}
+
+const OPEN = {
+ t: 'open',
+ launcherId: '11111111-2222-4333-8444-555555555555',
+ engine: 'claude',
+ tmuxPane: '%3',
+ cwd: '/tmp/demo',
+}
+
+describe('harness launcher socket', () => {
+ it('registers the session while the socket is open, and drops it the moment it closes', async () => {
+ const closed: string[] = []
+ const port = await boot({ onLauncherClosed: (id) => closed.push(id) })
+ const ws = connect(port)
+ await new Promise<void>((r) => ws.on('open', () => r()))
+ ws.send(JSON.stringify(OPEN))
+
+ await vi.waitFor(() => expect(launcherSessions.has(OPEN.launcherId)).toBe(true))
+ // Only a live id makes a hook registration count as an agent (hookServer gates on this).
+ expect(launcherSessions.get(OPEN.launcherId)?.tmuxPane).toBe('%3')
+
+ ws.close()
+ await vi.waitFor(() => expect(launcherSessions.has(OPEN.launcherId)).toBe(false))
+ expect(closed).toEqual([OPEN.launcherId]) // → forgetSession, no reaper, no polling
+ })
+
+ it('will not let a just-deleted session register itself again', async () => {
+ // Deleting an agent no longer kills its pane, so the engine keeps running for a moment and its catch
+ // hook (every turn boundary) still POSTs here. The launcher IS alive, which is all this endpoint used
+ // to check — so without the tombstone the tile the user deleted comes straight back.
+ const registered: string[] = []
+ const port = await boot({ onRegistered: (entry) => registered.push(entry.sessionId) })
+ const ws = connect(port)
+ await new Promise<void>((r) => ws.on('open', () => r()))
+ ws.send(JSON.stringify(OPEN))
+ await vi.waitFor(() => expect(launcherSessions.has(OPEN.launcherId)).toBe(true))
+
+ const post = (sessionId: string): Promise<Response> => fetch(`http://127.0.0.1:${port}/api/hook/session-start`, {
+ method: 'POST',
+ body: JSON.stringify({
+ sessionId, launcherId: OPEN.launcherId, engine: 'cursor', tmuxPane: '%3',
+ cwd: '/tmp/demo', hookEvent: 'UserPromptSubmit',
+ }),
+ })
+
+ await post('live-session')
+ await vi.waitFor(() => expect(registered).toEqual(['live-session']))
+
+ markDeleted('doomed-session')
+ const res = await post('doomed-session')
+ expect(await res.json()).toMatchObject({ ignored: true, reason: 'deleted' })
+ expect(registered).toEqual(['live-session'])
+
+ ws.close()
+ })
+
+ it('waits for a transcript the engine announced but has not written yet', async () => {
+ // Claude fires SessionStart BEFORE creating the file — measured 3s apart on a real pane. Registration
+ // requires a real file behind a session, so the announcement used to be refused outright and the agent
+ // stayed off the list until something else stumbled on it.
+ const projects = mkdtempSync(join(tmpdir(), 'hookwait-'))
+ const transcriptPath = join(projects, 'late-session.jsonl')
+ process.env.CLAUDE_PROJECTS_DIR = projects
+ vi.resetModules()
+ const { startHookServer: freshServer } = await import('./hookServer.js')
+ const { launcherSessions: freshBook, MACHINE_WS_PATH: freshPath } = await import('./lib/launcherSessions.js')
+ const registered: string[] = []
+ const { server } = await freshServer(0, { onRegistered: (e) => registered.push(e.sessionId), onSessionEnd: () => {} })
+ servers.push({ close: () => { server.close(); rmSync(projects, { recursive: true, force: true }) } })
+ const port = (server.address() as { port: number }).port
+
+ const ws = new WebSocket(`ws://127.0.0.1:${port}${freshPath}`)
+ await new Promise<void>((r) => ws.on('open', () => r()))
+ ws.send(JSON.stringify(OPEN))
+ await vi.waitFor(() => expect(freshBook.has(OPEN.launcherId)).toBe(true))
+
+ const res = await fetch(`http://127.0.0.1:${port}/api/hook/session-start`, {
+ method: 'POST',
+ body: JSON.stringify({
+ sessionId: 'late-session', launcherId: OPEN.launcherId, engine: 'claude',
+ tmuxPane: '%3', cwd: '/tmp/demo', transcriptPath, hookEvent: 'SessionStart',
+ }),
+ })
+ expect(await res.json()).toMatchObject({ pending: true })
+ expect(registered).toEqual([]) // nothing to register yet — and nothing refused either
+
+ writeFileSync(transcriptPath, '{}\n') // the engine finishes starting up
+ await vi.waitFor(() => expect(registered).toEqual(['late-session']), { timeout: 5_000 })
+ ws.close()
+ freshBook.close(OPEN.launcherId)
+ })
+
+ it('refuses an upgrade that carries an Origin header (i.e. from a web page)', async () => {
+ const port = await boot()
+ // A browser cannot omit Origin, and unlike fetch() it can open a loopback WebSocket freely — so this
+ // is the WS-side equivalent of the x-adapter-local gate on the mutating HTTP routes.
+ const ws = connect(port, { Origin: 'http://evil.example' })
+ const outcome = await new Promise<string>((r) => {
+ ws.on('open', () => r('open'))
+ ws.on('error', () => r('refused'))
+ ws.on('close', () => r('refused'))
+ })
+ expect(outcome).toBe('refused')
+ })
+
+ it('refuses an upgrade on any other path', async () => {
+ const port = await boot()
+ const ws = connect(port, undefined, '/api/not-machine')
+ const outcome = await new Promise<string>((r) => {
+ ws.on('open', () => r('open'))
+ ws.on('error', () => r('refused'))
+ ws.on('close', () => r('refused'))
+ })
+ expect(outcome).toBe('refused')
+ })
+
+ it('drops a socket whose open payload is invalid', async () => {
+ const port = await boot()
+ const ws = connect(port)
+ await new Promise<void>((r) => ws.on('open', () => r()))
+ ws.send(JSON.stringify({ ...OPEN, tmuxPane: 'not-a-pane' }))
+ await new Promise<void>((r) => ws.on('close', () => r()))
+ expect(launcherSessions.has(OPEN.launcherId)).toBe(false)
+ })
+
+ it('lets a reconnect reclaim the same id without the old socket evicting it', async () => {
+ const closed: string[] = []
+ const port = await boot({ onLauncherClosed: (id) => closed.push(id) })
+
+ const first = connect(port)
+ await new Promise<void>((r) => first.on('open', () => r()))
+ first.send(JSON.stringify(OPEN))
+ await vi.waitFor(() => expect(launcherSessions.has(OPEN.launcherId)).toBe(true))
+
+ // Same launcher reconnecting (e.g. after a daemon self-update restart) re-announces the SAME id.
+ const second = connect(port)
+ await new Promise<void>((r) => second.on('open', () => r()))
+ second.send(JSON.stringify(OPEN))
+ await vi.waitFor(() => expect(launcherSessions.get(OPEN.launcherId)).toBeTruthy())
+
+ // The superseded socket closing must NOT take the session down with it.
+ await vi.waitFor(() => expect(first.readyState).toBe(WebSocket.CLOSED))
+ await new Promise((r) => setTimeout(r, 50))
+ expect(launcherSessions.has(OPEN.launcherId)).toBe(true)
+ expect(closed).toEqual([])
+ })
+})
diff --git a/cli/src/lib/__fixtures__/hermes-async-delegation.json b/cli/src/lib/__fixtures__/hermes-async-delegation.json
new file mode 100644
index 000000000..5f96da85b
--- /dev/null
+++ b/cli/src/lib/__fixtures__/hermes-async-delegation.json
@@ -0,0 +1,62 @@
+[
+ {
+ "id": 284,
+ "role": "user",
+ "content": "Chạy 2 sub-agent SONG SONG (launch cả 2 cùng lúc): agent 1 đếm số file .md trong repo, agent 2 đếm số file .ts. Xong báo lại.",
+ "toolCallId": null,
+ "toolCalls": null,
+ "toolName": null,
+ "finishReason": null,
+ "reasoning": null
+ },
+ {
+ "id": 285,
+ "role": "assistant",
+ "content": "Mình sẽ launch 2 sub-agent song song để đếm file trong repo.",
+ "toolCallId": null,
+ "toolCalls": "[{\"id\": \"call_be161d7ab3c33e30\", \"call_id\": \"call_be161d7ab3c33e30\", \"response_item_id\": \"fc_be161d7ab3c33e30\", \"type\": \"function\", \"function\": {\"name\": \"delegate_task\", \"arguments\": \"{\\\"tasks\\\":[{\\\"goal\\\":\\\"\\u0110\\u1ebfm t\\u1ed5ng s\\u1ed1 file c\\u00f3 \\u0111u\\u00f4i .md (Markdown) trong th\\u01b0 m\\u1ee5c /Users/example/Work/ai-workers/opencode-agent1 (\\u0111\\u1ec7 quy, bao g\\u1ed3m c\\u1ea3 th\\u01b0 m\\u1ee5c con). B\\u1ecf qua c\\u00e1c th\\u01b0 m\\u1ee5c \\u1ea9n nh\\u01b0 .git, node_modules, dist, build, .next, .venv, __pycache__ n\\u1ebfu c\\u00f3. Tr\\u1ea3 v\\u1ec1 k\\u1ebft qu\\u1ea3: t\\u1ed5ng s\\u1ed1 file .md t\\u00ecm \\u0111\\u01b0\\u1ee3c, v\\u00ed d\\u1ee5 1-2 file \\u0111\\u1ea1i di\\u1ec7n (\\u0111\\u01b0\\u1eddng d\\u1eabn \\u0111\\u1ea7y \\u0111\\u1ee7), v\\u00e0 c\\u00e2u l\\u1ec7nh shell \\u0111\\u00e3 d\\u00f9ng \\u0111\\u1ec3 \\u0111\\u1ebfm. Tr\\u1ea3 l\\u1eddi b\\u1eb1ng ti\\u1ebfng Vi\\u1ec7t.\\\",\\\"role\\\":\\\"leaf\\\"},{\\\"goal\\\":\\\"\\u0110\\u1ebfm t\\u1ed5ng s\\u1ed1 file c\\u00f3 \\u0111u\\u00f4i .ts (TypeScript) trong th\\u01b0 m\\u1ee5c /Users/example/Work/ai-workers/opencode-agent1 (\\u0111\\u1ec7 quy, bao g\\u1ed3m c\\u1ea3 th\\u01b0 m\\u1ee5c con). B\\u1ecf qua c\\u00e1c th\\u01b0 m\\u1ee5c \\u1ea9n nh\\u01b0 .git, node_modules, dist, build, .next, .venv, __pycache__ n\\u1ebfu c\\u00f3. Tr\\u1ea3 v\\u1ec1 k\\u1ebft qu\\u1ea3: t\\u1ed5ng s\\u1ed1 file .ts t\\u00ecm \\u0111\\u01b0\\u1ee3c, v\\u00ed d\\u1ee5 1-2 file \\u0111\\u1ea1i di\\u1ec7n (\\u0111\\u01b0\\u1eddng d\\u1eabn \\u0111\\u1ea7y \\u0111\\u1ee7), v\\u00e0 c\\u00e2u l\\u1ec7nh shell \\u0111\\u00e3 d\\u00f9ng \\u0111\\u1ec3 \\u0111\\u1ebfm. Tr\\u1ea3 l\\u1eddi b\\u1eb1ng ti\\u1ebfng Vi\\u1ec7t.\\\",\\\"role\\\":\\\"leaf\\\"}]}\"}}]",
+ "toolName": null,
+ "finishReason": "tool_calls",
+ "reasoning": null
+ },
+ {
+ "id": 286,
+ "role": "tool",
+ "content": "{\"status\": \"dispatched\", \"mode\": \"background\", \"count\": 2, \"delegation_id\": \"deleg_3c9f8264\", \"goals\": [\"Đếm tổng số file có đuôi .md (Markdown) trong thư mục /Users/example/Work/ai-workers/opencode-agent1 (đệ quy, bao gồm cả thư mục con). Bỏ qua các thư mục ẩn như .git, node_modules, dist, build, .next, .venv, __pycache__ nếu có. Trả về kết quả: tổng số file .md tìm được, ví dụ 1-2 file đại diện (đường dẫn đầy đủ), và câu lệnh shell đã dùng để đếm. Trả lời bằng tiếng Việt.\", \"Đếm tổng số file có đuôi .ts (TypeScript) trong thư mục /Users/example/Work/ai-workers/opencode-agent1 (đệ quy, bao gồm cả thư mục con). Bỏ qua các thư mục ẩn như .git, node_modules, dist, build, .next, .venv, __pycache__ nếu có. Trả về kết quả: tổng số file .ts tìm được, ví dụ 1-2 file đại diện (đường dẫn đầy đủ), và câu lệnh shell đã dùng để đếm. Trả lời bằng tiếng Việt.\"], \"note\": \"2 subagents are running in parallel in the background. You and the user can keep working; they wait on each other and their consolidated results re-enter the conversation as a single message once ALL of them finish. Do not wait or poll — just continue.\", \"live_transcripts\": [\"/Users/example/.hermes/cache/delegation/live/deleg_3c9f8264/task-0.log\", \"/Users/example/.hermes/cache/delegation/live/deleg_3c9f8264/task-1.log\"], \"live_transcripts_hint\": \"Each subagent streams a human-readable transcript of its operations to the file listed above (append-only, one per task). Read or `tail -f` these paths at any time to watch a child work while it runs.\"}",
+ "toolCallId": "call_be161d7ab3c33e30",
+ "toolCalls": null,
+ "toolName": "delegate_task",
+ "finishReason": null,
+ "reasoning": null
+ },
+ {
+ "id": 289,
+ "role": "assistant",
+ "content": "Đã launch 2 sub-agent song song:\n\n- **Agent 1**: đếm số file `.md` trong repo\n- **Agent 2**: đếm số file `.ts` trong repo\n\nMình sẽ tổng hợp khi cả hai xong. Trong lúc chờ bạn có thể tiếp tục làm việc khác.",
+ "toolCallId": null,
+ "toolCalls": null,
+ "toolName": null,
+ "finishReason": "stop",
+ "reasoning": null
+ },
+ {
+ "id": 305,
+ "role": "user",
+ "content": "[ASYNC DELEGATION BATCH COMPLETE — deleg_3c9f8264]\nA background fan-out of 2 subagent(s) you dispatched earlier has finished. All ran in parallel and waited on each other; their consolidated results are below. You may have moved on since dispatching — act on these or re-dispatch if things have changed.\n\nDispatched: 2026-08-05 11:04:38 (33s ago)\nRole: leaf Model: ? Total duration: 34.49s\n\n--- ✓ TASK 1/2: Đếm tổng số file có đuôi .md (Markdown) trong thư mục /Users/example/Work/ai-workers/opencode-agent1 (đệ quy, bao gồm cả thư mục con). Bỏ qua các thư mục ẩn như .git, node_modules, dist, build, .next, .venv, __pycache__ nếu có. Trả về kết quả: tổng số file .md tìm được, ví dụ 1-2 file đại diện (đường dẫn đầy đủ), và câu lệnh shell đã dùng để đếm. Trả lời bằng tiếng Việt. (status=completed, api_calls=3, 18.27s) ---\n## Kết quả\n\n**Tổng số file `.md` tìm được: 3 file**\n\n**File đại diện (2/3):**\n- `/Users/example/Work/ai-workers/opencode-agent1/TODO.md`\n- `/Users/example/Work/ai-workers/opencode-agent1/.commandcode/taste/taste.md`\n\n**Danh sách đầy đủ (3 file):**\n1. `/Users/example/Work/ai-workers/opencode-agent1/TODO.md`\n2. `/Users/example/Work/ai-workers/opencode-agent1/.commandcode/taste/taste.md`\n3. `/Users/example/Work/ai-workers/opencode-agent1/.commandcode/taste/sample/taste.md`\n\n**Câu lệnh shell đã dùng:**\n```bash\nfind /Users/example/Work/ai-workers/opencode-agent1 \\\n -type d \\( -name '.git' -o -name 'node_modules' -o -name 'dist' -o -name 'build' -o -name '.next' -o -name '.venv' -o -name '__pycache__' \\) -prune -o \\\n -type f -name '*.md' -print | tee /tmp/md_files_list.txt | wc -l\n```\n\n**Giải thích ngắn:**\n- `-type d ... -prune -o`: bỏ qua các thư mục ẩn/build output đã liệt kê (các thư mục khớp sẽ bị cắt khỏi cây tìm kiếm).\n- `-type f -name '*.md' -print`: chỉ in ra file `.md`.\n- `tee` đồng thời lưu danh sách để xem, `wc -l` đếm dòng (= số file).\nFull live transcript (complete tool/assistant trace): /Users/example/.hermes/cache/delegation/live/deleg_3c9f8264/task-0.log\n\n--- ✓ TASK 2/2: Đếm tổng số file có đuôi .ts (TypeScript) trong thư mục /Users/example/Work/ai-workers/opencode-agent1 (đệ quy, bao gồm cả thư mục con). Bỏ qua các thư mục ẩn như .git, node_modules, dist, build, .next, .venv, __pycache__ nếu có. Trả về kết quả: tổng số file .ts tìm được, ví dụ 1-2 file đại diện (đường dẫn đầy đủ), và câu lệnh shell đã dùng để đếm. Trả lời bằng tiếng Việt. (status=completed, api_calls=4, 33.9s) ---\nĐã xác nhận — thư mục này thực sự không chứa file `.ts` nào. Các file hiện có chỉ là: `TODO.md`, `agent2/index.html`, `agent2/script.js`, `agent2/style.css`, và 2 file `taste.md` trong `.commandcode/`.\n\n## Kết quả\n\n- **Tổng số file `.ts` tìm được: 0**\n- **Ví dụ file đại diện**: Không có (không tìm thấy file `.ts` nào)\n- **Câu lệnh shell đã dùng để đếm**:\n\n```bash\ncd /Users/example/Work/ai-workers/opencode-agent1 && find . \\( -name \".git\" -o -name \"node_modules\" -o -name \"dist\" -o -name \"build\" -o -name \".next\" -o -name \".venv\" -o -name \"__pycache__\" \\) -prune -o -type f -name \"*.ts\" -print | tee /tmp/ts_files_list.txt | wc -l\n```\n\n**Ghi chú**: Thư mục `opencode-agent1` hiện chỉ chứa file `TODO.md`, thư mục con `agent2/` (với `index.html`, `script.js`, `style.css` — không có `.ts`), và thư mục ẩn `.commandcode/` (chỉ chứa file `.md`). Không phát hiện thư mục `.git`, `node_modules`, `dist`, `build`, `.next`, `.venv`, `__pycache__` trong cây thư mục.\nFull live transcript (complete tool/assistant trace): /Users/example/.hermes/cache/delegation/live/deleg_3c9f8264/task-1.log",
+ "toolCallId": null,
+ "toolCalls": null,
+ "toolName": null,
+ "finishReason": null,
+ "reasoning": null
+ },
+ {
+ "id": 306,
+ "role": "assistant",
+ "content": "Tổng hợp kết quả từ 2 sub-agent:\n\n## 📂 Kết quả đếm file trong repo `/Users/example/Work/ai-workers/opencode-agent1`\n\n| Loại | Số lượng |\n|---|---|\n| **File `.md`** | **3** |\n| **File `.ts`** | **0** |\n\n### 📄 Danh sách file `.md` (3 file)\n1. `/Users/example/Work/ai-workers/opencode-agent1/TODO.md`\n2. `/Users/example/Work/ai-workers/opencode-agent1/.commandcode/taste/taste.md`\n3. `/Users/example/Work/ai-workers/opencode-agent1/.commandcode/taste/sample/taste.md`\n\n### 📘 File `.ts`\n**Không có file `.ts` nào** trong repo. Repo hiện chỉ có `TODO.md`, thư mục `agent2/` (chứa `index.html`, `script.js`, `style.css`) và thư mục ẩn `.commandcode/` (chỉ chứa file `.md`).\n\nCả 2 sub-agent đều dùng `find` với `-prune` để bỏ qua `.git`, `node_modules`, `dist`, `build`, `.next`, `.venv`, `__pycache__`.",
+ "toolCallId": null,
+ "toolCalls": null,
+ "toolName": null,
+ "finishReason": "stop",
+ "reasoning": null
+ }
+]
\ No newline at end of file
diff --git a/cli/src/lib/__fixtures__/question-commandcode-review.txt b/cli/src/lib/__fixtures__/question-commandcode-review.txt
new file mode 100644
index 000000000..1269be20e
--- /dev/null
+++ b/cli/src/lib/__fixtures__/question-commandcode-review.txt
@@ -0,0 +1,167 @@
+⠶ Ok, bỏ caro, làm game cờ vua hoàn chỉnh trong index.html: đủ luật (chiếu tướng, nhập thành, bắt tốt qua đường, phong cấp), chơi 2 người hoặc với máy (AI minimax).
+
+ WRITE  [index.html]
+ └ The file /Users/example/Working/Tmux/Agent-6/index.html has been updated successfully.
+
+✻ Thought for 12 seconds [ctrl+o to expand]
+
+⠶ Xong file chính, giờ tôi sửa 2 lỗi nhỏ: kiểm tra hộp thoại phong cấp và điều kiện nhập thành phải kiểm tra xe thật sự còn ở góc.
+
+ EDIT  [index.html]
+ │ Edited /Users/example/Working/Tmux/Agent-6/index.html (1 replacement)
+ └  ... +15 lines [ctrl+o to expand]
+
+ EDIT  [index.html]
+ │ Edited /Users/example/Working/Tmux/Agent-6/index.html (1 replacement)
+ └  ... +17 lines [ctrl+o to expand]
+
+✻ Thought for 1 second [ctrl+o to expand]
+
+⠶ Giờ tôi kiểm tra cú pháp JS bằng cách tách phần script ra và chạy node --check.
+
+ SHELL  [awk '/<script>/{flag=1;next}/<\/script>/{flag=0}flag' index.html > /tmp/check_chess.js && ...]
+ └ SYNTAX OK
+
+⠶ Cú pháp ổn. Mở game trong trình duyệt.
+
+ SHELL  [open index.html]
+ └ (no output)
+
+⠶ Xong, đã thay bằng game cờ vua trong index.html và mở trong trình duyệt:
+
+ - 🤖 Chơi với máy: bạn cầm quân Trắng đi trước; AI dùng minimax + alpha-beta cắt tỉa độ sâu 3, có bảng vị trí (piece-square tables) nên chơi khá khá
+ - 👥 2 người chơi: đấu cùng bàn
+ - Đủ luật: chiếu tướng, chiếu hết, hòa hết nước, bắt tốt qua đường, nhập thành (kể cả cánh hậu), phong cấp (hiện hộp thoại chọn ♛♜♝♞)
+ - ↩️ Đi lại: undo nước đi (chơi với máy thì undo 1 lượt đi của cả 2 bên)
+
+ Nếu muốn AI mạnh hơn (tăng độ sâu tìm kiếm), thêm đồng hồ đếm giờ, hoặc đổi giao diện thì cứ nói tôi.
+
+ TASTE  Learned
+ └ Changes their mind repeatedly mid-task and expects prior work to be fully discarded/replaced with the new request rather than merged or preserved (abandoned a finished Mario game for caro, then swapped caro for a full chess
+ game — three consecutive game switches, each announced with "đổi ý") [Confidence 95%]
+ ]8;;file:///Users/example/Working/Tmux/Agent-6/.commandcode/taste/taste.md\taste.md]8;;\
+
+❯ Cho tao nhiều cái option để lựa hình dạng của quân cờ và màu sắc
+
+✻ Thought for 76 seconds [ctrl+o to expand]
+
+⠶ Giỏi đấy, thêm hệ thống tùy chọn: kiểu quân cờ (vẽ vector / ký hiệu / hình khối), màu bàn cờ, và màu quân cờ. Để tôi đọc lại file trước khi sửa.
+
+ READ  [index.html] 60 lines
+
+ READ  [index.html] 120 lines
+
+✻ Thought for 19 seconds [ctrl+o to expand]
+
+⠶ Giờ tôi thêm giao diện tùy chọn: CSS cho nhóm select, thêm 3 dropdown (kiểu quân, màu bàn, màu quân) vào toolbar.
+
+ EDIT  [index.html]
+ │ Edited /Users/example/Working/Tmux/Agent-6/index.html (1 replacement)
+ └  ... +36 lines [ctrl+o to expand]
+
+ EDIT  [index.html]
+ │ Edited /Users/example/Working/Tmux/Agent-6/index.html (1 replacement)
+ └  ... +26 lines [ctrl+o to expand]
+
+⠶ Bây giờ thêm state cho tùy chọn và viết hàm vẽ vector/khối. Tôi thêm sau dòng let history... và thay phần vẽ quân cờ.
+
+ EDIT  [index.html]
+ │ Edited /Users/example/Working/Tmux/Agent-6/index.html (1 replacement)
+ └  ... +21 lines [ctrl+o to expand]
+
+⠶ Giờ thay phần vẽ quân cờ trong drawBoard để gọi hàm vẽ theo style, và thêm các hàm vẽ vector/khối + bind sự kiện cho dropdown.
+
+ EDIT  [index.html]
+ │ Edited /Users/example/Working/Tmux/Agent-6/index.html (1 replacement)
+ └  ... +40 lines [ctrl+o to expand]
+
+⠶ Giờ thêm phần tô màu ô bàn cờ theo theme (trong drawBoard), và bind sự kiện cho dropdown ở cuối file.
+
+ EDIT  [index.html]
+ │ Edited /Users/example/Working/Tmux/Agent-6/index.html (1 replacement)
+ └  ... +15 lines [ctrl+o to expand]
+
+ EDIT  [index.html]
+ │ Edited /Users/example/Working/Tmux/Agent-6/index.html (1 replacement)
+ └  ... +15 lines [ctrl+o to expand]
+
+⠶ Kiểm tra cú pháp rồi mở lại trình duyệt.
+
+ SHELL  [awk '/<script>/{flag=1;next}/<\/script>/{flag=0}flag' index.html > /tmp/check_chess.js && ...]
+ └ SYNTAX OK
+
+⠶ Xong! Đã thêm hàng tùy chọn phía trên bàn cờ gồm 3 dropdown:
+
+ - Quân cờ (hình dạng): 3 kiểu —
+
+ - ♞ Ký hiệu: dùng ký tự Unicode như cũ
+ - Vector 3D: vẽ tay bằng canvas — tốt có đế/đầu/vương miện, hậu có mão, mã có đầu ngựa, xe có răng cưa
+ - Khối màu: quân được biểu diễn bằng hình khối (tốt = nửa tròn, mã = chữ L, tượng = thoi, xe = vuông, hậu = sao, vua = tròn + thập)
+ - Bàn cờ: 4 màu — Cổ điển (be/nâu), Xanh lá, Gỗ, Tối
+ - Quân cờ (màu): Trắng/Đen, Đỏ/Xanh, Vàng/Đen — áp dụng cho cả 3 kiểu vẽ
+
+ Đổi lựa chọn là bàn cờ vẽ lại ngay. Cứ chọn thoải mái, muốn thêm kiểu nào nữa (ví dụ bàn cờ gỗ sáng, quân hồng/tím) thì nói tôi thêm.
+
+ TASTE  Learned
+ └ Uses informal/casual Vietnamese register (e.g., "tao", "cho tao") and expects a relaxed, colloquial tone in replies [Confidence 80%]
+ ]8;;file:///Users/example/Working/Tmux/Agent-6/.commandcode/taste/taste.md\taste.md]8;;\
+
+ TASTE  Learned
+ └ Likes games to offer many user-selectable appearance options (piece shapes, board color themes, piece color themes) via in-game UI controls rather than a single fixed look — requested "nhiều cái option" for piece style and
+ colors [Confidence 70%]
+ ]8;;file:///Users/example/Working/Tmux/Agent-6/.commandcode/taste/game-dev/taste.md\game-dev/taste.md]8;;\
+
+❯ Ý tao là mày đưa ra những cái option và tao chọn sau khi tao chọn xong thì mới code theo cái option của tao chứ không phải đưa trên UI mày hiểu không
+
+✻ Thought for 2 seconds [ctrl+o to expand]
+
+⠶ À hiểu rồi, xin lỗi nhé. Tôi hỏi mày chọn trước, chọn xong tôi mới code theo đúng lựa chọn.
+
+ QUESTION  [User answered questions]
+ │ Quân cờ mày muốn hình dạng kiểu nào? → dung di, ko lam nua
+ │ Bàn cờ mày muốn màu gì? → dung
+ └  ... +1 lines [ctrl+o to expand]
+
+✻ Thought for 1 second [ctrl+o to expand]
+
+⠶ Ok dừng. Game cờ vua vẫn còn trong index.html đó, khi nào muốn chỉnh lại cứ nói nhé.
+
+ TASTE  Learned
+ └ Wants appearance options (piece style, board colors, piece colors) offered by the assistant as pre-build choices — the user picks first, then only the chosen option gets coded; explicitly rejected building options into an
+ in-game UI ("chứ không phải đưa trên UI") [Confidence 85%]
+ ]8;;file:///Users/example/Working/Tmux/Agent-6/.commandcode/taste/game-dev/taste.md\game-dev/taste.md]8;;\
+
+ TASTE  Learned
+ └ When they ask for "options" (tùy chọn), they mean: the assistant presents the options and the user picks, and only after the user chooses does the assistant write the code — not implementing all options into the product/UI.
+ Explicitly corrected the assistant on this ("đưa option, tao chọn xong rồi mới code") [Confidence 90%]
+ ]8;;file:///Users/example/Working/Tmux/Agent-6/.commandcode/taste/taste.md\taste.md]8;;\
+
+❯ Gửi cho theo lại một vài sự lựa chọn đi
+
+✻ Thought for 1 second [ctrl+o to expand]
+
+⠶ Ok, đây lại các lựa chọn để mày chọn.
+
+ QUESTION  [User answered questions]
+ └  Processing…
+
+
+────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+✔ Kiểu quân cờ | ✔ Màu bàn cờ | ✔ Màu quân cờ | ● Review
+
+1. Quân cờ mày muốn hình dạng kiểu nào?
+ Ký hiệu Unicode
+
+2. Bàn cờ mày muốn màu gì?
+ Xanh lá
+
+3. Màu của 2 phe quân cờ thế nào?
+ Đỏ / Xanh
+
+❯ 1. Submit
+  2. Cancel
+
+← to go back and edit
+
+
diff --git a/cli/src/lib/__fixtures__/question-commandcode.txt b/cli/src/lib/__fixtures__/question-commandcode.txt
new file mode 100644
index 000000000..87d86b924
--- /dev/null
+++ b/cli/src/lib/__fixtures__/question-commandcode.txt
@@ -0,0 +1,167 @@
+
+✻ Thought for 1 second [ctrl+o to expand]
+
+⠶ 8 cái chân (4 con × 2 chân).
+
+❯ Vậy năm con gà có bao nhiêu cái chân
+
+⠶ 10 cái chân (5 con × 2 chân).
+
+❯ Làm cho ta một cái game Mario đây
+
+✻ Thought for 1 second [ctrl+o to expand]
+
+⠶ Mình sẽ làm một game Mario đơn giản chạy được ngay trong terminal hoặc trình duyệt. Để mình xem thư mục hiện tại có gì trước.
+
+ LIST  [Agent-6]
+ └ Completed
+
+✻ Thought for 4 seconds [ctrl+o to expand]
+
+⠶ Thư mục trống, mình sẽ tạo một game Mario platformer chạy trong trình duyệt bằng một file HTML duy nhất.
+
+ TODOS  [2 items]
+☐ Đang tạo file index.html với game Mario platformer…
+☐ Kiểm tra và chạy thử game
+
+✻ Thought for 1 second [ctrl+o to expand]
+
+⠶ Mình sẽ tạo game Mario bằng Canvas với nhân vật, quái vật, coin, vật lý nhảy, và tính điểm.
+
+ WRITE  [index.html]
+ └ Completed
+
+◼ Ran 1 session start hook
+
+❯ code cho a game mario di
+
+✻ Thought for 1 second [ctrl+o to expand]
+
+⠶ Được, mình sẽ tạo lại file game Mario cho bạn.
+
+❯ Interrupted · What should Command Code do instead?
+
+
+Resume this session with:
+cmd --resume ae93cc89-0dff-452a-a875-33b1516bbc80
+^CMacbooks-MacBook-Pro-8:Agent-6 example$ harness cmd --yolo
+
+ ███████ ███████ ███████████ ███████████ ███████ ████████ ████
+ ███ ███ ██ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███████
+ ███ ██ ███ ███ ███ ███ ███ ███ ███ ███████ ███ ███ ███ ███
+ ███ ███ ██ ███ ███ ███ ███ ███ ███ ███ ███████ ███ ███ ███ ███
+ ███████ ███████ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███████
+
+
+# Command Code v1.6.0
+# models: deepseek-v4-flash · taste-1
+# ~/Working/Tmux/Agent-6
+
+◼ Ran 1 session start hook
+
+❯ code cho a game mario
+
+✻ Thought for 1 second [ctrl+o to expand]
+
+⠶ Để tôi xem thư mục hiện tại trước đã.
+
+ LIST  [Agent-6]
+ │ Found 1 items (1 dirs, 0 files)
+ │ Directories:
+ └  ... +1 lines [ctrl+o to expand]
+
+✻ Thought for 2 seconds [ctrl+o to expand]
+
+⠶ Thư mục trống, mình sẽ tạo một game Mario phong cách platformer hoàn chỉnh trong một file HTML duy nhất (canvas + JS thuần, không cần dependency).
+
+ WRITE  [index.html]
+ └ File created successfully at: /Users/example/Working/Tmux/Agent-6/index.html
+
+✻ Thought for 1 second [ctrl+o to expand]
+
+⠶ File đã tạo. Giờ tôi cần sửa vài lỗi: const bị gán lại (targetCam) và filter vào biến const (enemies, items).
+
+ EDIT  [index.html]
+ │ Edited /Users/example/Working/Tmux/Agent-6/index.html (1 replacement)
+ └  ... +10 lines [ctrl+o to expand]
+
+ EDIT  [index.html]
+ │ Edited /Users/example/Working/Tmux/Agent-6/index.html (1 replacement)
+ └  ... +8 lines [ctrl+o to expand]
+
+⠶ Giờ tôi mở game trong trình duyệt để kiểm tra xem nó chạy được không.
+
+ SHELL  [open index.html]
+ └ (no output)
+
+⠶ Đã tạo xong game Mario trong index.html và mở trong trình duyệt. Bấm vào cửa sổ game rồi chơi:
+
+ - ← → (hoặc A/D): di chuyển
+ - Space / ↑ (hoặc W): nhảy (giữ lâu để nhảy cao hơn)
+ - R: chơi lại
+
+ Game có 3 level, đất/đi bẫy, hộp ? đập ra xu, goomba có thể đạp để diệt, cờ vàng ở cuối level để qua màn. Nếu thấy gì cần chỉnh (độ khó, thêm item như nấm, âm thanh...) cứ nói nhé.
+
+❯ Theo đổi ý rồi cos cho game cờ cà rô đi
+
+✻ Thought for 30 seconds [ctrl+o to expand]
+
+⠶ Ok, bỏ Mario, làm game cờ caro (5 quân liên tiếp thắng) chơi được với máy hoặc 2 người trong cùng file index.html.
+
+ WRITE  [index.html]
+ └ The file /Users/example/Working/Tmux/Agent-6/index.html has been updated successfully.
+
+⠶ Mở lại game trong trình duyệt.
+
+ SHELL  [open index.html]
+ └ (no output)
+
+⠶ Xong, đã thay bằng game cờ caro trong index.html và mở trong trình duyệt:
+
+ - 🤖 Chơi với máy: bạn là X, đi trước; AI tính toán tấn công + chặn
+ - 👥 2 người chơi: cùng bàn bấm lần lượt
+ - 🔄 Chơi lại: reset ván cờ
+
+ Bàn 15×15, ai đủ 5 quân liên tiếp (ngang/dọc/chéo) thắng. AI có mức tương đối khá (chặn 3 liên tiếp, tấn công khi có cơ hội). Nếu muốn AI khó hơn (thuật toán minimax sâu hơn) hay bàn nhỏ hơn thì báo tôi nhé.
+
+ TASTE  Learned
+ └ Changes their mind mid-task and expects prior work to be fully discarded/replaced with the new request rather than merged or preserved (e.g., dropped a finished Mario game for a caro game in the same file) [Confidence 60%]
+ ]8;;file:///Users/example/Working/Tmux/Agent-6/.commandcode/taste/taste.md\taste.md]8;;\
+
+ TASTE  Learned
+ └ Likes browser-based games implemented as a single self-contained HTML file (canvas + vanilla JS, no dependencies) that runs by just opening the file [Confidence 90%]
+ ]8;;file:///Users/example/Working/Tmux/Agent-6/.commandcode/taste/game-dev/taste.md\game-dev/taste.md]8;;\
+
+ TASTE  Learned
+ └ Expects finished game projects to be opened automatically in the browser (e.g., `open index.html`) for verification [Confidence 80%]
+ ]8;;file:///Users/example/Working/Tmux/Agent-6/.commandcode/taste/game-dev/taste.md\game-dev/taste.md]8;;\
+
+ TASTE  Learned
+ └ Prefers game UI text and communication in Vietnamese, including in-game labels and instructions [Confidence 80%]
+ ]8;;file:///Users/example/Working/Tmux/Agent-6/.commandcode/taste/game-dev/taste.md\game-dev/taste.md]8;;\
+
+❯ Tao lại thay đổi ấy rồi việc cho tao game cầu vụ đi
+
+✻ Thought for 6 seconds [ctrl+o to expand]
+
+⠶ "cầu vụ" tôi đoán là cờ vua nhưng cũng có thể là game khác — để tôi hỏi nhanh cho đúng ý.
+
+ QUESTION  [User answered questions]
+ └  Processing…
+
+
+────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+● Loại game | ◯ Review
+
+"Cầu vụ" bạn muốn game gì?
+
+❯ 1. Cờ vua (Chess) (Recommended)
+  Game cờ vua 2 người hoặc chơi với máy, đủ luật: chiếu tướng, nhập thành, phong cấp.
+  2. Cầu vồng
+  Game chủ đề cầu vồng / màu sắc, kiểu giải đố hoặc arcade.
+  3. Cầu vượt
+  Game băng qua đường (kiểu Crossy Road / đường đông xe cộ).
+  4. Type something...
+
+
diff --git a/cli/src/lib/__fixtures__/question-devin-multi.txt b/cli/src/lib/__fixtures__/question-devin-multi.txt
new file mode 100644
index 000000000..31ea3de2f
--- /dev/null
+++ b/cli/src/lib/__fixtures__/question-devin-multi.txt
@@ -0,0 +1,105 @@
+
+❭ Giá eth mới nhất bây giờ là bao nhiêu
+
+❭ hi
+
+⏺ web_search(query="Ethereum ETH price today live")
+
+Giá Ethereum (ETH) mới nhất:
+
+CoinMarketCap: $1,871.91 USD (+1.51% trong 24h) CoinGecko: $1,872.00 USD (+1.50% trong 24h)
+
+Tóm tắt:
+
+ • Giá hiện tại: ~$1,872 USD
+ • Thay đổi 24h: Tăng ~1.5%
+ • Market cap: ~$225.9 tỷ USD
+ • Khối lượng giao dịch 24h: ~$5.3-5.8 tỷ USD
+ • Xu hướng 7 ngày: Giảm ~3.9%
+
+Free plan, use /upgrade to access better models · 100% remaining (resets in 28m)
+
+❭ hỏi tao tao thích màu gì và đưa ra 2 lựa chọn xanh, đỏ để tao chọn đi
+
+⏺ Asked user Bạn thích màu gì?
+ └ Xanh
+
+Bạn chọn màu Xanh! 👍
+
+Màu xanh rất đẹp và mang lại cảm giác thư giãn, tươi mát. Bạn thích màu xanh dương hay xanh lá hơn?
+
+❭ hỏi tao tao thích màu gì và đưa ra 2 lựa chọn xanh, đỏ và nhiều step lựa chọn để tao chọn đi
+
+⏺ Asked user Bạn thích màu gì? (có thể chọn nhiều màu)
+ │ Tool 'ask_user_question' validation failed: Question 1 must have 2-4 options, got 5.
+ ✗ Failed
+
+⏺ Asked user Bạn thích màu gì? (có thể chọn nhiều màu)
+ │ Tool execution was rejected: The user wants to clarify these questions.
+ │ This means they may have additional information, context or questions for you.
+ │ Take their response into account and then reformulate the questions if appropriate.
+ │ Start by asking them what they would like to clarify.
+ │ Questions asked:
+ │ - "Bạn thích màu gì? (có thể chọn nhiều màu)"
+ ✗  (No answer provided)
+
+Bạn muốn tôi điều chỉnh câu hỏi như thế nào? Tôi có thể:
+
+ 1. Giữ 4 lựa chọn: Xanh, Đỏ, Vàng, Tím (cho phép chọn nhiều)
+ 2. Chỉ 2 lựa chọn: Xanh, Đỏ (cho phép chọn nhiều)
+ 3. Hoặc bạn có ý tưởng khác?
+
+Bạn thích cách nào?
+
+❭ cho tao kieu lụa chọn size -> màu sắc đi
+
+⏺ Asked user 2 questions
+ │ Size: S
+ └ Màu sắc: Xanh
+
+Bạn đã chọn:
+
+ • Size: S
+ • Màu sắc: Xanh
+
+Lựa chọn rất đẹp! Size S vừa vặn và màu xanh mang lại cảm giác tươi mát. Bạn cần thêm thông tin gì không?
+
+❭ cho tao kieu lụa chọn size -> màu sắc đi
+
+⏺ Asked user 2 questions
+ │ Size: S
+ └ Màu sắc: Xanh
+
+Bạn đã chọn:
+
+ • Size: S
+ • Màu sắc: Xanh
+
+Lựa chọn của bạn: Size S màu xanh! 👍
+
+❭ hoi tao thich mau gi, 2 lua chon: Xanh, Do
+
+⏺ Asked user Bạn thích màu gì?
+ └ Đỏ
+
+Bạn chọn màu Đỏ! 🔴
+
+Màu đỏ rất nổi bật và mang lại cảm giác năng động, mạnh mẽ.
+
+✱ Did you know
+ Type while the agent works to queue messages; press Enter on an empty input to send them now
+
+❭ hoi tao thich mau nao, cho chon NHIEU mau: Xanh, Do, Vang
+
+── Màu yêu thích ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+ Bạn thích màu nào? (có thể chọn nhiều màu) (multi-select)
+ □ 1 Xanh
+ Màu xanh dương hoặc xanh lá
+ □ 2 Đỏ
+ Màu đỏ tươi
+ □ 3 Vàng
+ Màu vàng tươi sáng
+ □ 4 Other (type your own)
+─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+↑↓ navigate · ␣ toggle · ↵ select · e select+type · ? help me out · esc cancel
+? Not ready to answer, help me out!
diff --git a/cli/src/lib/__fixtures__/question-devin.txt b/cli/src/lib/__fixtures__/question-devin.txt
new file mode 100644
index 000000000..ca7cc99a4
--- /dev/null
+++ b/cli/src/lib/__fixtures__/question-devin.txt
@@ -0,0 +1,105 @@
+
+Bạn cần giúp gì không?
+
+❭ hi
+
+Xin chào! 👋
+
+Bạn cần giúp gì không?
+
+❭ hi
+
+Xin chào! 👋
+
+Bạn cần giúp gì không?
+
+❭ Giá eth mới nhất bây giờ là bao nhiêu
+
+❭ hi
+
+⏺ web_search(query="Ethereum ETH price today live")
+
+Giá Ethereum (ETH) mới nhất:
+
+CoinMarketCap: $1,871.91 USD (+1.51% trong 24h) CoinGecko: $1,872.00 USD (+1.50% trong 24h)
+
+Tóm tắt:
+
+ • Giá hiện tại: ~$1,872 USD
+ • Thay đổi 24h: Tăng ~1.5%
+ • Market cap: ~$225.9 tỷ USD
+ • Khối lượng giao dịch 24h: ~$5.3-5.8 tỷ USD
+ • Xu hướng 7 ngày: Giảm ~3.9%
+
+Free plan, use /upgrade to access better models · 100% remaining (resets in 28m)
+
+❭ hỏi tao tao thích màu gì và đưa ra 2 lựa chọn xanh, đỏ để tao chọn đi
+
+⏺ Asked user Bạn thích màu gì?
+ └ Xanh
+
+Bạn chọn màu Xanh! 👍
+
+Màu xanh rất đẹp và mang lại cảm giác thư giãn, tươi mát. Bạn thích màu xanh dương hay xanh lá hơn?
+
+❭ hỏi tao tao thích màu gì và đưa ra 2 lựa chọn xanh, đỏ và nhiều step lựa chọn để tao chọn đi
+
+⏺ Asked user Bạn thích màu gì? (có thể chọn nhiều màu)
+ │ Tool 'ask_user_question' validation failed: Question 1 must have 2-4 options, got 5.
+ ✗ Failed
+
+⏺ Asked user Bạn thích màu gì? (có thể chọn nhiều màu)
+ │ Tool execution was rejected: The user wants to clarify these questions.
+ │ This means they may have additional information, context or questions for you.
+ │ Take their response into account and then reformulate the questions if appropriate.
+ │ Start by asking them what they would like to clarify.
+ │ Questions asked:
+ │ - "Bạn thích màu gì? (có thể chọn nhiều màu)"
+ ✗  (No answer provided)
+
+Bạn muốn tôi điều chỉnh câu hỏi như thế nào? Tôi có thể:
+
+ 1. Giữ 4 lựa chọn: Xanh, Đỏ, Vàng, Tím (cho phép chọn nhiều)
+ 2. Chỉ 2 lựa chọn: Xanh, Đỏ (cho phép chọn nhiều)
+ 3. Hoặc bạn có ý tưởng khác?
+
+Bạn thích cách nào?
+
+❭ cho tao kieu lụa chọn size -> màu sắc đi
+
+⏺ Asked user 2 questions
+ │ Size: S
+ └ Màu sắc: Xanh
+
+Bạn đã chọn:
+
+ • Size: S
+ • Màu sắc: Xanh
+
+Lựa chọn rất đẹp! Size S vừa vặn và màu xanh mang lại cảm giác tươi mát. Bạn cần thêm thông tin gì không?
+
+❭ cho tao kieu lụa chọn size -> màu sắc đi
+
+⏺ Asked user 2 questions
+ │ Size: S
+ └ Màu sắc: Xanh
+
+Bạn đã chọn:
+
+ • Size: S
+ • Màu sắc: Xanh
+
+Lựa chọn của bạn: Size S màu xanh! 👍
+
+❭ hoi tao thich mau gi, 2 lua chon: Xanh, Do
+
+── Màu yêu thích ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+ Bạn thích màu gì?
+ ❭ 1 Xanh
+ Màu xanh dương hoặc xanh lá
+ · 2 Đỏ
+ Màu đỏ tươi
+ · Other (type your own)
+─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+↑↓ navigate · ↵ select · e select+type · ? help me out · esc cancel
+? Not ready to answer, help me out!
diff --git a/cli/src/lib/__fixtures__/question-hermes.txt b/cli/src/lib/__fixtures__/question-hermes.txt
new file mode 100644
index 000000000..fc944db70
--- /dev/null
+++ b/cli/src/lib/__fixtures__/question-hermes.txt
@@ -0,0 +1,93 @@
+│  ◆ Hermes: Hey! What can I help you with today? │
+│ │
+╰───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
+ ⚕ minimax-m3 │ ctx -- │ [░░░░░░░░░░] -- │ 19h 44m │ ⏲ 0s │ ⚠ YOLO
+─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+❯
+─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+❯
+╭────────────────────────────────────────────────────────────────────────── Previous Conversation ───────────────────────────────────────────────────────────────────────────╮
+│  ● You: hi │
+│  ◆ Hermes: Hey! What can I help you with today? │
+│ │
+╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
+ ⚕ minimax-m3 │ ctx -- │ [░░░░░░░░░░] -- │ 19h 44m │ ⏲ 0s │ ⚠ YOLO
+──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+❯
+──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+❯
+╭─────────────────────────────────────────────────────────────────────────── Previous Conversation ────────────────────────────────────────────────────────────────────────────╮
+│  ● You: hi │
+│  ◆ Hermes: Hey! What can I help you with today? │
+│ │
+╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
+ ⚕ minimax-m3 │ ctx -- │ [░░░░░░░░░░] -- │ 20h │ ⏲ 0s │ ⚠ YOLO
+────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+❯
+────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+❯
+╭───────────────────────────────────────────────────────────────────────── Previous Conversation ──────────────────────────────────────────────────────────────────────────╮
+│  ● You: hi │
+│  ◆ Hermes: Hey! What can I help you with today? │
+│ │
+╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
+ ⚕ minimax-m3 │ ctx -- │ [░░░░░░░░░░] -- │ 20h │ ⏲ 0s │ ⚠ YOLO
+────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+❯
+────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+❯
+╭───────────────────────────────────────────────────────────────────────────────────────────────── Previous Conversation ─────────────────────────────────────────────────────────────────────────────────────────────────╮
+│  ● You: hi │
+│  ◆ Hermes: Hey! What can I help you with today? │
+│ │
+╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
+ ⚕ minimax-m3 │ ctx -- │ [░░░░░░░░░░] -- │ 1.2d │ ⏲ 0s │ ⚠ YOLO
+───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+❯
+───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+❯
+╭──────────────────────────────────────────────────────────────────────────── Previous Conversation ─────────────────────────────────────────────────────────────────────────────╮
+│  ● You: hi │
+│  ◆ Hermes: Hey! What can I help you with today? │
+│ │
+╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
+
+────────────────────────────────────────
+● dung tool clarify de hoi tao: mau yeu thich, 2 lua chon Xanh va Do
+Initializing agent...
+
+────────────────────────────────────────
+
+? Clarify: Màu yêu thích của bạn là gì? → Đỏ
+ ┊ ⚡ clarify Màu yêu thích của bạn là gì? 45.9s
+ (tip) That tool ran for a while. Use /verbose to cycle tool-progress display modes (all -> new -> off -> verbose). This tip only shows once.
+
+╭─ ⚕ Hermes ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
+ Bạn chọn Đỏ! 🔴
+
+ Đỏ — màu của năng lượng, đam mê và sự táo bạo. Lựa chọn tuyệt vời!
+╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
+
+────────────────────────────────────────
+● dung tool clarify hoi tao: chon size, 2 lua chon S va M
+────────────────────────────────────────
+
+╭─ Hermes needs your input ──────────────────────╮
+│ │
+│ Bạn muốn chọn size nào?  │
+│ │
+│ ❯ 1. S  │
+│  2. M  │
+│  3. Other (type your answer)  │
+│ │
+╰────────────────────────────────────────────────╯
+
+ ❓ Bạn muốn chọn size nào? ( 30.5s · ↓ 63 tok)
+ ↑/↓ to select, Enter to confirm (89s)
+ ⚕ minimax-m3 │ 18K/1M │ [░░░░░░░░░░] 2% │ 1.3d │ ⏱ 31s │ ⚠ YOLO
+──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+? ❯
+──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+
+
diff --git a/cli/src/lib/__fixtures__/question-multi.txt b/cli/src/lib/__fixtures__/question-multi.txt
new file mode 100644
index 000000000..338243a38
--- /dev/null
+++ b/cli/src/lib/__fixtures__/question-multi.txt
@@ -0,0 +1,45 @@
+
+⏺ You picked durian (via the custom "Other" option, not Apple or Mango).
+
+✻ Worked for 5s
+
+❯ Ask me two questions in ONE AskUserQuestion call: (1) which colors? multiSelect true, options Red, Blue, Green. (2)
+ which size? single, options S, M. Nothing else.
+
+⏺ User answered Claude's questions:
+ ⎿  · Which colors do you like? → Green, Red
+ · Which size do you want? → M
+
+⏺ Colors: Green and Red. Size: M.
+
+✻ Cooked for 4s
+
+❯ Use AskUserQuestion: pick a drink? options Tea, Coffee. Nothing else.
+
+⏺ User answered Claude's questions:
+ ⎿  · Which drink would you like? → Tea
+
+⏺ You picked Tea.
+
+✻ Churned for 4s
+
+❯ Use AskUserQuestion ONE question multiSelect true: which toppings? options Cheese, Ham, Basil. Nothing else.
+────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+Planning: /Users/example/.claude/plans/use-the-askuserquestion-tool-async-zephyr.md
+────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+← ☐ Toppings ✔ Submit →
+
+Which toppings do you want?
+
+❯ 1. [ ] Cheese
+ Melted and savory.
+ 2. [ ] Ham
+ Salty cured meat.
+ 3. [ ] Basil
+ Fresh herb, aromatic.
+ 4. [ ] Type something
+ Submit
+────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+ 5. Chat about this
+
+Enter to select · ↑/↓ to navigate · Esc to cancel
diff --git a/cli/src/lib/__fixtures__/question-opencode-review.txt b/cli/src/lib/__fixtures__/question-opencode-review.txt
new file mode 100644
index 000000000..e0e065609
--- /dev/null
+++ b/cli/src/lib/__fixtures__/question-opencode-review.txt
@@ -0,0 +1,30 @@
+ ┃ 
+
+ + Thought: 47ms
+
+ Bạn chọn size M.
+
+ ▣  Build · MiniMax M3 (vibe) · 1m 6s
+
+ ┃ 
+ ┃ hoi tao 2 cau: cau 1 chon mau Xanh/Do (chon nhieu duoc), cau 2 chon size S/M 
+ ┃ 
+
+ + Thought: 373ms
+
+ → Asked 2 questions
+
+ ▣  Build · MiniMax M3 (vibe)
+
+ ┃ 
+ ┃ Chọn màu Chọn size  Confirm  
+ ┃ 
+ ┃ Review 
+ ┃ 
+ ┃ Chọn màu: Xanh 
+ ┃ 
+ ┃ Chọn size: M 
+ ┃ 
+ ┃ ⇆ tab enter submit esc dismiss 
+ ┃ 
+
diff --git a/cli/src/lib/__fixtures__/question-opencode.txt b/cli/src/lib/__fixtures__/question-opencode.txt
new file mode 100644
index 000000000..e06e01213
--- /dev/null
+++ b/cli/src/lib/__fixtures__/question-opencode.txt
@@ -0,0 +1,46 @@
+
+ 
+ ▣  Build · MiniMax M3 (vibe) · 37.4s  Greeting
+ 
+ ┃   Context
+ ┃ dung tool askQuestion de hoi tao: mau yeu thich, 2 lua chon Xanh/Do. Bat buoc dung tool, khong tra loi   26,685 tokens
+ ┃  bang text   5% used
+ ┃   $0.00 spent
+ 
+ + Thought: 477ms  LSP
+  LSPs are disabled
+ ┃  
+ ┃ # Questions  
+ ┃  
+ ┃ Màu yêu thích của bạn là gì?  
+ ┃ Xanh  
+ ┃  
+ 
+ + Thought: 60ms 
+ 
+ Bạn chọn màu Xanh. 
+ 
+ ▣  Build · MiniMax M3 (vibe) · 17.4s 
+ 
+ ┃  
+ ┃ dung tool question hoi tao: chon size, 2 lua chon S va M, moi cai co mo ta  
+ ┃  
+ 
+ + Thought: 426ms 
+ 
+ → Asked 1 question 
+ 
+ ▣  Build · MiniMax M3 (vibe) 
+ 
+ ┃  
+ ┃ Bạn muốn chọn size nào?  
+ ┃  
+ ┃ 1. Size S  
+ ┃ Size nhỏ, phù hợp người có thể trạng nhỏ/vừa  
+ ┃ 2. Size M  
+ ┃ Size vừa, phù hợp đa số thể trạng  
+ ┃ 3. Type your own answer  
+ ┃   ~/Work/ai-workers/opencode-agent1
+ ┃ ↑↓ select enter submit esc dismiss  
+ ┃   • OpenCode 1.18.11
+ 
diff --git a/cli/src/lib/__fixtures__/question-review.txt b/cli/src/lib/__fixtures__/question-review.txt
new file mode 100644
index 000000000..c6ebaaab6
--- /dev/null
+++ b/cli/src/lib/__fixtures__/question-review.txt
@@ -0,0 +1,45 @@
+
+⏺ You picked durian (via the custom "Other" option, not Apple or Mango).
+
+✻ Worked for 5s
+
+❯ Ask me two questions in ONE AskUserQuestion call: (1) which colors? multiSelect true, options Red, Blue, Green. (2)
+ which size? single, options S, M. Nothing else.
+
+⏺ User answered Claude's questions:
+ ⎿  · Which colors do you like? → Green, Red
+ · Which size do you want? → M
+
+⏺ Colors: Green and Red. Size: M.
+
+✻ Cooked for 4s
+
+❯ Use AskUserQuestion: pick a drink? options Tea, Coffee. Nothing else.
+
+⏺ User answered Claude's questions:
+ ⎿  · Which drink would you like? → Tea
+
+⏺ You picked Tea.
+
+✻ Churned for 4s
+
+❯ Use AskUserQuestion ONE question multiSelect true: which toppings? options Cheese, Ham, Basil. Nothing else.
+
+────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+← ☒ Toppings ✔ Submit →
+
+Review your answers
+
+ ● Which toppings do you want?
+ → Cheese, Basil
+
+Ready to submit your answers?
+
+❯ 1. Submit answers
+ 2. Cancel
+
+
+
+
+
+
diff --git a/cli/src/lib/__fixtures__/question-single.txt b/cli/src/lib/__fixtures__/question-single.txt
new file mode 100644
index 000000000..4013f03c6
--- /dev/null
+++ b/cli/src/lib/__fixtures__/question-single.txt
@@ -0,0 +1,45 @@
+
+⏺ User answered Claude's questions:
+ ⎿  · Which color do you like? → Yellow
+
+⏺ You picked Yellow.
+
+✻ Sautéed for 4s
+
+❯ Again: use AskUserQuestion to ask which fruit? options Apple, Mango. Nothing else.
+
+⏺ User answered Claude's questions:
+ ⎿  · Which fruit do you like? → durian please
+
+⏺ You picked durian (via the custom "Other" option, not Apple or Mango).
+
+✻ Worked for 5s
+
+❯ Ask me two questions in ONE AskUserQuestion call: (1) which colors? multiSelect true, options Red, Blue, Green. (2) 
+ which size? single, options S, M. Nothing else.
+
+⏺ User answered Claude's questions:
+ ⎿  · Which colors do you like? → Green, Red
+ · Which size do you want? → M
+
+⏺ Colors: Green and Red. Size: M.
+
+✻ Cooked for 4s
+
+❯ Use AskUserQuestion: pick a drink? options Tea, Coffee. Nothing else.
+────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+Planning: ]8;id=125y5xl;file:///Users/example/.claude/plans/use-the-askuserquestion-tool-async-zephyr.md\/Users/example/.claude/plans/use-the-askuserquestion-tool-async-zephyr.md]8;;\
+────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+ ☐ Drink 
+
+Which drink would you like?
+
+❯ 1. Tea
+ Lighter, steeped leaves.
+ 2. Coffee
+ Stronger, roasted beans.
+ 3. Type something.
+────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+ 4. Chat about this
+
+Enter to select · ↑/↓ to navigate · Esc to cancel
diff --git a/cli/src/lib/__fixtures__/question-tabs.txt b/cli/src/lib/__fixtures__/question-tabs.txt
new file mode 100644
index 000000000..b32af6f2f
--- /dev/null
+++ b/cli/src/lib/__fixtures__/question-tabs.txt
@@ -0,0 +1,45 @@
+│ /…/scratchpad/qtest │ │
+╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
+
+ Tackle your toughest work with Opus 5. Switch anytime with /model.
+
+❯ Use the AskUserQuestion tool right now to ask me: which color do you like? options Red, Yellow, Orange. Do nothing
+ else.
+
+⏺ User answered Claude's questions:
+ ⎿  · Which color do you like? → Yellow
+
+⏺ You picked Yellow.
+
+✻ Sautéed for 4s
+
+❯ Again: use AskUserQuestion to ask which fruit? options Apple, Mango. Nothing else.
+
+⏺ User answered Claude's questions:
+ ⎿  · Which fruit do you like? → durian please
+
+⏺ You picked durian (via the custom "Other" option, not Apple or Mango).
+
+✻ Worked for 5s
+
+❯ Ask me two questions in ONE AskUserQuestion call: (1) which colors? multiSelect true, options Red, Blue, Green. (2)
+ which size? single, options S, M. Nothing else.
+────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+Planning: /Users/example/.claude/plans/use-the-askuserquestion-tool-async-zephyr.md
+────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+← ☐ Colors ☐ Size ✔ Submit →
+
+Which colors do you like?
+
+❯ 1. [ ] Red
+ A warm, bold color.
+ 2. [ ] Blue
+ A cool, calm color.
+ 3. [ ] Green
+ A fresh, natural color.
+ 4. [ ] Type something
+ Next
+────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+ 5. Chat about this
+
+Enter to select · Tab/Arrow keys to navigate · Esc to cancel
diff --git a/cli/src/lib/__fixtures__/transcript-async-subagents.jsonl b/cli/src/lib/__fixtures__/transcript-async-subagents.jsonl
new file mode 100644
index 000000000..0d27f8eb7
--- /dev/null
+++ b/cli/src/lib/__fixtures__/transcript-async-subagents.jsonl
@@ -0,0 +1,14 @@
+{"parentUuid":"b7f10ebf-4452-45d0-ab43-0b53cef268aa","isSidechain":false,"promptId":"88091fa0-6988-4f62-901a-c24322706230","type":"user","message":{"role":"user","content":"Chạy 3 sub-agent SONG SONG (launch cả 3 cùng một lượt), mỗi agent một việc độc lập rồi báo cáo lại:\n- Agent 1: Report giá coin BTC\n- Agent 2: Report giá coin ETH\n- Agent 3: Report giá coin BNB"},"uuid":"1fb3dd23-973c-4021-8ab4-e7b4ba90dd72","timestamp":"2026-08-05T03:03:13.339Z","permissionMode":"bypassPermissions","origin":{"kind":"human"},"promptSource":"typed","userType":"external","entrypoint":"cli","cwd":"/Users/example/Work/ai-workers/opencode-agent1","sessionId":"b03cad16-2cf0-43a3-9374-996d0653bb87","version":"2.1.222","gitBranch":"HEAD","slug":"code-landing-page-ve-woolly-cosmos"}
+{"parentUuid":"3bb6e104-3d90-4f7e-99d1-738dd527a241","isSidechain":false,"message":{"model":"claude-sonnet-5","id":"msg_011CdirkPiUgkobR2jeeVXAT","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_0151gJRdan4nRckLW37Woy5N","name":"Agent","input":{"description":"Report giá BTC","prompt":"Tìm giá hiện tại của Bitcoin (BTC) bằng WebSearch. Báo cáo giá USD hiện tại, thay đổi % trong 24h, và vốn hóa thị trường nếu có. Trả lời ngắn gọn bằng tiếng Việt kèm nguồn.","run_in_background":true},"caller":{"type":"direct"}}],"stop_reason":"tool_use","stop_sequence":null,"stop_details":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":329,"cache_read_input_tokens":96082,"output_tokens":611,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":329,"ephemeral_5m_input_tokens":0},"inference_geo":"not_available","iterations":[{"input_tokens":2,"output_tokens":611,"cache_read_input_tokens":96082,"cache_creation_input_tokens":329,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":329},"type":"message"}],"speed":"standard"},"diagnostics":null},"requestId":"req_011CdirkLG7tiNdJXwVBoq2U","type":"assistant","uuid":"6d806235-1350-4af6-be97-0e884e58441d","timestamp":"2026-08-05T03:03:17.355Z","effort":"high","session_id":"b03cad16-2cf0-43a3-9374-996d0653bb87","userType":"external","entrypoint":"cli","cwd":"/Users/example/Work/ai-workers/opencode-agent1","sessionId":"b03cad16-2cf0-43a3-9374-996d0653bb87","version":"2.1.222","gitBranch":"HEAD","slug":"code-landing-page-ve-woolly-cosmos"}
+{"parentUuid":"6d806235-1350-4af6-be97-0e884e58441d","isSidechain":false,"promptId":"88091fa0-6988-4f62-901a-c24322706230","type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_0151gJRdan4nRckLW37Woy5N","type":"tool_result","content":[{"type":"text","text":"Async agent launched successfully. (This tool result is internal metadata — never quote or paste any part of it, including the agentId below, into a user-facing reply.)\nagentId: a523fae36e503c7a1 (internal ID - do not mention to user. Use SendMessage with to: 'a523fae36e503c7a1', summary: '<5-10 word recap>' to continue this agent.)\nThe agent is working in the background. You will be notified automatically when it completes. You know nothing about its results until that notification arrives — do not report, assume, or predict them; continue other work or respond to the user in the meantime.\nDo not duplicate this agent's work — avoid working with the same files or topics it is using.\noutput_file: /private/tmp/claude-502/-Users-example-Work-ai-workers-opencode-agent1/b03cad16-2cf0-43a3-9374-996d0653bb87/tasks/a523fae36e503c7a1.output\nDo NOT Read or tail this file via the shell tool — it is the full subagent JSONL transcript and reading it will overflow your context. If the user asks for progress, say the agent is still running; you'll get a completion notification."}]}]},"uuid":"6ec2acc8-7928-48bd-a017-25a40208df3f","timestamp":"2026-08-05T03:03:17.368Z","toolUseResult":{"isAsync":true,"status":"async_launched","agentId":"a523fae36e503c7a1","description":"Report giá BTC","resolvedModel":"claude-sonnet-5","prompt":"Tìm giá hiện tại của Bitcoin (BTC) bằng WebSearch. Báo cáo giá USD hiện tại, thay đổi % trong 24h, và vốn hóa thị trường nếu có. Trả lời ngắn gọn bằng tiếng Việt kèm nguồn.","outputFile":"/private/tmp/claude-502/-Users-example-Work-ai-workers-opencode-agent1/b03cad16-2cf0-43a3-9374-996d0653bb87/tasks/a523fae36e503c7a1.output","canReadOutputFile":true},"sourceToolAssistantUUID":"6d806235-1350-4af6-be97-0e884e58441d","session_id":"b03cad16-2cf0-43a3-9374-996d0653bb87","userType":"external","entrypoint":"cli","cwd":"/Users/example/Work/ai-workers/opencode-agent1","sessionId":"b03cad16-2cf0-43a3-9374-996d0653bb87","version":"2.1.222","gitBranch":"HEAD","slug":"code-landing-page-ve-woolly-cosmos"}
+{"parentUuid":"6ec2acc8-7928-48bd-a017-25a40208df3f","isSidechain":false,"message":{"model":"claude-sonnet-5","id":"msg_011CdirkPiUgkobR2jeeVXAT","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_012D8sB1E69zHCNdp9tjiF15","name":"Agent","input":{"description":"Report giá ETH","prompt":"Tìm giá hiện tại của Ethereum (ETH) bằng WebSearch. Báo cáo giá USD hiện tại, thay đổi % trong 24h, và vốn hóa thị trường nếu có. Trả lời ngắn gọn bằng tiếng Việt kèm nguồn.","run_in_background":true},"caller":{"type":"direct"}}],"stop_reason":"tool_use","stop_sequence":null,"stop_details":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":329,"cache_read_input_tokens":96082,"output_tokens":611,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":329,"ephemeral_5m_input_tokens":0},"inference_geo":"not_available","iterations":[{"input_tokens":2,"output_tokens":611,"cache_read_input_tokens":96082,"cache_creation_input_tokens":329,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":329},"type":"message"}],"speed":"standard"},"diagnostics":null},"requestId":"req_011CdirkLG7tiNdJXwVBoq2U","type":"assistant","uuid":"afa094fe-038c-45d2-9c6c-848996d18038","timestamp":"2026-08-05T03:03:18.386Z","effort":"high","session_id":"b03cad16-2cf0-43a3-9374-996d0653bb87","userType":"external","entrypoint":"cli","cwd":"/Users/example/Work/ai-workers/opencode-agent1","sessionId":"b03cad16-2cf0-43a3-9374-996d0653bb87","version":"2.1.222","gitBranch":"HEAD","slug":"code-landing-page-ve-woolly-cosmos"}
+{"parentUuid":"afa094fe-038c-45d2-9c6c-848996d18038","isSidechain":false,"promptId":"88091fa0-6988-4f62-901a-c24322706230","type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_012D8sB1E69zHCNdp9tjiF15","type":"tool_result","content":[{"type":"text","text":"Async agent launched successfully. (This tool result is internal metadata — never quote or paste any part of it, including the agentId below, into a user-facing reply.)\nagentId: a316a821c79b054b9 (internal ID - do not mention to user. Use SendMessage with to: 'a316a821c79b054b9', summary: '<5-10 word recap>' to continue this agent.)\nThe agent is working in the background. You will be notified automatically when it completes. You know nothing about its results until that notification arrives — do not report, assume, or predict them; continue other work or respond to the user in the meantime.\nDo not duplicate this agent's work — avoid working with the same files or topics it is using.\noutput_file: /private/tmp/claude-502/-Users-example-Work-ai-workers-opencode-agent1/b03cad16-2cf0-43a3-9374-996d0653bb87/tasks/a316a821c79b054b9.output\nDo NOT Read or tail this file via the shell tool — it is the full subagent JSONL transcript and reading it will overflow your context. If the user asks for progress, say the agent is still running; you'll get a completion notification."}]}]},"uuid":"be3f8b06-3806-456a-89f3-3c52abff964b","timestamp":"2026-08-05T03:03:18.393Z","toolUseResult":{"isAsync":true,"status":"async_launched","agentId":"a316a821c79b054b9","description":"Report giá ETH","resolvedModel":"claude-sonnet-5","prompt":"Tìm giá hiện tại của Ethereum (ETH) bằng WebSearch. Báo cáo giá USD hiện tại, thay đổi % trong 24h, và vốn hóa thị trường nếu có. Trả lời ngắn gọn bằng tiếng Việt kèm nguồn.","outputFile":"/private/tmp/claude-502/-Users-example-Work-ai-workers-opencode-agent1/b03cad16-2cf0-43a3-9374-996d0653bb87/tasks/a316a821c79b054b9.output","canReadOutputFile":true},"sourceToolAssistantUUID":"afa094fe-038c-45d2-9c6c-848996d18038","session_id":"b03cad16-2cf0-43a3-9374-996d0653bb87","userType":"external","entrypoint":"cli","cwd":"/Users/example/Work/ai-workers/opencode-agent1","sessionId":"b03cad16-2cf0-43a3-9374-996d0653bb87","version":"2.1.222","gitBranch":"HEAD","slug":"code-landing-page-ve-woolly-cosmos"}
+{"parentUuid":"be3f8b06-3806-456a-89f3-3c52abff964b","isSidechain":false,"message":{"model":"claude-sonnet-5","id":"msg_011CdirkPiUgkobR2jeeVXAT","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_018wkW4V5DWLAQxEHe9Mty56","name":"Agent","input":{"description":"Report giá BNB","prompt":"Tìm giá hiện tại của BNB (Binance Coin) bằng WebSearch. Báo cáo giá USD hiện tại, thay đổi % trong 24h, và vốn hóa thị trường nếu có. Trả lời ngắn gọn bằng tiếng Việt kèm nguồn.","run_in_background":true},"caller":{"type":"direct"}}],"stop_reason":"tool_use","stop_sequence":null,"stop_details":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":329,"cache_read_input_tokens":96082,"output_tokens":611,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":329,"ephemeral_5m_input_tokens":0},"inference_geo":"not_available","iterations":[{"input_tokens":2,"output_tokens":611,"cache_read_input_tokens":96082,"cache_creation_input_tokens":329,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":329},"type":"message"}],"speed":"standard"},"diagnostics":null},"requestId":"req_011CdirkLG7tiNdJXwVBoq2U","type":"assistant","uuid":"62496664-6f92-4276-bd22-0da9b7e2c0a5","timestamp":"2026-08-05T03:03:19.357Z","effort":"high","session_id":"b03cad16-2cf0-43a3-9374-996d0653bb87","userType":"external","entrypoint":"cli","cwd":"/Users/example/Work/ai-workers/opencode-agent1","sessionId":"b03cad16-2cf0-43a3-9374-996d0653bb87","version":"2.1.222","gitBranch":"HEAD","slug":"code-landing-page-ve-woolly-cosmos"}
+{"parentUuid":"62496664-6f92-4276-bd22-0da9b7e2c0a5","isSidechain":false,"promptId":"88091fa0-6988-4f62-901a-c24322706230","type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_018wkW4V5DWLAQxEHe9Mty56","type":"tool_result","content":[{"type":"text","text":"Async agent launched successfully. (This tool result is internal metadata — never quote or paste any part of it, including the agentId below, into a user-facing reply.)\nagentId: a2c64c3994f29b798 (internal ID - do not mention to user. Use SendMessage with to: 'a2c64c3994f29b798', summary: '<5-10 word recap>' to continue this agent.)\nThe agent is working in the background. You will be notified automatically when it completes. You know nothing about its results until that notification arrives — do not report, assume, or predict them; continue other work or respond to the user in the meantime.\nDo not duplicate this agent's work — avoid working with the same files or topics it is using.\noutput_file: /private/tmp/claude-502/-Users-example-Work-ai-workers-opencode-agent1/b03cad16-2cf0-43a3-9374-996d0653bb87/tasks/a2c64c3994f29b798.output\nDo NOT Read or tail this file via the shell tool — it is the full subagent JSONL transcript and reading it will overflow your context. If the user asks for progress, say the agent is still running; you'll get a completion notification."}]}]},"uuid":"92c47b08-e3e0-433d-b937-900ff198112c","timestamp":"2026-08-05T03:03:19.365Z","toolUseResult":{"isAsync":true,"status":"async_launched","agentId":"a2c64c3994f29b798","description":"Report giá BNB","resolvedModel":"claude-sonnet-5","prompt":"Tìm giá hiện tại của BNB (Binance Coin) bằng WebSearch. Báo cáo giá USD hiện tại, thay đổi % trong 24h, và vốn hóa thị trường nếu có. Trả lời ngắn gọn bằng tiếng Việt kèm nguồn.","outputFile":"/private/tmp/claude-502/-Users-example-Work-ai-workers-opencode-agent1/b03cad16-2cf0-43a3-9374-996d0653bb87/tasks/a2c64c3994f29b798.output","canReadOutputFile":true},"sourceToolAssistantUUID":"62496664-6f92-4276-bd22-0da9b7e2c0a5","session_id":"b03cad16-2cf0-43a3-9374-996d0653bb87","userType":"external","entrypoint":"cli","cwd":"/Users/example/Work/ai-workers/opencode-agent1","sessionId":"b03cad16-2cf0-43a3-9374-996d0653bb87","version":"2.1.222","gitBranch":"HEAD","slug":"code-landing-page-ve-woolly-cosmos"}
+{"parentUuid":"92c47b08-e3e0-433d-b937-900ff198112c","isSidechain":false,"message":{"model":"claude-sonnet-5","id":"msg_011CdirkoEb5qoKyJunoTZ3A","type":"message","role":"assistant","content":[{"type":"text","text":"Đã spawn 3 sub-agent song song cho BTC, ETH, BNB. Sẽ báo kết quả khi cả ba hoàn thành."}],"stop_reason":"end_turn","stop_sequence":null,"stop_details":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":1835,"cache_read_input_tokens":96411,"output_tokens":56,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":1835,"ephemeral_5m_input_tokens":0},"inference_geo":"not_available","iterations":[{"input_tokens":2,"output_tokens":56,"cache_read_input_tokens":96411,"cache_creation_input_tokens":1835,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":1835},"type":"message"}],"speed":"standard"},"diagnostics":null},"requestId":"req_011Cdirkmasap34QVbNSxMtX","type":"assistant","uuid":"15e0b381-5691-409a-979f-0aa1f349a4d2","timestamp":"2026-08-05T03:03:21.711Z","effort":"high","session_id":"b03cad16-2cf0-43a3-9374-996d0653bb87","userType":"external","entrypoint":"cli","cwd":"/Users/example/Work/ai-workers/opencode-agent1","sessionId":"b03cad16-2cf0-43a3-9374-996d0653bb87","version":"2.1.222","gitBranch":"HEAD","slug":"code-landing-page-ve-woolly-cosmos"}
+{"parentUuid":"bcdc2f84-6773-460d-97cb-e0f19ee9d655","isSidechain":false,"promptId":"a34a1b6d-99c7-48d3-87a7-bdf62986e6d6","type":"user","message":{"role":"user","content":"<task-notification>\n<task-id>a316a821c79b054b9</task-id>\n<tool-use-id>toolu_012D8sB1E69zHCNdp9tjiF15</tool-use-id>\n<output-file>/private/tmp/claude-502/-Users-example-Work-ai-workers-opencode-agent1/b03cad16-2cf0-43a3-9374-996d0653bb87/tasks/a316a821c79b054b9.output</output-file>\n<status>completed</status>\n<summary>Agent \"Report giá ETH\" finished</summary>\n<note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note>\n<result>**Giá ETH hiện tại (khoảng 4-5/8/2026):**\n\n- **Giá:** ~$1.860 – $1.870 USD (dao động nhẹ tùy sàn)\n- **Thay đổi 24h:** dao động từ khoảng -1,3% đến +1,2% tùy nguồn (Kraken: +0,54%; CoinMarketCap: +1,24%; TradingView: -1,31%)\n- **Vốn hóa thị trường:** ~$225,36 tỷ USD (đứng thứ 2 sau Bitcoin)\n\nLưu ý: giá crypto biến động liên tục nên các sàn có thể chênh lệch nhẹ.\n\n**Nguồn:**\n- [Ethereum price today - CoinMarketCap](https://coinmarketcap.com/currencies/ethereum/)\n- [Ethereum Price Today - Kraken](https://www.kraken.com/prices/ethereum)\n- [Ethereum Price USD - Bitget](https://www.bitget.com/price/ethereum)\n- [ETHUSD - TradingView](https://www.tradingview.com/symbols/ETHUSD/)\n- [Ethereum Price - CoinGecko](https://www.coingecko.com/en/coins/ethereum)</result>\n<usage><subagent_tokens>22468</subagent_tokens><tool_uses>2</tool_uses><duration_ms>16101</duration_ms></usage>\n</task-notification>"},"uuid":"a300c11e-ee90-4971-a55e-1e65cc889ada","timestamp":"2026-08-05T03:03:34.512Z","permissionMode":"bypassPermissions","origin":{"kind":"task-notification"},"promptSource":"system","userType":"external","entrypoint":"cli","cwd":"/Users/example/Work/ai-workers/opencode-agent1","sessionId":"b03cad16-2cf0-43a3-9374-996d0653bb87","version":"2.1.222","gitBranch":"HEAD","slug":"code-landing-page-ve-woolly-cosmos"}
+{"parentUuid":"a300c11e-ee90-4971-a55e-1e65cc889ada","isSidechain":false,"message":{"model":"claude-sonnet-5","id":"msg_011CdirmuoGD5sZutf83YEn1","type":"message","role":"assistant","content":[{"type":"text","text":"Sub-agent ETH xong: **~$1,860–$1,870** (~$225.36 tỷ vốn hóa). Đang chờ BTC, BNB."}],"stop_reason":"end_turn","stop_sequence":null,"stop_details":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":908,"cache_read_input_tokens":98302,"output_tokens":58,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":908,"ephemeral_5m_input_tokens":0},"inference_geo":"not_available","iterations":[{"input_tokens":2,"output_tokens":58,"cache_read_input_tokens":98302,"cache_creation_input_tokens":908,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":908},"type":"message"}],"speed":"standard"},"diagnostics":null},"requestId":"req_011CdirmtZMANtd8iW6nJwsU","type":"assistant","uuid":"dce6acd3-4a9c-4949-b8af-c9830aeff8c5","timestamp":"2026-08-05T03:03:37.111Z","effort":"high","session_id":"b03cad16-2cf0-43a3-9374-996d0653bb87","userType":"external","entrypoint":"cli","cwd":"/Users/example/Work/ai-workers/opencode-agent1","sessionId":"b03cad16-2cf0-43a3-9374-996d0653bb87","version":"2.1.222","gitBranch":"HEAD","slug":"code-landing-page-ve-woolly-cosmos"}
+{"parentUuid":"a9b39095-a212-48df-ae02-cbd99efd8b47","isSidechain":false,"promptId":"dc0af503-4440-451d-a47b-c1568e306d0f","type":"user","message":{"role":"user","content":"<task-notification>\n<task-id>a2c64c3994f29b798</task-id>\n<tool-use-id>toolu_018wkW4V5DWLAQxEHe9Mty56</tool-use-id>\n<output-file>/private/tmp/claude-502/-Users-example-Work-ai-workers-opencode-agent1/b03cad16-2cf0-43a3-9374-996d0653bb87/tasks/a2c64c3994f29b798.output</output-file>\n<status>completed</status>\n<summary>Agent \"Report giá BNB\" finished</summary>\n<note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note>\n<result>**Giá BNB (Binance Coin) hiện tại** (theo CoinMarketCap):\n\n- **Giá:** ~$590,04 USD\n- **Thay đổi 24h:** +0,72%\n- **Vốn hóa thị trường:** ~$78,57 tỷ USD (xếp hạng #4)\n- **Khối lượng giao dịch 24h:** ~$959,99 triệu USD\n\nLưu ý: giá có thể chênh lệch nhẹ giữa các sàn (Coinbase ~$603, Binance.US ~$587,5, TradingView ~$593,3) do tính chất phi tập trung của thị trường crypto.\n\nNguồn:\n- [CoinMarketCap – BNB price today](https://coinmarketcap.com/currencies/bnb/)\n- [Coinbase – BNB price](https://www.coinbase.com/price/bnb)\n- [CoinDesk – BNB price](https://www.coindesk.com/price/binance-coin)</result>\n<usage><subagent_tokens>23357</subagent_tokens><tool_uses>3</tool_uses><duration_ms>20924</duration_ms></usage>\n</task-notification>"},"uuid":"38211f02-97de-4c99-935f-96a89adfb16b","timestamp":"2026-08-05T03:03:40.309Z","permissionMode":"bypassPermissions","origin":{"kind":"task-notification"},"promptSource":"system","userType":"external","entrypoint":"cli","cwd":"/Users/example/Work/ai-workers/opencode-agent1","sessionId":"b03cad16-2cf0-43a3-9374-996d0653bb87","version":"2.1.222","gitBranch":"HEAD","slug":"code-landing-page-ve-woolly-cosmos"}
+{"parentUuid":"38211f02-97de-4c99-935f-96a89adfb16b","isSidechain":false,"message":{"model":"claude-sonnet-5","id":"msg_011CdirnM4HxsRzijHpb9wek","type":"message","role":"assistant","content":[{"type":"text","text":"Sub-agent BNB xong: **~$590.04** (+0.72% 24h). Chỉ còn chờ BTC."}],"stop_reason":"end_turn","stop_sequence":null,"stop_details":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":811,"cache_read_input_tokens":99268,"output_tokens":45,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":811,"ephemeral_5m_input_tokens":0},"inference_geo":"not_available","iterations":[{"input_tokens":2,"output_tokens":45,"cache_read_input_tokens":99268,"cache_creation_input_tokens":811,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":811},"type":"message"}],"speed":"standard"},"diagnostics":null},"requestId":"req_011CdirnKXmPQEbfckXVQVPn","type":"assistant","uuid":"b686b78e-0da0-474d-bd10-d46bcfb45931","timestamp":"2026-08-05T03:03:42.739Z","effort":"high","session_id":"b03cad16-2cf0-43a3-9374-996d0653bb87","userType":"external","entrypoint":"cli","cwd":"/Users/example/Work/ai-workers/opencode-agent1","sessionId":"b03cad16-2cf0-43a3-9374-996d0653bb87","version":"2.1.222","gitBranch":"HEAD","slug":"code-landing-page-ve-woolly-cosmos"}
+{"parentUuid":"87df87cb-268e-47d7-a5ed-8d5a9887d1b0","isSidechain":false,"promptId":"4aee7f55-d1a2-403d-b844-f079413b802c","type":"user","message":{"role":"user","content":"<task-notification>\n<task-id>a523fae36e503c7a1</task-id>\n<tool-use-id>toolu_0151gJRdan4nRckLW37Woy5N</tool-use-id>\n<output-file>/private/tmp/claude-502/-Users-example-Work-ai-workers-opencode-agent1/b03cad16-2cf0-43a3-9374-996d0653bb87/tasks/a523fae36e503c7a1.output</output-file>\n<status>completed</status>\n<summary>Agent \"Report giá BTC\" finished</summary>\n<note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note>\n<result>## Giá Bitcoin (BTC) hiện tại\n\n- **Giá:** khoảng **$63.500 – $63.900 USD** (dữ liệu sáng 4-5/8/2026)\n- **Thay đổi 24h:** khoảng **+2,1%**\n- **Vốn hóa thị trường:** khoảng **$1.281 tỷ USD** (~1,28 nghìn tỷ)\n- **Khối lượng giao dịch 24h:** khoảng $25,7 tỷ USD\n\nLưu ý: giá có thể chênh lệch nhẹ (khoảng $62.700–$64.000) tùy sàn giao dịch và thời điểm cập nhật do biến động thị trường real-time.\n\n**Nguồn:**\n- [Bitcoin price today, BTC to USD live price, marketcap and chart | CoinMarketCap](https://coinmarketcap.com/currencies/bitcoin/)\n- [Bitcoin price today, BTC to USD live price, marketcap and chart | CoinDesk](https://www.coindesk.com/price/bitcoin)\n- [Current price of Bitcoin for August 4, 2026 | Fortune](https://fortune.com/article/price-of-bitcoin-08-04-2026/)\n- [Current price of Bitcoin for August 3, 2026 | Fortune](https://fortune.com/article/price-of-bitcoin-08-03-2026/)</result>\n<usage><subagent_tokens>23679</subagent_tokens><tool_uses>3</tool_uses><duration_ms>37304</duration_ms></usage>\n</task-notification>"},"uuid":"d00348f9-be09-4c26-b336-49699c0d0941","timestamp":"2026-08-05T03:03:54.705Z","permissionMode":"bypassPermissions","origin":{"kind":"task-notification"},"promptSource":"system","userType":"external","entrypoint":"cli","cwd":"/Users/example/Work/ai-workers/opencode-agent1","sessionId":"b03cad16-2cf0-43a3-9374-996d0653bb87","version":"2.1.222","gitBranch":"HEAD","slug":"code-landing-page-ve-woolly-cosmos"}
+{"parentUuid":"d00348f9-be09-4c26-b336-49699c0d0941","isSidechain":false,"message":{"model":"claude-sonnet-5","id":"msg_011CdiroQaAE3qz5v6VKxiaU","type":"message","role":"assistant","content":[{"type":"text","text":"Cả 3 sub-agent đã hoàn thành. Tổng hợp giá coin:\n\n| Coin | Giá (USD) | Thay đổi 24h | Vốn hóa thị trường |\n|---|---|---|---|\n| **BTC** | ~$63,500–$63,900 | +2.1% | ~$1,281 tỷ (#1) |\n| **ETH** | ~$1,860–$1,870 | ~+0.5–1.2% (chênh lệch giữa sàn) | ~$225.36 tỷ (#2) |\n| **BNB** | ~$590.04 | +0.72% | ~$78.57 tỷ (#4) |"}],"stop_reason":"end_turn","stop_sequence":null,"stop_details":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":958,"cache_read_input_tokens":100124,"output_tokens":224,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":958,"ephemeral_5m_input_tokens":0},"inference_geo":"not_available","iterations":[{"input_tokens":2,"output_tokens":224,"cache_read_input_tokens":100124,"cache_creation_input_tokens":958,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":958},"type":"message"}],"speed":"standard"},"diagnostics":null},"requestId":"req_011CdiroP3PCaKzhRGN9hyUC","type":"assistant","uuid":"e0b9f612-31ff-41aa-9e78-f9e213479423","timestamp":"2026-08-05T03:03:58.748Z","effort":"high","session_id":"b03cad16-2cf0-43a3-9374-996d0653bb87","userType":"external","entrypoint":"cli","cwd":"/Users/example/Work/ai-workers/opencode-agent1","sessionId":"b03cad16-2cf0-43a3-9374-996d0653bb87","version":"2.1.222","gitBranch":"HEAD","slug":"code-landing-page-ve-woolly-cosmos"}
diff --git a/cli/src/lib/askQuestion.spec.ts b/cli/src/lib/askQuestion.spec.ts
new file mode 100644
index 000000000..a0699bfac
--- /dev/null
+++ b/cli/src/lib/askQuestion.spec.ts
@@ -0,0 +1,407 @@
+import { readFileSync } from 'fs'
+import { join } from 'path'
+import { describe, expect, it } from 'vitest'
+import {
+ AskQuestionController,
+ matchRow,
+ parseEngineQuestionPane,
+ parseQuestionPane,
+ QuestionWatcher,
+ shapeQuestions,
+ type QuestionView,
+ type ReviewView,
+} from './askQuestion.js'
+import type { RegisteredSession } from './registry.js'
+
+// Real `tmux capture-pane` output from Claude Code 2.1.220 dialogs (the single-select one still carries
+// its SGR codes, exactly as captureTmuxPane returns it).
+const fixture = (name: string): string =>
+ readFileSync(join(__dirname, '__fixtures__', `question-${name}.txt`), 'utf8')
+
+const asQuestion = (view: ReturnType<typeof parseQuestionPane>): QuestionView => {
+ expect(view?.kind).toBe('question')
+ return view as QuestionView
+}
+
+describe('shapeQuestions', () => {
+ it('keys each question the way the CLI matches answers, and flattens option labels', () => {
+ const shaped = shapeQuestions([
+ { question: 'Which color?', header: 'Color', multiSelect: true, options: [{ label: 'Red', description: 'warm' }, { label: 'Blue' }] },
+ ])
+ expect(shaped).toEqual([{ key: 'Which color?', q: 'Which color?', options: ['Red', 'Blue'], multi: true }])
+ })
+
+ it('falls back to id/header for the key and defaults multi to false', () => {
+ expect(shapeQuestions([{ id: 'q1', options: [] }])).toEqual([{ key: 'q1', q: '', options: [], multi: false }])
+ expect(shapeQuestions(undefined)).toEqual([])
+ })
+})
+
+describe('the Hermes clarify dialog', () => {
+ // Real capture from hermes on a live pane: the SAME dialog Claude paints (`❯ 1. Xanh` rows, a footer
+ // reading "Enter to confirm") wrapped in a box-drawing frame. Peeling the frame is the whole adaptation
+ // — a second parser would have drifted from the one it duplicates.
+ it('reads through the box frame that wraps it', () => {
+ const view = asQuestion(parseEngineQuestionPane('hermes', fixture('hermes')))
+ expect(view.question).toBe('Bạn muốn chọn size nào?')
+ expect(view.rows.map((r) => [r.number, r.label])).toEqual([['1', 'S'], ['2', 'M']])
+ expect(view.multi).toBe(false)
+ })
+
+ it('offers the free-text row as free text, not as an option', () => {
+ // Hermes writes "Other (type your answer)" where Claude writes "Type something." — it must not be
+ // announced to the device as a choosable label.
+ const view = asQuestion(parseEngineQuestionPane('hermes', fixture('hermes')))
+ expect(view.rows.map((r) => r.label)).not.toContain('Other (type your answer)')
+ })
+
+ it('is invisible to the unframed parser — which is why the engine branch exists', () => {
+ expect(parseQuestionPane(fixture('hermes'))).toBeNull()
+ })
+})
+
+describe('the OpenCode question dialog', () => {
+ // Real capture from opencode on a live pane. Same bones as Claude's — `1. Size S` rows, a free-text row
+ // last — but framed in `┃` and with its own footer wording ("enter submit"), which is why the shared
+ // footer anchor had to learn a second phrasing rather than each CLI getting a parser.
+ it('reads through the frame and the different footer wording', () => {
+ const view = asQuestion(parseEngineQuestionPane('opencode', fixture('opencode')))
+ expect(view.question).toBe('Bạn muốn chọn size nào?')
+ expect(view.rows.map((r) => r.label)).toEqual(['Size S', 'Size M'])
+ })
+
+ it('treats "Type your own answer" as the free-text row, not an option', () => {
+ // Each CLI words this row differently; offering it as a label would send the device an answer that
+ // selects nothing.
+ const view = asQuestion(parseEngineQuestionPane('opencode', fixture('opencode')))
+ expect(view.typeRow?.label).toBe('Type your own answer')
+ expect(view.rows.map((r) => r.label)).not.toContain('Type your own answer')
+ })
+
+ it('ignores the description line under each option', () => {
+ const view = asQuestion(parseEngineQuestionPane('opencode', fixture('opencode')))
+ expect(view.rows).toHaveLength(2)
+ })
+})
+
+describe('the OpenCode review screen', () => {
+ // Real capture of the last step of a multi-question dialog: a "Review" heading over `label: answer`
+ // lines, NO numbered rows, submitted with Enter. Before this was recognised the driver read it as "no
+ // dialog", stopped, and left a fully-answered form sitting there unsubmitted.
+ it('is a review, not a question, and submits with Enter', () => {
+ const view = parseEngineQuestionPane('opencode', fixture('opencode-review')) as ReviewView
+ expect(view?.kind).toBe('review')
+ expect(view.submitRow).toBe('Enter')
+ })
+
+ it('does not mistake a live question for the review', () => {
+ expect(parseEngineQuestionPane('opencode', fixture('opencode'))?.kind).toBe('question')
+ })
+})
+
+describe('parseQuestionPane', () => {
+ it('reads a single-select dialog through its ANSI styling', () => {
+ const view = asQuestion(parseQuestionPane(fixture('single')))
+ expect(view.question).toBe('Which drink would you like?')
+ expect(view.rows.map((r) => r.label)).toEqual(['Tea', 'Coffee'])
+ expect(view.multi).toBe(false)
+ expect(view.typeRow?.number).toBe('3')
+ })
+
+ it('reads a multi-select dialog: checkbox rows, and excludes the type/chat rows', () => {
+ const view = asQuestion(parseQuestionPane(fixture('multi')))
+ expect(view.question).toBe('Which toppings do you want?')
+ expect(view.rows.map((r) => r.label)).toEqual(['Cheese', 'Ham', 'Basil'])
+ expect(view.multi).toBe(true)
+ expect(view.typeRow?.number).toBe('4')
+ })
+
+ it('skips the question tab bar when several questions share one dialog', () => {
+ const view = asQuestion(parseQuestionPane(fixture('tabs')))
+ expect(view.question).toBe('Which colors do you like?')
+ expect(view.rows.map((r) => r.label)).toEqual(['Red', 'Blue', 'Green'])
+ })
+
+ it('recognises the review screen (no footer, rows below the prompt)', () => {
+ const view = parseQuestionPane(fixture('review'))
+ expect(view?.kind).toBe('review')
+ expect((view as ReviewView).submitRow).toBe('1')
+ })
+
+ it('returns null when no dialog is open', () => {
+ expect(parseQuestionPane('❯ \n ⏸ plan mode on (shift+tab to cycle)')).toBeNull()
+ })
+})
+
+describe('matchRow', () => {
+ const rows = [
+ { number: '1', label: 'Tách socket riêng cho voice', checked: false },
+ { number: '2', label: 'Giữ nguyên', checked: false },
+ ]
+
+ it('matches exactly and case/space-insensitively', () => {
+ expect(matchRow(rows, 'giữ NGUYÊN')?.number).toBe('2')
+ })
+
+ it('matches a label the device truncated to its 80-byte buffer', () => {
+ expect(matchRow(rows, 'Tách socket riêng')?.number).toBe('1')
+ })
+
+ it('returns null for a free-text answer', () => {
+ expect(matchRow(rows, 'cho tao cai khac di')).toBeNull()
+ })
+})
+
+// --- driving the pane -------------------------------------------------------------------------
+
+interface Machine {
+ keys: string[]
+ texts: string[]
+ controller: AskQuestionController
+}
+
+function machine(captures: string[]): Machine {
+ const keys: string[] = []
+ const texts: string[] = []
+ let i = 0
+ const controller = new AskQuestionController({
+ getSession: () => ({ sessionId: 's1', tmuxPane: '%1' } as RegisteredSession),
+ capture: async () => captures[Math.min(i++, captures.length - 1)],
+ sendText: async (_pane, text) => { texts.push(text); return true },
+ sendKey: async (_pane, key) => { keys.push(key); return true },
+ wait: async () => {},
+ })
+ return { keys, texts, controller }
+}
+
+const CLOSED = '❯ \n ⏸ plan mode on (shift+tab to cycle)'
+
+describe('AskQuestionController.answer', () => {
+ it('presses the option digit for a single-select answer', async () => {
+ const h = machine([fixture('single'), CLOSED])
+ const ok = await h.controller.answer({ requestId: 'r1', sessionId: 's1', answers: { 'Which drink would you like?': 'Coffee' } })
+ expect(ok).toBe(true)
+ expect(h.keys).toEqual(['2'])
+ })
+
+ it('types a voice/free-text answer into the "Type something." row and submits it', async () => {
+ const h = machine([fixture('single'), CLOSED])
+ const ok = await h.controller.answer({ requestId: 'r1', sessionId: 's1', answers: { 'Which drink would you like?': 'nuoc mia' } })
+ expect(ok).toBe(true)
+ expect(h.keys).toEqual(['3', 'Enter'])
+ expect(h.texts).toEqual(['nuoc mia'])
+ })
+
+ it('toggles each selected checkbox then Tabs on, and submits from the review screen', async () => {
+ const h = machine([fixture('multi'), fixture('review')])
+ const ok = await h.controller.answer({ requestId: 'r1', sessionId: 's1', answers: { 'Which toppings do you want?': 'Cheese, Basil' } })
+ expect(ok).toBe(true)
+ expect(h.keys).toEqual(['1', '3', 'Tab', '1'])
+ })
+
+ it('answers each question of a multi-question dialog positionally when the text does not match', async () => {
+ const h = machine([fixture('tabs'), fixture('single'), CLOSED])
+ const ok = await h.controller.answer({
+ requestId: 'r1',
+ sessionId: 's1',
+ answers: { 'Which colors do you like?': 'Blue', 'Which size do you want?': 'Tea' },
+ })
+ expect(ok).toBe(true)
+ expect(h.keys).toEqual(['2', 'Tab', '1'])
+ })
+
+ it('leaves a multi-question dialog open on the question the device has not been shown yet', async () => {
+ // The device answers ONE question at a time (the watcher pushes them as the pane advances), so the
+ // drive loop must stop at the next question instead of guessing an answer for it.
+ const h = machine([fixture('tabs'), fixture('single'), CLOSED])
+ const ok = await h.controller.answer({ requestId: 'r1', sessionId: 's1', answers: { 'Which colors do you like?': 'Blue' } })
+ expect(ok).toBe(true)
+ expect(h.keys).toEqual(['2', 'Tab'])
+ })
+
+ it('does nothing when the dialog is already gone', async () => {
+ const h = machine([CLOSED])
+ expect(await h.controller.answer({ requestId: 'r1', sessionId: 's1', answers: { q: 'a' } })).toBe(false)
+ expect(h.keys).toEqual([])
+ })
+
+ it('gives up instead of hammering keys when the dialog never advances', async () => {
+ const h = machine([fixture('single')])
+ const ok = await h.controller.answer({ requestId: 'r1', sessionId: 's1', answers: { 'Which drink would you like?': 'Tea' } })
+ expect(ok).toBe(false)
+ expect(h.keys.length).toBeLessThanOrEqual(3)
+ })
+
+ it('falls back to the remembered session when the device sends no sessionId', async () => {
+ const h = machine([fixture('single'), CLOSED])
+ h.controller.remember('r9', 's1')
+ expect(await h.controller.answer({ requestId: 'r9', answers: { 'Which drink would you like?': 'Tea' } })).toBe(true)
+ expect(h.keys).toEqual(['1'])
+ })
+
+ it('drops an answer with no answers map', async () => {
+ const h = machine([fixture('single')])
+ expect(await h.controller.answer({ requestId: 'r1', sessionId: 's1', answers: {} })).toBe(false)
+ })
+})
+
+describe('QuestionWatcher', () => {
+ const session = { sessionId: 's1', tmuxPane: '%1', engine: 'claude' } as RegisteredSession
+
+ function watcher(captures: string[], opts: { hasDevice?: boolean } = {}): {
+ seen: Array<{ requestId: string; questions: ReturnType<typeof shapeQuestions> }>
+ tick: () => Promise<void>
+ instance: QuestionWatcher
+ } {
+ let i = 0
+ const seen: Array<{ requestId: string; questions: ReturnType<typeof shapeQuestions> }> = []
+ const instance = new QuestionWatcher({
+ getSession: () => session,
+ capture: async () => captures[Math.min(i++, captures.length - 1)],
+ hasDevice: () => opts.hasDevice !== false,
+ onQuestion: (_s, requestId, questions) => { seen.push({ requestId, questions }) },
+ })
+ // tick() is private — exercised the way the interval does.
+ const tick = (): Promise<void> => (instance as unknown as { tick: (s: string) => Promise<void> }).tick('s1')
+ return { seen, tick, instance }
+ }
+
+ it('announces an open dialog in the device question shape', async () => {
+ const w = watcher([fixture('single')])
+ await w.tick()
+ expect(w.seen).toHaveLength(1)
+ expect(w.seen[0].questions).toEqual([
+ { key: 'Which drink would you like?', q: 'Which drink would you like?', options: ['Tea', 'Coffee'], multi: false },
+ ])
+ })
+
+ it('announces a question ONCE while it stays on screen', async () => {
+ const w = watcher([fixture('single')])
+ await w.tick(); await w.tick(); await w.tick()
+ expect(w.seen).toHaveLength(1)
+ })
+
+ it('announces the next question of the same dialog once the pane advances', async () => {
+ const w = watcher([fixture('tabs'), fixture('single')])
+ await w.tick(); await w.tick()
+ expect(w.seen.map((s) => s.questions[0].q)).toEqual(['Which colors do you like?', 'Which drink would you like?'])
+ expect(w.seen[0].requestId).not.toBe(w.seen[1].requestId)
+ })
+
+ it('re-announces an open question after a device (re)join', async () => {
+ const w = watcher([fixture('single')])
+ await w.tick()
+ w.instance.reset()
+ await w.tick()
+ expect(w.seen).toHaveLength(2)
+ expect(w.seen[0].requestId).toBe(w.seen[1].requestId) // stable id → the device dedups if it still has it
+ })
+
+ it('says nothing when the pane has no dialog, or when no device is listening', async () => {
+ expect((await (async () => { const w = watcher([CLOSED]); await w.tick(); return w.seen })()).length).toBe(0)
+ expect((await (async () => { const w = watcher([fixture('single')], { hasDevice: false }); await w.tick(); return w.seen })()).length).toBe(0)
+ })
+
+ it('carries the multi-select flag so the device renders checkboxes', async () => {
+ const w = watcher([fixture('multi')])
+ await w.tick()
+ expect(w.seen[0].questions[0]).toMatchObject({ options: ['Cheese', 'Ham', 'Basil'], multi: true })
+ })
+})
+
+describe('parseQuestionPane — frame boundary', () => {
+ // A capture taken mid-repaint: the live frame's question line is not painted yet, and the PREVIOUS
+ // question is still in scrollback above. Pairing that stale title with the live options is what made
+ // the device re-show "Chọn màu?" over question 2's options.
+ const midRepaint = [
+ 'Chọn màu?',
+ '',
+ ' 1. Đỏ',
+ ' 2. Vàng',
+ '────────────────────────────',
+ '← ☒ Màu ☐ Size ✔ Submit →',
+ '',
+ '',
+ '❯ 1. S',
+ ' Nhỏ.',
+ ' 2. M',
+ ' 3. Type something.',
+ '',
+ 'Enter to select · Tab/Arrow keys to navigate · Esc to cancel',
+ ].join('\n')
+
+ it('never takes a question from an older frame in scrollback', () => {
+ const view = parseQuestionPane(midRepaint) as QuestionView
+ expect(view.kind).toBe('question')
+ expect(view.rows.map((r) => r.label)).toEqual(['S', 'M'])
+ expect(view.question).toBe('') // → the watcher skips this tick instead of announcing a stale title
+ })
+
+ it('so the watcher announces nothing until the question paints', async () => {
+ let capture = midRepaint
+ const seen: string[] = []
+ const w = new QuestionWatcher({
+ getSession: () => ({ sessionId: 's1', tmuxPane: '%1', engine: 'claude' } as RegisteredSession),
+ capture: async () => capture,
+ hasDevice: () => true,
+ onQuestion: (_s, _r, qs) => { seen.push(qs[0].q) },
+ })
+ const tick = (): Promise<void> => (w as unknown as { tick: (s: string) => Promise<void> }).tick('s1')
+ await tick()
+ expect(seen).toEqual([])
+ capture = midRepaint.replace('← ☒ Màu ☐ Size ✔ Submit →\n\n', '← ☒ Màu ☐ Size ✔ Submit →\n\nChọn size?\n')
+ await tick()
+ expect(seen).toEqual(['Chọn size?'])
+ })
+})
+
+/**
+ * Command Code paints the same dialog as Claude but with NO footer — the pane just ends at the last
+ * option — so the footer anchor found nothing and the device showed no question at all while the terminal
+ * sat waiting for an answer. Fixture captured from a live pane.
+ */
+describe('the Command Code question dialog', () => {
+ const capture = fixture('commandcode')
+
+ it('reads it through the tab bar instead of a footer', () => {
+ const view = parseQuestionPane(capture)
+ expect(view?.kind).toBe('question')
+ if (view?.kind !== 'question') return
+ expect(view.question).toBe('"Cầu vụ" bạn muốn game gì?')
+ expect(view.rows.map((row) => row.label)).toEqual([
+ 'Cờ vua (Chess) (Recommended)',
+ 'Cầu vồng',
+ 'Cầu vượt',
+ ])
+ })
+
+ it('keeps the free-text row out of the options', () => {
+ // Claude writes "Type something.", Command Code "Type something..." — treated as an option it would
+ // both pollute the device's list and leave a voice answer nowhere to go.
+ const view = parseQuestionPane(capture)
+ if (view?.kind !== 'question') throw new Error('not a question')
+ expect(view.typeRow?.number).toBe('4')
+ expect(view.rows.some((row) => /type something/i.test(row.label))).toBe(false)
+ })
+})
+
+/**
+ * Command Code's review screen has neither Claude's "Ready to submit your answers" line nor a footer —
+ * just a Submit/Cancel pair under a numbered summary. Unrecognised, the drive loop hit its "nothing on
+ * screen" exit and reported success while the terminal sat on the review screen, unanswered. Fixture
+ * captured from a live pane in exactly that state.
+ */
+describe('the Command Code review screen', () => {
+ const capture = fixture('commandcode-review')
+
+ it('is recognised by its Submit/Cancel pair', () => {
+ expect(parseQuestionPane(capture)).toEqual({ kind: 'review', submitRow: '1' })
+ })
+
+ it('does not read the numbered SUMMARY as options', () => {
+ // "1. Quân cờ mày muốn hình dạng kiểu nào?" and friends are recap lines, not choices — reading them
+ // as a question is how a review screen turns into a phantom question on the device.
+ const view = parseQuestionPane(capture)
+ expect(view?.kind).not.toBe('question')
+ })
+})
diff --git a/cli/src/lib/askQuestion.ts b/cli/src/lib/askQuestion.ts
new file mode 100644
index 000000000..bb62f4ba4
--- /dev/null
+++ b/cli/src/lib/askQuestion.ts
@@ -0,0 +1,570 @@
+/**
+ * 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.
+ *
+ * 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
+ * such channel — the adapter watches a JSONL transcript and talks to a real TUI. So both halves read and
+ * write the pane itself:
+ *
+ * OUT QuestionWatcher polls the pane while a turn is open and pushes the open dialog as
+ * `commander_question`, in the SAME shape the hosted runtime sends, so the firmware's existing question
+ * screen renders it unchanged (commanderQuestions in websocket.ts). NOT from the transcript —
+ * see the QuestionWatcher docblock for why that source cannot work.
+ * IN the device's `question_response` → keystrokes into the pane's dialog.
+ *
+ * Dialog mechanics (verified against Claude Code 2.1.220, `tmux capture-pane`):
+ * - single-select : the option's digit selects AND submits, advancing to the next question / review.
+ * - free text : the digit of the "Type something." row opens it for editing (does NOT submit) →
+ * type the text → Enter submits.
+ * - multi-select : rows render as `[ ]` / `[✔]`; a digit TOGGLES; Tab advances to the next question.
+ * - review : after the last question, "Ready to submit your answers?" → "1. Submit answers".
+ */
+
+import type { RegisteredSession } from './registry.js'
+import type { AgentEngine } from '../engines/types.js'
+import { parseDevinQuestionPane } from '../engines/devin/askQuestion.js'
+
+/** Device-facing question shape — byte-for-byte the hosted runtime’s `commanderQuestions()` output. */
+export interface ShapedQuestion {
+ key: string
+ q: string
+ options: string[]
+ multi: boolean
+}
+
+export interface QuestionRow {
+ /** The digit to press. */
+ number: string
+ /** Option text with any `[ ]` checkbox prefix removed. */
+ label: string
+ checked: boolean
+}
+
+export interface QuestionView {
+ kind: 'question'
+ question: string
+ rows: QuestionRow[]
+ multi: boolean
+ /** The "Type something." row, when the dialog offers free text. */
+ typeRow: QuestionRow | null
+}
+
+export interface ReviewView {
+ kind: 'review'
+ submitRow: string
+}
+
+export type PaneView = QuestionView | ReviewView | null
+
+const STEP_MS = 350 // let the TUI repaint between keystrokes
+const TEXT_MS = 250
+const MAX_STEPS = 14 // hard bound on the drive loop (questions × keys), never spin on a stuck pane
+const CAPTURE_LINES = 60
+
+// Rows that exist in every dialog but can never BE an answer.
+const CHAT_ROW = /^chat about (this|these)$/i
+// Claude writes "Type something.", Command Code "Type something..." — one trailing dot or three, and
+// missing it costs the free-text row: a voice answer would have nowhere to go and the row would be
+// offered on the device as if it were a real option.
+// Claude "Type something.", Command Code "Type something...", OpenCode "Type your own answer", Hermes
+// "Other (type your answer)". Same row in every dialog: it opens an editor instead of choosing, so it must
+// never be offered to the device as a selectable label.
+const TYPE_ROW = /^(type something\.{0,3}|type your own( answer)?|other \(type your (own|answer)\))$/i
+
+function stripAnsi(value: string): string {
+ return value.replace(/\u001b\[[0-9;:]*[A-Za-z]/g, '')
+}
+
+function norm(value: string): string {
+ return value.toLowerCase().replace(/\s+/g, ' ').replace(/[.…]+$/, '').trim()
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms))
+}
+
+/**
+ * Shape a raw AskUserQuestion input into the device form. Port of the hosted runtime’s `commanderQuestions`
+ * (websocket.ts): `key` MUST stay the value the CLI matches answers by — prompt/question first — because
+ * the device echoes it back as the answers-map key.
+ */
+export function shapeQuestions(questions: unknown): ShapedQuestion[] {
+ return (Array.isArray(questions) ? questions : []).map((raw, i) => {
+ const q = (raw ?? {}) as Record<string, unknown>
+ const opts = Array.isArray(q.options) ? q.options : []
+ return {
+ key: (q.prompt as string) || (q.question as string) || (q.id as string) || (q.header as string) || `question_${i}`,
+ q: (q.prompt as string) || (q.question as string) || '',
+ options: opts
+ .map((o) => String((typeof o === 'string' ? o : (o as Record<string, unknown>)?.label) ?? ''))
+ .filter(Boolean),
+ // Three spellings because three CLIs: `allow_multiple` (the hosted runtime), `multiSelect` (claude),
+ // `multi_select` (devin — read from a real `ask_user_question` call in its SQLite store).
+ multi: (q.allow_multiple as boolean) ?? (q.multiSelect as boolean) ?? (q.multi_select as boolean) ?? false,
+ }
+ })
+}
+
+/**
+ * The dialog on screen, read the way `engine` paints it.
+ *
+ * Claude and Command Code share one shape (see parseQuestionPane); devin draws a different one and gets
+ * its own parser rather than more branches in here.
+ */
+export function parseEngineQuestionPane(engine: AgentEngine, capture: string): PaneView {
+ if (engine === 'devin') return parseDevinQuestionPane(capture)
+ // Hermes and OpenCode paint Claude's dialog inside a box; peel the border and the shared parser fits.
+ if (engine === 'hermes') return parseQuestionPane(unframe(capture))
+ if (engine === 'opencode') {
+ const plain = unframe(capture)
+ return opencodeReview(plain) ?? parseQuestionPane(plain)
+ }
+ return parseQuestionPane(capture)
+}
+
+/**
+ * Strip the box-drawing frame Hermes draws around its `clarify` dialog.
+ *
+ * Measured on a live pane: Hermes paints the SAME dialog Claude does — `❯ 1. Xanh` rows, a footer reading
+ * `↑/↓ to select, Enter to confirm` — only wrapped in `│ … │`. Peeling the border makes the existing
+ * parser fit exactly, which is far better than a second parser that would drift from it over time.
+ */
+/**
+ * OpenCode's final step of a multi-question dialog.
+ *
+ * It is a REVIEW, not a question: a "Review" heading over `label: answer` lines, with no numbered rows at
+ * all, submitted by pressing Enter. The shared parser needs rows to recognise a dialog, so without this
+ * the driver saw "nothing on screen", stopped, and left the agent sitting on an unsubmitted form after
+ * every answer had been given (measured on a live pane).
+ *
+ * `submitRow` carries the KEY to press, which for every other CLI happens to be a digit — 'Enter' rides
+ * the same field rather than widening the type for one engine.
+ */
+function opencodeReview(plain: string): ReviewView | null {
+ const lines = stripAnsi(plain).split('\n')
+ const footer = lines.findLastIndex((l) => /enter\s+submit/i.test(l))
+ if (footer < 0) return null
+ let sawReview = false
+ for (let i = footer - 1; i >= 0 && footer - i <= 14; i--) {
+ if (parseRow(lines[i])) return null // rows above ⇒ still a question, not the review
+ if (/^\s*review\s*$/i.test(lines[i])) { sawReview = true; break }
+ }
+ return sawReview ? { kind: 'review', submitRow: 'Enter' } : null
+}
+
+function unframe(capture: string): string {
+ // stripAnsi FIRST: on a real capture the border is preceded by SGR codes, so matching `^│` against the
+ // raw text silently never fired — hermes read as "no dialog open" with the dialog plainly on screen.
+ return stripAnsi(capture)
+ .split('\n')
+ .map((line) => line.replace(/^(\s*)[│┃|]\s?/, '$1').replace(/\s*[│┃|]\s*$/, ''))
+ .join('\n')
+}
+
+/** How this engine's multi-select dialog is submitted once the boxes are ticked. */
+function multiSubmitKey(engine: AgentEngine): string {
+ // Claude advances with Tab; devin submits with Enter (measured on a live pane — Tab does nothing there).
+ return engine === 'devin' ? 'Enter' : 'Tab'
+}
+
+function parseRow(line: string): QuestionRow | null {
+ const m = /^\s*[❯›>]?\s*(\d+)\.\s+(.+?)\s*$/.exec(line)
+ if (!m) return null
+ const raw = m[2]
+ const box = /^\[([^\]])\]\s*(.*)$/.exec(raw)
+ return {
+ number: m[1],
+ label: (box ? box[2] : raw).trim(),
+ checked: !!box && box[1].trim() !== '',
+ }
+}
+
+/**
+ * Read the CURRENT dialog off a pane capture. The capture includes scrollback (old dialogs, old plan
+ * text), so everything is anchored to the LAST footer line — the only marker the live dialog always
+ * paints at the bottom of the screen.
+ */
+/** "❯ 1. Submit" immediately followed by "2. Cancel" — Command Code's review screen, which carries no
+ * other marker. Returns the Submit row's number and where it sits, or null. */
+function findSubmitPair(lines: string[]): { row: string; index: number } | null {
+ for (let i = lines.length - 1; i >= 1; i--) {
+ const row = parseRow(lines[i])
+ if (!row || !/^submit$/i.test(row.label)) continue
+ const next = parseRow(lines[i + 1] ?? '')
+ if (next && /^cancel$/i.test(next.label)) return { row: row.number, index: i }
+ }
+ return null
+}
+
+/** The tab bar of a footer-less dialog: "● Loại game | ◯ Review". Returns its LAST occurrence, or -1. */
+function findTabBarDialog(lines: string[]): number {
+ for (let i = lines.length - 1; i >= 0; i--) {
+ const line = lines[i].trim()
+ if (!/^[●◯✔✓]/.test(line) || !line.includes('|')) continue // answered tabs turn into ✔
+ // Only a tab bar with a numbered list under it is a question; the same glyphs appear in prose.
+ for (let j = i + 1; j < lines.length && j - i <= 8; j++) {
+ const row = parseRow(lines[j])
+ if (row?.number === '1') return i
+ }
+ }
+ return -1
+}
+
+/** Read a dialog that has no footer: question first, then the numbered rows, top-down from the tab bar. */
+function parseDownward(lines: string[], tabBar: number): PaneView {
+ let question = ''
+ const rows: QuestionRow[] = []
+ let checkbox = false
+ for (let i = tabBar + 1; i < lines.length; i++) {
+ const row = parseRow(lines[i])
+ if (row) {
+ if (/^\s*[❯›>]?\s*\d+\.\s+\[/.test(lines[i])) checkbox = true
+ rows.push(row)
+ continue
+ }
+ // Between the tab bar and row 1 sits the question; after the rows start, plain lines are the option
+ // descriptions and must not overwrite it.
+ const line = lines[i].trim()
+ if (!question && rows.length === 0 && line && !/^[─━-]{6,}$/.test(line)) question = line
+ }
+ if (!rows.length) return null
+ const answerable = rows.filter((r) => !CHAT_ROW.test(r.label) && !TYPE_ROW.test(r.label))
+ return {
+ kind: 'question',
+ question,
+ rows: answerable,
+ multi: checkbox,
+ typeRow: rows.find((r) => TYPE_ROW.test(r.label)) ?? null,
+ }
+}
+
+export function parseQuestionPane(capture: string): PaneView {
+ const lines = stripAnsi(capture).replace(/\u00a0/g, ' ').split('\n')
+ // Each CLI words its own footer, and OpenCode rewords it PER SCREEN — `enter submit` on a single
+ // question, `enter toggle` on a multi-select, `enter confirm` on a step of a multi-question. They all
+ // mark the same thing: the bottom of a live dialog.
+ const footer = lines.findLastIndex((l) => /enter to (select|confirm)|enter\s+(submit|confirm|toggle)/i.test(l))
+ // The review screen paints no footer and puts its rows BELOW the prompt, so it needs its own anchor.
+ // Whichever anchor is LOWER on screen is the live one (the other is scrollback from an earlier step).
+ const review = lines.findLastIndex((l) => /Ready to submit your answers/i.test(l))
+ if (review > footer) {
+ for (let i = review + 1; i < lines.length && i - review <= 10; i++) {
+ const row = parseRow(lines[i])
+ if (row && /^submit answers$/i.test(row.label)) return { kind: 'review', submitRow: row.number }
+ }
+ return null
+ }
+ // Command Code's review screen has neither Claude's "Ready to submit your answers" line nor a footer:
+ // it is a "Submit"/"Cancel" pair under a summary that is itself numbered. Anchor on that PAIR — the two
+ // rows adjacent, in that order — because the summary lines above are numbered too and reading them as
+ // options is how the device answered everything and then sat there, never submitting.
+ const submit = findSubmitPair(lines)
+ if (submit && submit.index > footer) return { kind: 'review', submitRow: submit.row }
+ // Command Code paints the SAME dialog with no footer at all — the pane simply ends at the last option.
+ // Its tab bar is the only thing above the rows that is unmistakably part of the dialog, so anchor on
+ // that and read DOWNWARD. Nothing else on either CLI's screen looks like "● X | ◯ Y" followed by a
+ // numbered list, which is what keeps ordinary numbered output from being read as a question.
+ const anchor = footer >= 0 ? footer : findTabBarDialog(lines)
+ if (anchor < 0) return null
+ if (footer < 0) return parseDownward(lines, anchor)
+
+ // Rows belonging to this dialog: the numbered rows just above the footer, back to the row numbered 1.
+ const rows: QuestionRow[] = []
+ let checkbox = false // `[ ]` / `[✔]` on a row ⇒ this question is multi-select
+ let start = -1
+ for (let i = footer - 1; i >= 0 && footer - i <= 40; i--) {
+ const row = parseRow(lines[i])
+ if (!row) continue
+ rows.unshift(row)
+ if (/^\s*[❯›>]?\s*\d+\.\s+\[/.test(lines[i])) checkbox = true
+ if (row.number === '1') { start = i; break }
+ }
+ if (start < 0 || rows.length === 0) return null
+
+ // The question is the nearest real text line above the rows. The dialog paints it between its header
+ // and its rows — `[tab bar | header chip] · blank · question · blank · rows` — so those, and a rule,
+ // are the TOP of this frame. Stop there, never skip past: mid-repaint the question line can be blank
+ // for one capture, and walking on would pick up the PREVIOUS question still sitting in scrollback and
+ // pair a stale title with the live options. An empty result just means "look again next tick".
+ let question = ''
+ for (let i = start - 1; i >= 0 && start - i <= 12; i--) {
+ const line = lines[i].trim()
+ if (!line) continue
+ if (/[←→]/.test(line) || /^[☐☒✔✓]/.test(line) || /^[─━-]{6,}$/.test(line)) break
+ question = line
+ break
+ }
+
+ const answerable = rows.filter((r) => !CHAT_ROW.test(r.label) && !TYPE_ROW.test(r.label))
+ return {
+ kind: 'question',
+ question,
+ rows: answerable,
+ multi: checkbox,
+ typeRow: rows.find((r) => TYPE_ROW.test(r.label)) ?? null,
+ }
+}
+
+/** Match an answer to a row. The device stores option labels in an 80-byte buffer, so a long label comes
+ * back truncated — prefix matches count, in both directions. */
+export function matchRow(rows: QuestionRow[], answer: string): QuestionRow | null {
+ const a = norm(answer)
+ if (!a) return null
+ return rows.find((r) => norm(r.label) === a)
+ ?? (a.length >= 3 ? rows.find((r) => norm(r.label).startsWith(a)) ?? rows.find((r) => a.startsWith(norm(r.label)) && norm(r.label).length >= 3) : undefined)
+ ?? null
+}
+
+/** Pick the answer for the question the dialog is currently showing: by its own text, else positionally. */
+export function pickAnswer(answers: Record<string, string>, question: string, used: Set<string>): { key: string; value: string } | null {
+ const entries = Object.entries(answers)
+ const q = norm(question)
+ const byText = entries.find(([k]) => norm(k) === q)
+ ?? (q.length >= 6 ? entries.find(([k]) => norm(k).startsWith(q) || q.startsWith(norm(k))) : undefined)
+ if (byText && !used.has(byText[0])) return { key: byText[0], value: byText[1] }
+ const next = entries.find(([k]) => !used.has(k))
+ return next ? { key: next[0], value: next[1] } : null
+}
+
+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>
+ /** Injected for tests. */
+ wait?: (ms: number) => Promise<void>
+}
+
+export interface QuestionAnswerPayload {
+ requestId?: string
+ sessionId?: string
+ agentId?: string
+ answers?: Record<string, string>
+}
+
+/**
+ * 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.
+ */
+export class AskQuestionController {
+ private pending = new Map<string, string>() // requestId → sessionId
+ private driving = new Set<string>() // sessionIds currently keying a dialog
+
+ constructor(private readonly deps: AskQuestionDeps) {}
+
+ /** Remember which session a mirrored question belongs to (the device may answer minutes later). */
+ remember(requestId: string, sessionId: string): void {
+ if (!requestId) return
+ if (this.pending.size > 64) this.pending.delete(this.pending.keys().next().value as string)
+ this.pending.set(requestId, sessionId)
+ }
+
+ async answer(payload: QuestionAnswerPayload): Promise<boolean> {
+ const requestId = payload.requestId ?? ''
+ const sessionId = payload.sessionId || payload.agentId || this.pending.get(requestId) || ''
+ const answers = payload.answers && typeof payload.answers === 'object' ? payload.answers : null
+ if (!sessionId || !answers || Object.keys(answers).length === 0) {
+ 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`)
+ return false
+ }
+ if (this.driving.has(sessionId)) return false
+ this.driving.add(sessionId)
+ try {
+ const ok = await this.drive(pane, 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)
+ }
+ }
+
+ /** 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> {
+ const wait = this.deps.wait ?? sleep
+ const used = new Set<string>()
+ let lastQuestion = ''
+ let repeats = 0
+ let answered = 0
+
+ for (let step = 0; step < MAX_STEPS; step++) {
+ const capture = await this.deps.capture(pane, 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
+ }
+ // 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
+ // second answer for it.
+ if (view.question && view.question === lastQuestion) {
+ if (++repeats >= 2) { console.warn(`[question] dialog stuck on "${view.question.slice(0, 60)}"`); return false }
+ await wait(STEP_MS)
+ continue
+ }
+ repeats = 0
+ lastQuestion = view.question
+
+ // Out of answers with the dialog still up = a multi-QUESTION dialog whose next question the device
+ // hasn't been shown yet. Leave it open: the watcher pushes that one and the device answers it next.
+ const picked = pickAnswer(answers, view.question, used)
+ if (!picked) return answered > 0
+ used.add(picked.key)
+ answered++
+
+ if (view.multi) {
+ // Device joins the selected labels with ", " (q_done_tap).
+ const labels = picked.value.split(',').map((s) => s.trim()).filter(Boolean)
+ let toggled = 0
+ for (const label of labels) {
+ const row = matchRow(view.rows, label)
+ if (!row || row.checked) continue
+ await this.deps.sendKey(pane, row.number)
+ 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
+ await wait(STEP_MS)
+ continue
+ }
+
+ const row = matchRow(view.rows, picked.value)
+ if (row) {
+ await this.deps.sendKey(pane, row.number) // selects AND submits this question
+ 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)
+ await wait(STEP_MS)
+ }
+ return false
+ }
+
+ /** True while a dialog is being keyed — the watcher pauses so a half-driven dialog isn't re-announced. */
+ isDriving(sessionId: string): boolean {
+ return this.driving.has(sessionId)
+ }
+
+ /** 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)
+ await wait(TEXT_MS)
+ await this.deps.sendText(pane, text)
+ await wait(TEXT_MS)
+ await this.deps.sendKey(pane, 'Enter')
+ }
+}
+
+// ── watching a pane for an open question ─────────────────────────────────────────────────────────
+
+export interface QuestionWatcherDeps {
+ getSession: (sessionId: string) => RegisteredSession | undefined
+ capture: (pane: 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). */
+ onQuestion: (sessionId: string, requestId: string, questions: ShapedQuestion[]) => void
+ /** True while that session's dialog is being keyed by an answer already in flight. */
+ isDriving?: (sessionId: string) => boolean
+}
+
+const POLL_MS = 1500
+const QUESTION_ENGINES = new Set<AgentEngine>(['claude', 'commandcode', 'devin', 'hermes', 'opencode'])
+
+/** Does this engine ever paint a question dialog? Callers use it to decide whether to watch its pane. */
+export function pollsQuestions(engine: AgentEngine): boolean {
+ return QUESTION_ENGINES.has(engine)
+}
+
+/**
+ * The OUT half. The obvious source — the transcript's AskUserQuestion `tool_use` line — is useless here:
+ * the CLI does not flush that line until the question has been ANSWERED (its JSONL `timestamp` is the
+ * message's creation time, not its write time), so a device would only ever learn about a question after
+ * it no longer exists. The dialog itself, on the other hand, is on screen the whole time it is waiting.
+ *
+ * So while a turn is open we read the pane. This also means the question survives an adapter restart and
+ * re-announces to a device that attaches mid-question — neither of which a one-shot event could do.
+ */
+export class QuestionWatcher {
+ private timers = new Map<string, NodeJS.Timeout>()
+ private last = new Map<string, string>() // sessionId → fingerprint of the announced question
+ private readonly blocked = new Map<string, string>()
+
+ constructor(private readonly deps: QuestionWatcherDeps) {}
+
+ /** Poll this session's pane while its turn is open (called on turn_started). */
+ start(sessionId: string): void {
+ if (this.timers.has(sessionId)) return
+ 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
+ this.timers.set(sessionId, setInterval(() => { void this.tick(sessionId) }, POLL_MS))
+ }
+
+ stop(sessionId: string): void {
+ const timer = this.timers.get(sessionId)
+ if (timer) { clearInterval(timer); this.timers.delete(sessionId) }
+ this.last.delete(sessionId)
+ }
+
+ stopAll(): void {
+ for (const timer of this.timers.values()) clearInterval(timer)
+ this.timers.clear()
+ this.last.clear()
+ }
+
+ /** A device (re)joined: forget what we announced so an open question is pushed again. */
+ reset(): void {
+ this.last.clear()
+ }
+
+ private async tick(sessionId: string): Promise<void> {
+ const pane = this.deps.getSession(sessionId)?.tmuxPane
+ if (!pane) { 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' : ''
+ if (blocked !== (this.blocked.get(sessionId) ?? '')) {
+ this.blocked.set(sessionId, blocked)
+ console.log(`[question] ${sessionId.slice(0, 8)} watcher ${blocked ? `paused · ${blocked}` : 'polling'}`)
+ }
+ if (blocked) return
+ const engine = this.deps.getSession(sessionId)?.engine ?? 'claude'
+ const view = parseEngineQuestionPane(engine, await this.deps.capture(pane, 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
+ }
+ const fingerprint = `${view.question}|${view.rows.map((r) => r.label).join('|')}|${view.multi}`
+ if (this.last.get(sessionId) === fingerprint) return
+ this.last.set(sessionId, fingerprint)
+ // A pane-derived question has no tool_use id. The key only has to round-trip through the device and
+ // back (the answer is keyed into the pane, not matched to a tool call), so the question's own text
+ // serves as both — and the device dedups a repeated push by this id.
+ this.deps.onQuestion(sessionId, `q_${hash(sessionId + fingerprint)}`, [{
+ key: view.question,
+ q: view.question,
+ options: view.rows.map((r) => r.label),
+ multi: view.multi,
+ }])
+ }
+}
+
+function hash(value: string): string {
+ let h = 0x811c9dc5
+ for (let i = 0; i < value.length; i++) h = Math.imul(h ^ value.charCodeAt(i), 0x01000193) >>> 0
+ return h.toString(16).padStart(8, '0')
+}
diff --git a/cli/src/lib/commandcodeModel.spec.ts b/cli/src/lib/commandcodeModel.spec.ts
new file mode 100644
index 000000000..e7d450d3d
--- /dev/null
+++ b/cli/src/lib/commandcodeModel.spec.ts
@@ -0,0 +1,166 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, rmSync, writeFileSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import type { RegisteredSession } from './registry.js'
+
+/**
+ * Command Code agents were DISPLAY-ONLY between 2026-07-30 and CLI 1.6.0: switching had been built and
+ * reverted because the /model dialog ignored typed input, so it could only be arrow-driven, and a 49-row
+ * picker stalled the device's the device UI task into a watchdog reset. 1.6.0 added `--list-models` and gave
+ * `/model` and `/effort` arguments, so the picker is back — behind a version gate, and with the chip
+ * still required to name what the agent is actually running: model AND reasoning level.
+ */
+let commandcodeHome = ''
+
+async function loadRuntimeProfile() {
+ vi.resetModules()
+ process.env.COMMANDCODE_HOME = commandcodeHome
+ return import('./runtimeProfile.js')
+}
+
+const session = (): RegisteredSession => ({
+ sessionId: 'session:1',
+ engine: 'commandcode',
+ launcherId: 'h1',
+ agentId: 'h1',
+ boundAt: 0,
+ transcriptPath: '/tmp/session.jsonl',
+ projectDir: 'tmp',
+ cwd: '/tmp',
+ tmuxPane: '%1',
+ source: null,
+ title: null,
+ model: null,
+ cliVersion: null,
+ processIdentity: null,
+ registeredAt: 1,
+ updatedAt: 1,
+ lastHookAt: 1,
+ lastTranscriptAt: 1,
+})
+
+/** An assistant line as Command Code writes it: the model is top level, as a full gateway id. */
+const assistantLine = (model: string): string =>
+ JSON.stringify({ type: 'message', model, message: { role: 'assistant', content: [{ type: 'text', text: 'hi' }] } })
+
+/** Its global config — the ONLY place the reasoning level is recorded, keyed by full id. */
+const writeConfig = (config: unknown): void =>
+ writeFileSync(join(commandcodeHome, 'config.json'), JSON.stringify(config))
+
+describe('a Command Code agent', () => {
+ beforeEach(() => {
+ commandcodeHome = mkdtempSync(join(tmpdir(), 'adapter-commandcode-'))
+ })
+
+ afterEach(() => {
+ rmSync(commandcodeHome, { recursive: true, force: true })
+ })
+
+ it('shows the running model and its configured reasoning level', async () => {
+ const { parseRuntimeProfile, RuntimeProfileManager } = await loadRuntimeProfile()
+ writeConfig({
+ model: 'deepseek/deepseek-v4-flash',
+ reasoningEffort: { 'deepseek/deepseek-v4-flash': 'high' },
+ })
+ const manager = new RuntimeProfileManager()
+ const target = session()
+ manager.ingest(target, assistantLine('deepseek/deepseek-v4-flash'))
+ await manager.ingestConfig(target, true)
+
+ const profile = parseRuntimeProfile(manager.selectedModel(target))
+ // Short name, not "deepseek/deepseek-v4-flash": the device labels by splitting on -/_ and never "/",
+ // so a vendor prefix reads as "Deepseek/deepseek V4 Flash" on the round screen.
+ expect(profile?.model).toBe('deepseek-v4-flash')
+ expect(profile?.effort).toBe('high')
+ })
+
+ it('keeps the level after the next assistant line', async () => {
+ // Regression: the transcript path used to stamp effort='auto' on every line, wiping the configured
+ // level a second after it was read, so the chip flipped back to Auto on the next reply.
+ const { parseRuntimeProfile, RuntimeProfileManager } = await loadRuntimeProfile()
+ writeConfig({ model: 'x/y', reasoningEffort: { 'moonshotai/kimi-k3': 'medium' } })
+ const manager = new RuntimeProfileManager()
+ const target = session()
+ manager.ingest(target, assistantLine('moonshotai/kimi-k3'))
+ await manager.ingestConfig(target, true)
+ manager.ingest(target, assistantLine('moonshotai/kimi-k3'))
+
+ expect(parseRuntimeProfile(manager.selectedModel(target))?.effort).toBe('medium')
+ })
+
+ it('falls back to Auto when the model has no level set', async () => {
+ const { parseRuntimeProfile, RuntimeProfileManager } = await loadRuntimeProfile()
+ writeConfig({ model: 'deepseek/deepseek-v4-flash', reasoningEffort: { 'qwen/qwen3.7-plus': 'low' } })
+ const manager = new RuntimeProfileManager()
+ const target = session()
+ manager.ingest(target, assistantLine('deepseek/deepseek-v4-flash'))
+ await manager.ingestConfig(target, true)
+
+ expect(parseRuntimeProfile(manager.selectedModel(target))?.effort).toBe('auto')
+ })
+
+ it('names the config model before the agent has answered once', async () => {
+ const { parseRuntimeProfile, RuntimeProfileManager } = await loadRuntimeProfile()
+ writeConfig({ model: 'moonshotai/kimi-k3', reasoningEffort: {} })
+ const manager = new RuntimeProfileManager()
+ const target = session()
+ await manager.ingestConfig(target, true)
+
+ // A fresh agent has no transcript line to read; the config's model is what it will run.
+ expect(parseRuntimeProfile(manager.selectedModel(target))?.model).toBe('kimi-k3')
+ })
+
+ it('re-reads the level when the model changes', async () => {
+ // The level is stored PER MODEL. Switching to a model with no level of its own kept showing the
+ // previous model's — the chip read "Kimi K3 · High" when Kimi K3 has no level set at all.
+ const { parseRuntimeProfile, RuntimeProfileManager } = await loadRuntimeProfile()
+ writeConfig({ model: 'deepseek/deepseek-v4-flash', reasoningEffort: { 'deepseek/deepseek-v4-flash': 'high' } })
+ const manager = new RuntimeProfileManager()
+ const target = session()
+ manager.ingest(target, assistantLine('deepseek/deepseek-v4-flash'))
+ await manager.ingestConfig(target, true)
+ expect(parseRuntimeProfile(manager.selectedModel(target))?.effort).toBe('high')
+
+ manager.ingest(target, assistantLine('moonshotai/kimi-k3'))
+ await new Promise((resolve) => setTimeout(resolve, 20)) // the re-read ingest() fires is async
+ const profile = parseRuntimeProfile(manager.selectedModel(target))
+ expect(profile?.model).toBe('kimi-k3')
+ expect(profile?.effort).toBe('auto')
+ })
+
+ it('offers nothing to pick when the catalogue cannot be read', async () => {
+ // Deliberately hide the CLI: a catalogue that cannot be read must leave the device with nothing to
+ // open rather than a half-list — and this test must not depend on what is installed on the computer.
+ const realPath = process.env.PATH
+ process.env.PATH = commandcodeHome
+ try {
+ const { RuntimeProfileManager } = await loadRuntimeProfile()
+ const manager = new RuntimeProfileManager()
+ const target = session()
+ manager.ingest(target, assistantLine('moonshotai/kimi-k3'))
+ await expect(manager.modelsForSession(target)).resolves.toEqual([])
+ } finally {
+ process.env.PATH = realPath
+ }
+ })
+
+ it('is never switchable, whatever the CLI version says', async () => {
+ // Switching is Claude and Codex only (owner, 2026-07-31). 1.6.0 does take `/model` as a plain command,
+ // so the driver would work — the gate is policy, not capability, which is why version is irrelevant.
+ const { supportsNativeRuntimeControl } = await loadRuntimeProfile()
+ expect(supportsNativeRuntimeControl({ ...session(), cliVersion: '1.6.0' })).toBe(false)
+ expect(supportsNativeRuntimeControl({ ...session(), cliVersion: '1.5.0' })).toBe(false)
+ expect(supportsNativeRuntimeControl({ ...session(), cliVersion: null })).toBe(false)
+ })
+
+ it('keeps the transcript schema version out of the CLI version', async () => {
+ const { RuntimeProfileManager } = await loadRuntimeProfile()
+ const manager = new RuntimeProfileManager()
+ const target = session()
+ // Command Code stamps `"version": 3` on its session header — a SCHEMA number. Reading it as a CLI
+ // version would invent a "3.0.0" build that no gate should ever act on.
+ manager.ingest(target, JSON.stringify({ type: 'session', version: 3, id: 'x', cwd: '/tmp' }))
+ expect(target.cliVersion).toBeNull()
+ })
+})
diff --git a/cli/src/lib/commander.spec.ts b/cli/src/lib/commander.spec.ts
new file mode 100644
index 000000000..4017d3d96
--- /dev/null
+++ b/cli/src/lib/commander.spec.ts
@@ -0,0 +1,375 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, rmSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import { CommanderMirror, type CommanderFrame } from './commander.js'
+import type { LiveEvent } from './normalize.js'
+
+let dataDir = ''
+
+describe('CommanderMirror recap events', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ dataDir = mkdtempSync(join(tmpdir(), 'adapter-commander-'))
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ rmSync(dataDir, { recursive: true, force: true })
+ })
+
+ it('fans a TodoWrite out to the device as a todo list, whatever engine produced it', () => {
+ // The device renders the checklist from `todos:[{c,s}]` folded onto a processing frame — nothing else
+ // carries it. Every engine reaches this through the SAME shape (`input.todos[{content,status}]`), which
+ // is why an engine whose planning tool is named differently silently loses its checklist: hermes calls
+ // its tool `todo`, and until that was mapped the device showed no list at all for it.
+ const deviceFrames: CommanderFrame[] = []
+ const mirror = new CommanderMirror({
+ send: (frame) => deviceFrames.push(frame),
+ sendWeb: () => {},
+ hasDevice: () => true,
+ summarize: async () => null,
+ dataDir,
+ })
+
+ mirror.ingest([
+ { type: 'turn_started', payload: { userMessage: 'plan it' } },
+ {
+ type: 'tool_start',
+ payload: {
+ id: 't1',
+ tool: 'TodoWrite',
+ input: { todos: [
+ { content: 'In hello', status: 'completed' },
+ { content: 'In world', status: 'in_progress' },
+ { content: 'Tổng kết', status: 'pending' },
+ ] },
+ },
+ },
+ ] as LiveEvent[], 'session-todos')
+
+ const withTodos = deviceFrames.filter((f) => Array.isArray((f.payload as { todos?: unknown }).todos))
+ expect(withTodos).toHaveLength(1)
+ expect((withTodos[0].payload as { todos: Array<{ c: string; s: string }> }).todos).toEqual([
+ { c: 'In hello', s: 'completed' },
+ { c: 'In world', s: 'in_progress' },
+ { c: 'Tổng kết', s: 'pending' },
+ ])
+ })
+
+ it('keeps the todo list on the busy tile through the heartbeat', () => {
+ // The device clears a busy tile on a watchdog; the 5s heartbeat has to re-assert the SAME list or the
+ // checklist would vanish mid-turn while the agent is still working on it.
+ const deviceFrames: CommanderFrame[] = []
+ const mirror = new CommanderMirror({
+ send: (frame) => deviceFrames.push(frame),
+ sendWeb: () => {},
+ hasDevice: () => true,
+ summarize: async () => null,
+ dataDir,
+ })
+ mirror.ingest([
+ { type: 'turn_started', payload: { userMessage: 'plan it' } },
+ { type: 'tool_start', payload: { id: 't1', tool: 'TodoWrite', input: { todos: [{ content: 'A', status: 'pending' }] } } },
+ ] as LiveEvent[], 'session-hb')
+
+ deviceFrames.length = 0
+ expect(mirror.heartbeat('session-hb')).toBe(true)
+ expect(deviceFrames.some((f) => Array.isArray((f.payload as { todos?: unknown }).todos))).toBe(true)
+ })
+
+ it('feeds the device its sub-agent list, running then finished', () => {
+ // The firmware has always been able to draw this list (ui_project_set_agents) and never received one:
+ // nothing in the adapter, the node or the backend emitted `kind:'agents'`, for any engine. It renders
+ // each row verbatim, so the text and colour are decided here — `›` while running (the device scrolls
+ // that row into view), `✓ … · Ns` once done.
+ const deviceFrames: CommanderFrame[] = []
+ const mirror = new CommanderMirror({
+ send: (frame) => deviceFrames.push(frame),
+ sendWeb: () => {},
+ hasDevice: () => true,
+ summarize: async () => null,
+ dataDir,
+ })
+
+ mirror.ingest([
+ { type: 'turn_started', payload: { userMessage: 'delegate it' } },
+ { type: 'tool_start', payload: { id: 'a1', tool: 'Task', input: { description: 'audit the parser' } } },
+ // claude's own tool is named `Agent`, not `Task` — both must open a row (measured on a live turn).
+ { type: 'tool_start', payload: { id: 'a2', tool: 'Agent', input: { description: 'write the tests' } } },
+ ] as LiveEvent[], 'session-agents')
+
+ const rowsOf = (): Array<{ text: string; color: string }> => {
+ const last = deviceFrames.filter((f) => f.payload.kind === 'agents').pop()
+ return (last?.payload.agents ?? []) as Array<{ text: string; color: string }>
+ }
+ expect(rowsOf().map((r) => r.text)).toEqual(['› audit the parser', '› write the tests'])
+
+ mirror.ingest([
+ { type: 'tool_end', payload: { id: 'a1', tool: 'Task', output: 'ok', isError: false, summary: 'done', durationSeconds: 12 } },
+ ] as LiveEvent[], 'session-agents')
+
+ expect(rowsOf().map((r) => r.text)).toEqual(['✓ audit the parser · 12s', '› write the tests'])
+ expect(rowsOf()[0].color).not.toBe(rowsOf()[1].color) // finished and running must be tellable apart
+ })
+
+ it('carries a still-RUNNING sub-agent into the next turn and drops the finished ones', () => {
+ // Finished rows must not sit above "Working…" on the next turn — but a running one is not finished
+ // just because the user typed again: claude's async sub-agents outlive the turn that spawned them,
+ // and cursor announces a Task through its HOOK ~60ms BEFORE the turn opens (measured live).
+ const deviceFrames: CommanderFrame[] = []
+ const mirror = new CommanderMirror({
+ send: (frame) => deviceFrames.push(frame),
+ sendWeb: () => {},
+ hasDevice: () => true,
+ summarize: async () => null,
+ dataDir,
+ })
+ mirror.ingest([
+ { type: 'turn_started', payload: { userMessage: 'one' } },
+ { type: 'tool_start', payload: { id: 'a1', tool: 'Task', input: { description: 'first' } } },
+ { type: 'tool_end', payload: { id: 'a1', tool: 'Task', output: 'done', isError: false, summary: '' } },
+ { type: 'tool_start', payload: { id: 'a2', tool: 'Task', input: { description: 'still going' } } },
+ { type: 'turn_started', payload: { userMessage: 'two' } },
+ { type: 'tool_start', payload: { id: 'b1', tool: 'Task', input: { description: 'second' } } },
+ ] as LiveEvent[], 'session-agents-2')
+
+ const last = deviceFrames.filter((f) => f.payload.kind === 'agents').pop()
+ expect((last?.payload.agents as Array<{ text: string }>).map((r) => r.text)).toEqual(['› still going', '› second'])
+ })
+
+ it('emits done before summary when recap succeeds', async () => {
+ const deviceFrames: CommanderFrame[] = []
+ const webFrames: Record<string, unknown>[] = []
+ const mirror = new CommanderMirror({
+ send: (frame) => deviceFrames.push(frame),
+ sendWeb: (frame) => webFrames.push(frame),
+ hasDevice: () => true,
+ summarize: async () => 'Short recap\n\nLong body',
+ dataDir,
+ })
+
+ mirror.ingest([
+ { type: 'turn_started', payload: { userMessage: 'what happened?' } },
+ { type: 'text_delta', payload: { content: 'The assistant answered.' } },
+ { type: 'turn_ended', payload: {} },
+ ] as LiveEvent[], 'session-1')
+
+ await vi.runAllTimersAsync()
+ await Promise.resolve()
+
+ expect(deviceFrames.map((f) => f.payload.kind)).toEqual([
+ 'processing',
+ 'processing',
+ 'done',
+ 'summary',
+ ])
+ expect(deviceFrames.at(-1)?.payload).toEqual({ kind: 'summary', text: 'Long body', recap: 'Short recap' })
+ expect(webFrames.map((f) => f.type)).toEqual(['turn_summary_pending', 'turn_summary'])
+ })
+
+ it('runs the recap once when a turn closes twice (Stop hook + watcher race)', async () => {
+ const deviceFrames: CommanderFrame[] = []
+ let summarizeCalls = 0
+ const mirror = new CommanderMirror({
+ send: (frame) => deviceFrames.push(frame),
+ sendWeb: () => {},
+ hasDevice: () => true,
+ summarize: async () => { summarizeCalls++; return 'Recap\n\nBody' },
+ dataDir,
+ })
+
+ mirror.ingest([
+ { type: 'turn_started', payload: { userMessage: 'who won?' } },
+ { type: 'text_delta', payload: { content: 'Spain won.' } },
+ { type: 'turn_ended', payload: {} },
+ ] as LiveEvent[], 'session-race')
+ // Second turn_ended for the SAME turn (the other of hook/watcher) — must NOT start a second recap.
+ mirror.ingest([{ type: 'turn_ended', payload: {} }] as LiveEvent[], 'session-race')
+
+ await vi.runAllTimersAsync()
+ await Promise.resolve()
+
+ expect(summarizeCalls).toBe(1)
+ expect(deviceFrames.filter((f) => f.payload.kind === 'summary')).toHaveLength(1)
+ })
+
+ it('renders normalized Codex Task and child tools through the same device cards as Claude', () => {
+ const deviceFrames: CommanderFrame[] = []
+ const mirror = new CommanderMirror({
+ send: (frame) => deviceFrames.push(frame),
+ sendWeb: () => {},
+ hasDevice: () => true,
+ summarize: async () => null,
+ dataDir,
+ })
+
+ mirror.ingest([
+ {
+ type: 'tool_start',
+ payload: {
+ id: 'task-1',
+ tool: 'Task',
+ input: { subagent_type: 'explorer', description: 'Inspect the API' },
+ },
+ },
+ {
+ type: 'tool_start',
+ payload: {
+ id: 'child-1',
+ tool: 'Bash',
+ input: { command: 'rg TODO' },
+ parentToolUseId: 'task-1',
+ },
+ },
+ ], 'session-codex')
+
+ expect(deviceFrames.map((frame) => frame.payload)).toEqual([
+ {
+ kind: 'tool',
+ text: 'Task',
+ recap: 'Inspect the API',
+ color: '#d19a66',
+ detail: 'subagent_type: explorer · description: Inspect the API',
+ },
+ // …and the same Task also opens a row in the device's sub-agent list, which is a separate surface
+ // from the tool card: the card scrolls away with the feed, the list stays above "Working…".
+ { kind: 'agents', agents: [{ text: '› Inspect the API', color: '#ff9d00' }] },
+ {
+ kind: 'tool',
+ text: 'Bash',
+ recap: 'rg TODO',
+ color: '#e5c07b',
+ detail: 'command: rg TODO',
+ },
+ ])
+ })
+
+ it('heartbeat re-emits processing while a turn is open, nothing when idle', () => {
+ const deviceFrames: CommanderFrame[] = []
+ const mirror = new CommanderMirror({
+ send: (frame) => deviceFrames.push(frame),
+ sendWeb: () => {},
+ hasDevice: () => true,
+ summarize: async () => null,
+ dataDir,
+ })
+
+ // No such session → idle, emits nothing.
+ expect(mirror.heartbeat('nope')).toBe(false)
+
+ mirror.ingest([{ type: 'turn_started', payload: { userMessage: 'hi' } }] as LiveEvent[], 'session-hb')
+ deviceFrames.length = 0 // drop the turn_started processing frame
+
+ // Turn open → heartbeat re-asserts Processing and reports busy.
+ expect(mirror.heartbeat('session-hb')).toBe(true)
+ expect(deviceFrames).toEqual([{ type: 'commander_event', agentId: 'session-hb', dbSessionId: 'session-hb', payload: { kind: 'processing', text: 'Processing' } }])
+ })
+
+ it('heartbeat re-emits "Summarizing…" during the summarize window', async () => {
+ const deviceFrames: CommanderFrame[] = []
+ let releaseSummarize: (v: string) => void = () => {}
+ const mirror = new CommanderMirror({
+ send: (frame) => deviceFrames.push(frame),
+ sendWeb: () => {},
+ hasDevice: () => true,
+ summarize: () => new Promise<string>((resolve) => { releaseSummarize = resolve }), // hangs until released
+ dataDir,
+ })
+
+ mirror.ingest([
+ { type: 'turn_started', payload: { userMessage: 'q' } },
+ { type: 'text_delta', payload: { content: 'answer' } },
+ { type: 'turn_ended', payload: {} },
+ ] as LiveEvent[], 'session-sum')
+ await Promise.resolve() // let onTurnEnded kick off the (hanging) summarize → summarizing=true
+ deviceFrames.length = 0
+
+ // Turn closed but summarize in flight → heartbeat re-asserts Summarizing… and still reports busy.
+ expect(mirror.heartbeat('session-sum')).toBe(true)
+ expect(deviceFrames.map((f) => f.payload)).toEqual([{ kind: 'processing', text: 'Summarizing…' }])
+
+ releaseSummarize('recap\n\nbody')
+ await vi.runAllTimersAsync()
+ await Promise.resolve()
+
+ // Summary done → idle → heartbeat emits nothing and reports not busy.
+ deviceFrames.length = 0
+ expect(mirror.heartbeat('session-sum')).toBe(false)
+ expect(deviceFrames).toEqual([])
+ })
+
+ it('says so in the log when a turn closes that was never opened', async () => {
+ // The real failure this guards: a first prompt landing while the session is being attached has
+ // its turn_started folded into history, so the live turn's close arrives with turnOpen false.
+ // That used to return in silence — a whole turn produced no recap and no trace of why.
+ const errors: string[] = []
+ const error = vi.spyOn(console, 'error').mockImplementation((line: unknown) => { errors.push(String(line)) })
+ const deviceFrames: CommanderFrame[] = []
+ let summarizeCalls = 0
+ const mirror = new CommanderMirror({
+ send: (frame) => deviceFrames.push(frame),
+ sendWeb: () => {},
+ hasDevice: () => true,
+ summarize: async () => { summarizeCalls++; return 'Recap\n\nBody' },
+ dataDir,
+ })
+
+ mirror.ingest([{ type: 'turn_ended', payload: {} }] as LiveEvent[], 'session-orphan')
+ await vi.runAllTimersAsync()
+
+ expect(summarizeCalls).toBe(0)
+ expect(deviceFrames).toEqual([])
+ expect(errors.join('\n')).toContain('turn-end · DROPPED')
+ error.mockRestore()
+ })
+
+ it('stays silent for the ordinary duplicate close', async () => {
+ // Every turn closes twice (watcher + Stop hook). That path must not start logging.
+ const errors: string[] = []
+ const error = vi.spyOn(console, 'error').mockImplementation((line: unknown) => { errors.push(String(line)) })
+ const mirror = new CommanderMirror({
+ send: () => {},
+ sendWeb: () => {},
+ hasDevice: () => true,
+ summarize: async () => 'Recap\n\nBody',
+ dataDir,
+ })
+
+ mirror.ingest([
+ { type: 'turn_started', payload: { userMessage: 'q' } },
+ { type: 'text_delta', payload: { content: 'answer' } },
+ { type: 'turn_ended', payload: {} },
+ { type: 'turn_ended', payload: {} },
+ ] as LiveEvent[], 'session-dup')
+ await vi.runAllTimersAsync()
+
+ expect(errors.join('\n')).not.toContain('DROPPED')
+ error.mockRestore()
+ })
+})
+
+describe('device frames address the agent, not the session', () => {
+ beforeEach(() => { vi.useFakeTimers(); dataDir = mkdtempSync(join(tmpdir(), 'adapter-commander-id-')) })
+ afterEach(() => { vi.useRealTimers(); rmSync(dataDir, { recursive: true, force: true }) })
+
+ it('sends agentId = the agent and dbSessionId = the engine session', () => {
+ // These two are different values now. The device routes tiles by `agentId` (stable across a `/clear`)
+ // and keeps `dbSessionId` to echo back when cancelling a turn; the backend also keys its voice queue
+ // on dbSessionId, so it must stay the engine session id.
+ const frames: CommanderFrame[] = []
+ const mirror = new CommanderMirror({
+ send: (f) => frames.push(f),
+ sendWeb: () => {},
+ hasDevice: () => true,
+ summarize: async () => null,
+ agentIdFor: (sessionId) => (sessionId === 'engine-session' ? 'agent-uuid' : undefined),
+ dataDir,
+ })
+ mirror.ingest([
+ { type: 'turn_started', payload: { userMessage: 'go' } },
+ ] as LiveEvent[], 'engine-session')
+
+ expect(frames[0]).toMatchObject({ agentId: 'agent-uuid', dbSessionId: 'engine-session' })
+ })
+})
diff --git a/cli/src/lib/commander.ts b/cli/src/lib/commander.ts
new file mode 100644
index 000000000..8745debf6
--- /dev/null
+++ b/cli/src/lib/commander.ts
@@ -0,0 +1,668 @@
+/**
+ * CommanderMirror — derives the paired hardware device's `commander_event` stream from the same LiveEvent
+ * stream the web receives, and produces the per-turn RECAP the way the hosted runtime does:
+ *
+ * turn_started → {kind:'processing'} (tile busy)
+ * tool_start → {kind:'tool', text, recap, color, detail}
+ * tool_start TodoWrite → + {kind:'processing', todos:[{c,s}]} (checklist)
+ * tool_start Task/Agent → + {kind:'agents', agents:[{text,color}]} (live sub-agent list)
+ * subagent_finished → + {kind:'agents', …} with that row ticked off
+ * turn_ended (device on) → {kind:'processing', text:'Summarizing…'} then, once the LLM one-shot
+ * returns, {kind:'summary', text:body, recap} (persisted per session)
+ * turn_ended (no device) → nothing (device-gated; the summary map is left untouched)
+ * turn_ended (empty text) → {kind:'done'} (clear busy)
+ *
+ * Every frame carries top-level `agentId` + `dbSessionId` (= the tmux session id). The recap
+ * (`summarizeTurnText`) is injected so it's unit-testable with a stub. Mirrors the hosted runtime's
+ * device-gated recap (recap.ts / manager.ts triggerTurnRecap / websocket.ts handleBrainSummaryEvent).
+ */
+
+import { mkdirSync, readFileSync, writeFileSync } from 'fs'
+import { join } from 'path'
+import type { LastTurnText, LiveEvent } from './normalize.js'
+
+export type CommanderFrame = {
+ type: 'commander_event'
+ agentId: string
+ dbSessionId: string
+ payload: Record<string, unknown>
+}
+
+export interface CommanderMirrorOpts {
+ /** Device-audience frame (commander_event cards). */
+ send: (frame: CommanderFrame) => void
+ /** Web-audience frame (turn_summary_pending / turn_summary — the "Summarizing…" indicator). */
+ sendWeb: (frame: Record<string, unknown>) => void
+ hasDevice: () => boolean
+ /** True while a device is ACTIVELY rendering this machine (vs attached-but-background under multi-attach).
+ * Gates the live turn-card STREAM; the turn-done `summary` card ignores it so a background machine still
+ * badges. Omitted → defaults to hasDevice (single-machine firmware: attached == active, streams as before). */
+ active?: () => boolean
+ summarize: (text: string, signal?: AbortSignal, userMessage?: string, sessionId?: string) => Promise<string | null>
+ /** Agent display name for a sessionId — rides the summary's outer frame so a BACKGROUND machine's device
+ * notification shows the agent name on line 2 (its tile isn't loaded). */
+ nameFor?: (sessionId: string) => string | undefined
+ readLastTurn?: (sessionId: string) => Promise<LastTurnText | null>
+ /** Engine session id → the AGENT that owns it. Frames are addressed to the agent (stable across a
+ * `/clear` rotation); `dbSessionId` stays the engine session, which is what the device echoes back to
+ * cancel a turn and what the backend keys its voice queue on. */
+ agentIdFor?: (sessionId: string) => string | undefined
+ dataDir: string
+ recapForce?: boolean
+}
+
+interface SessionState {
+ lastAssistantText: string
+ /** The user's prompt for the current turn (from turn_started) — fed to the recap so it leads with
+ * the direct answer to what was asked. */
+ lastUserMessage: string
+ turnOpen: boolean
+ /** Has a turn_started ever been seen for this session? Separates the normal duplicate-close
+ * (watcher and Stop hook race, every turn) from a close whose turn was never opened at all. */
+ everOpened: boolean
+ summarizing: boolean
+ lastTool: Record<string, unknown> | null
+ lastTodos: Array<{ c: string; s: string }> | null
+ /** Sub-agents this turn spawned, in the order they started — the device's list above "Working…". */
+ agents: Array<{ id: string; desc: string; startedAt: number; doneMs: number | null; carried?: true }>
+ /** A turn_ended is being HELD because sub-agents this turn spawned are still running (see below). */
+ endPending: boolean
+ /** Fires the held turn-end once the last sub-agent has finished AND the wrap-up text has stopped. */
+ endSettle: NodeJS.Timeout | null
+ /** Backstop: a sub-agent that never reports back must not cost the turn its recap. */
+ endDeadline: NodeJS.Timeout | null
+ abort: AbortController | null
+}
+
+interface TodoInput {
+ todos?: Array<{ content?: string; subject?: string; status?: string }>
+}
+
+const MAX_PART = 2000
+
+// Stable per-tool colors (device renders the tool name in this color); hash fallback for others.
+const TOOL_COLORS: Record<string, string> = {
+ Bash: '#e5c07b', Read: '#61afef', Write: '#98c379', Edit: '#98c379', Glob: '#c678dd',
+ Grep: '#c678dd', WebFetch: '#56b6c2', WebSearch: '#56b6c2', Task: '#d19a66', Agent: '#d19a66',
+ TodoWrite: '#5b8def',
+}
+const PALETTE = ['#e06c75', '#98c379', '#e5c07b', '#61afef', '#c678dd', '#56b6c2', '#d19a66']
+
+export function toolColor(name: string): string {
+ const hit = TOOL_COLORS[name]
+ if (hit) return hit
+ let h = 0
+ for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) >>> 0
+ return PALETTE[h % PALETTE.length]
+}
+
+const PRIMARY_KEYS = ['file_path', 'path', 'command', 'pattern', 'query', 'url', 'description', 'prompt', 'content']
+
+function truncate(s: string, n: number): string {
+ return s.length > n ? s.slice(0, n - 1) + '…' : s
+}
+
+function primaryArg(input: unknown): string {
+ if (!input || typeof input !== 'object') return ''
+ const obj = input as Record<string, unknown>
+ for (const key of PRIMARY_KEYS) {
+ const v = obj[key]
+ if (typeof v === 'string' && v.trim()) return truncate(v.replace(/\s+/g, ' ').trim(), 60)
+ }
+ for (const v of Object.values(obj)) {
+ if (typeof v === 'string' && v.trim()) return truncate(v.replace(/\s+/g, ' ').trim(), 60)
+ }
+ return ''
+}
+
+function compactArgs(input: unknown): string {
+ if (!input || typeof input !== 'object') return ''
+ const obj = input as Record<string, unknown>
+ const parts: string[] = []
+ for (const [k, v] of Object.entries(obj)) {
+ if (typeof v === 'string' && v.trim()) parts.push(`${k}: ${v.replace(/\s+/g, ' ').trim()}`)
+ if (parts.join(' · ').length > 200) break
+ }
+ return truncate(parts.join(' · '), 200)
+}
+
+/**
+ * What counts as a sub-agent.
+ *
+ * Every engine's own name is mapped to `Task` by its normalizer — EXCEPT claude, whose own tool is called
+ * `Agent` and passes through unmapped. Watching only for `Task` therefore missed the one engine this
+ * feature is modelled on; measured on a live claude turn, whose transcript names the tool `Agent`.
+ */
+const SUBAGENT_TOOLS = new Set(['Task', 'Agent'])
+
+/** Running = orange, finished = green. The device just paints the colour it is handed. */
+const AGENT_RUNNING_COLOR = '#ff9d00'
+const AGENT_DONE_COLOR = '#3ddc84'
+
+/**
+ * Claude's async `Agent` tool answers its own tool_use in ~4ms with this line — a LAUNCH ACK, not a
+ * result (measured: `dur= undefined out= Async agent launched successfully.`). Ticking the row off on it
+ * showed every sub-agent as finished the instant it started. The real finish is `subagent_finished`.
+ */
+const ASYNC_LAUNCH_ACK = /Async agent launched successfully/i
+
+/**
+ * After the last sub-agent reports in, the engine still writes its wrap-up ("Cả 2 sub-agent đã hoàn thành:
+ * …"). How long that takes is a model round-trip, not a constant — measured at 3s, 7s and 10.8s on three
+ * consecutive runs, so any fixed window is a coin flip (the 10s one lost by 0.85s).
+ *
+ * So the timer is only a backstop for "nothing more is coming". The two real signals are the Stop hook
+ * (`noteEngineStopped`, exact) and the wrap-up text itself landing — after which a short debounce is
+ * enough, because the text we were waiting for is already in hand.
+ */
+const SUBAGENT_SETTLE_MS = 12_000
+const SUBAGENT_TEXT_SETTLE_MS = 2_000
+/** A sub-agent that never reports back must not cost the turn its recap forever. */
+const SUBAGENT_MAX_WAIT_MS = 10 * 60_000
+
+/**
+ * The device renders ONE line per sub-agent and does no formatting of its own: `› desc` while it runs,
+ * `✓ desc · 12s` once it finishes, in the colour we pick (`ui_project_set_agents`). It also scrolls the
+ * `›` row into view, so that prefix is load-bearing, not decoration.
+ */
+function agentRows(agents: SessionState['agents']): Array<{ text: string; color: string }> {
+ return agents.map((a) => (a.doneMs === null
+ ? { text: `› ${a.desc}`, color: AGENT_RUNNING_COLOR }
+ : { text: `✓ ${a.desc} · ${Math.max(1, Math.round(a.doneMs / 1000))}s`, color: AGENT_DONE_COLOR }))
+}
+
+/**
+ * Does this row's sub-agent gate THIS turn's recap? Only one that started during it.
+ *
+ * Rows survive a turn boundary while they run (cursor announces a Task before its turn opens; claude's
+ * async agents outlive the turn that spawned them), so they stay on screen — but an agent spawned two
+ * prompts ago must not hold the answer to the question just asked: that could park a recap for the full
+ * 10-minute backstop with nothing on the device to explain the wait.
+ */
+function holdsTurn(a: SessionState['agents'][number]): boolean {
+ return a.doneMs === null && !a.carried
+}
+
+/** Split a persisted "recap\n\nbody" into its parts (mirror websocket.ts:540 / getRecentEvents). */
+function splitSummary(summary: string): { recap: string; body: string } {
+ const nl = summary.indexOf('\n\n')
+ const recap = (nl >= 0 ? summary.slice(0, nl) : summary).replace(/\s+/g, ' ').trim().slice(0, MAX_PART)
+ const body = (nl >= 0 ? summary.slice(nl + 2) : summary).replace(/\s+/g, ' ').trim().slice(0, MAX_PART)
+ return { recap, body }
+}
+
+export class CommanderMirror {
+ private states = new Map<string, SessionState>()
+ private summaries = new Map<string, string>() // sessionId → "recap\n\nbody"
+ private file: string
+ private saveTimer: NodeJS.Timeout | null = null
+
+ constructor(private opts: CommanderMirrorOpts) {
+ this.file = join(opts.dataDir, 'summaries.json')
+ this.load()
+ }
+
+ private stateFor(sessionId: string): SessionState {
+ let st = this.states.get(sessionId)
+ if (!st) {
+ st = { lastAssistantText: '', lastUserMessage: '', turnOpen: false, everOpened: false, summarizing: false, lastTool: null, lastTodos: null, agents: [], endPending: false, endSettle: null, endDeadline: null, abort: null }
+ this.states.set(sessionId, st)
+ }
+ return st
+ }
+
+ private emit(sessionId: string, payload: Record<string, unknown>): void {
+ // Bandwidth gate (mirrors the hosted runtime’s emitCommanderEvent empty-pool early-return): with no device
+ // connected every card would ride adapter→backend just to be dropped by deliverUpLocal. Gate the
+ // SEND only — ingest() keeps folding state (lastTool/lastTodos/lastAssistantText) regardless, so a
+ // device joining mid-turn still gets a correct replay (onCommanderJoin) and turn-end recap.
+ if (!this.opts.hasDevice() && !this.opts.recapForce) return
+ // Multi-attach: the turn-done `summary` card reaches ANY connected commander (a BACKGROUND machine badges
+ // from it). Streaming cards (processing/tool/todos/done) reach only the ACTIVELY-rendered machine — a
+ // background machine gets just its summary, not the live stream. Single-machine firmware defaults active to
+ // hasDevice, so attached == active and everything streams exactly like before.
+ const terminal = payload.kind === 'summary'
+ const active = this.opts.active ? this.opts.active() : this.opts.hasDevice()
+ if (!terminal && !active && !this.opts.recapForce) return
+ // Agent name on the summary's outer frame → background-machine device notif line 2 (see nameFor).
+ const name = terminal && this.opts.nameFor ? this.opts.nameFor(sessionId) : undefined
+ this.opts.send({ type: 'commander_event', agentId: this.opts.agentIdFor?.(sessionId) ?? sessionId, dbSessionId: sessionId, ...(name ? { name } : {}), payload })
+ }
+
+ /** Recap diagnostics stay in the adapter log; the web only gets summary pending/done state. */
+ private trace(_sessionId: string, line: string, isError = false): void {
+ ;(isError ? console.error : console.log)(`[recap] ${line}`)
+ }
+
+ /** Fold one session's LiveEvents into device commander_event frames (live cards + async recap). */
+ ingest(events: LiveEvent[], sessionId: string): void {
+ const st = this.stateFor(sessionId)
+ for (const e of events) {
+ switch (e.type) {
+ case 'turn_started':
+ st.abort?.abort() // supersede any in-flight recap from the previous turn
+ st.abort = null
+ // A new prompt supersedes a held turn-end outright: its sub-agents belong to the turn the user
+ // has just moved on from, and the recap they were holding is now stale.
+ this.clearEndTimers(st)
+ st.endPending = false
+ st.summarizing = false
+ st.lastAssistantText = ''
+ st.lastUserMessage = e.payload.userMessage || ''
+ st.turnOpen = true
+ st.everOpened = true
+ st.lastTool = null
+ st.lastTodos = null
+ // Drop the previous turn's finished rows, KEEP the ones still running. Two reasons, both
+ // measured: cursor's tool-start HOOK beats its transcript-derived turn_started by ~60ms, so a
+ // blanket reset deleted the sub-agent that had just been announced (two Tasks collapsed into
+ // one row, live); and a claude async sub-agent genuinely outlives the turn that spawned it, so
+ // a new prompt does not make it stop running. Anything past the wait cap is abandoned.
+ const hadAgents = st.agents.length > 0
+ st.agents = st.agents
+ .filter((a) => a.doneMs === null && Date.now() - a.startedAt < SUBAGENT_MAX_WAIT_MS)
+ .map((a) => ({ ...a, carried: true as const }))
+ this.emit(sessionId, { kind: 'processing', text: 'Processing' })
+ // Push the new list only when there WAS one: an empty array CLEARS the device's list
+ // (ui_project_set_agents deletes the box when the array is empty), which is what stops last
+ // turn's rows hanging around — but a turn that never had sub-agents has nothing to clear.
+ if (hadAgents) this.emit(sessionId, { kind: 'agents', agents: agentRows(st.agents) })
+ break
+
+ case 'text_delta':
+ st.lastAssistantText += e.payload.content
+ // The wrap-up text landed while the turn-end was held: this IS what the hold was waiting for,
+ // so drop to a short debounce (more blocks of the same message may still follow).
+ if (st.endSettle) this.armSettle(sessionId, st, SUBAGENT_TEXT_SETTLE_MS)
+ break
+
+ case 'tool_start': {
+ const tool = e.payload.tool || 'Tool'
+ // AskUserQuestion is not a tool card — it's a question the user answers on the device's question
+ // screen (QuestionWatcher pushes it live off the pane). By the time this line reaches the
+ // transcript the CLI has already been answered, so there is nothing left to show: drop it.
+ if (tool === 'AskUserQuestion') break
+ const toolPayload = {
+ kind: 'tool',
+ text: tool,
+ recap: primaryArg(e.payload.input),
+ color: toolColor(tool),
+ detail: compactArgs(e.payload.input),
+ }
+ st.lastTool = toolPayload
+ this.emit(sessionId, toolPayload)
+ // A sub-agent is not just a card: the device keeps a live LIST of them above "Working…", which
+ // nothing ever fed — the firmware has been able to render it since it shipped, and never got data.
+ if (SUBAGENT_TOOLS.has(tool)) {
+ const id = String(e.payload.id ?? `task-${st.agents.length}`)
+ const desc = primaryArg(e.payload.input) || 'sub-agent'
+ if (!st.agents.some((a) => a.id === id)) st.agents.push({ id, desc, startedAt: Date.now(), doneMs: null })
+ this.emit(sessionId, { kind: 'agents', agents: agentRows(st.agents) })
+ const running = st.agents.filter((a) => a.doneMs === null).length
+ console.log(`[subagents] ${sessionId.slice(0, 8)} ${running}/${st.agents.length} running · "${desc.slice(0, 40)}"`)
+ }
+ if (tool === 'TodoWrite') {
+ const todos = (e.payload.input as TodoInput | undefined)?.todos
+ if (Array.isArray(todos)) {
+ const mapped = todos.map((t) => ({ c: t?.content ?? t?.subject ?? '', s: t?.status ?? 'pending' }))
+ st.lastTodos = mapped
+ this.emit(sessionId, { kind: 'processing', text: 'Processing', todos: mapped })
+ }
+ }
+ break
+ }
+
+ case 'turn_ended':
+ // A killed turn takes the cancel path, not the recap path: clear the tile and stay silent. There
+ // is nothing to summarize, and a beep for output the user just threw away is worse than nothing.
+ if (e.payload.aborted) {
+ this.clearEndTimers(st)
+ st.endPending = false
+ this.cancel(sessionId)
+ } else if (st.agents.some(holdsTurn)) {
+ // Async sub-agents outlive the turn that spawned them: claude says "đã spawn 3 sub-agent" and
+ // ENDS the turn while all three are still working. Recapping there summarized the launch
+ // message and dropped the tile out of busy — the answer the user was waiting for arrived
+ // afterwards with nothing left to show it. Hold the end until the last one reports in.
+ this.holdTurnEnd(sessionId, st)
+ } else this.onTurnEnded(sessionId, st)
+ break
+
+ case 'tool_end': {
+ // Only sub-agents are tracked here; every other tool_end stays web-only.
+ const done = st.agents.find((a) => a.id === String(e.payload.id))
+ if (!done || done.doneMs !== null) break
+ // An async launch ack is not a finish — that one arrives later as `subagent_finished`.
+ if (ASYNC_LAUNCH_ACK.test(e.payload.output || '')) break
+ done.doneMs = e.payload.durationSeconds ? e.payload.durationSeconds * 1000 : Date.now() - done.startedAt
+ this.emit(sessionId, { kind: 'agents', agents: agentRows(st.agents) })
+ this.onSubagentDone(sessionId, st, done.desc)
+ break
+ }
+
+ case 'subagent_finished': {
+ const done = st.agents.find((a) => a.id === e.payload.id)
+ if (!done || done.doneMs !== null) break
+ done.doneMs = Date.now() - done.startedAt
+ this.emit(sessionId, { kind: 'agents', agents: agentRows(st.agents) })
+ this.onSubagentDone(sessionId, st, done.desc)
+ break
+ }
+
+ default:
+ break // thinking/user_message — web-only
+ }
+ }
+ }
+
+ private clearEndTimers(st: SessionState): void {
+ if (st.endSettle) clearTimeout(st.endSettle)
+ if (st.endDeadline) clearTimeout(st.endDeadline)
+ st.endSettle = null
+ st.endDeadline = null
+ }
+
+ /**
+ * The turn closed with sub-agents still running. Keep `turnOpen` true (so the eventual recap takes the
+ * normal path) and the device tile busy — it stays on `Processing` with the live sub-agent list until a
+ * `done`/`summary` card arrives, which is exactly the state we want it in.
+ */
+ private holdTurnEnd(sessionId: string, st: SessionState): void {
+ if (st.endPending) return
+ st.endPending = true
+ const running = st.agents.filter(holdsTurn).length
+ console.log(`[subagents] ${sessionId.slice(0, 8)} turn-end HELD · ${running} sub-agent(s) still running`)
+ this.clearEndTimers(st)
+ st.endDeadline = setTimeout(() => {
+ const stuck = st.agents.filter(holdsTurn).map((a) => a.desc).join(', ')
+ console.log(`[subagents] ${sessionId.slice(0, 8)} turn-end RELEASED by timeout · still running: ${stuck}`)
+ this.releaseTurnEnd(sessionId, st)
+ }, SUBAGENT_MAX_WAIT_MS)
+ st.endDeadline.unref?.()
+ }
+
+ /**
+ * The engine stopped writing (its Stop hook fired). If a turn-end is held and every sub-agent has
+ * reported in, the wrap-up is written — but not necessarily FLUSHED: measured, the hook beat the
+ * transcript line by ~200ms and an immediate release recapped the stale text (153 chars on disk, 1233
+ * a moment later). So this closes the window rather than releasing outright; the wrap-up landing
+ * re-arms it once more, and the recap reads a complete file either way.
+ *
+ * A stop while sub-agents are still running is just the launch ack's own stop: keep holding.
+ */
+ noteEngineStopped(sessionId: string): void {
+ const st = this.states.get(sessionId)
+ if (!st?.endPending) return
+ if (st.agents.some(holdsTurn)) return
+ console.log(`[subagents] ${sessionId.slice(0, 8)} turn-end settling after Stop hook`)
+ this.armSettle(sessionId, st, SUBAGENT_TEXT_SETTLE_MS)
+ }
+
+ /** A sub-agent finished: log it, and if it was the last one, let the held turn-end go through. */
+ private onSubagentDone(sessionId: string, st: SessionState, desc: string): void {
+ const running = st.agents.filter(holdsTurn).length
+ console.log(`[subagents] ${sessionId.slice(0, 8)} ${running}/${st.agents.length} still running · done "${desc.slice(0, 40)}"`)
+ if (!st.endPending || running > 0) return
+ this.armSettle(sessionId, st)
+ }
+
+ private armSettle(sessionId: string, st: SessionState, ms = SUBAGENT_SETTLE_MS): void {
+ if (st.endSettle) clearTimeout(st.endSettle)
+ st.endSettle = setTimeout(() => this.releaseTurnEnd(sessionId, st), ms)
+ st.endSettle.unref?.()
+ }
+
+ private releaseTurnEnd(sessionId: string, st: SessionState): void {
+ if (!st.endPending) return
+ this.clearEndTimers(st)
+ st.endPending = false
+ this.onTurnEnded(sessionId, st)
+ }
+
+ private onTurnEnded(sessionId: string, st: SessionState): void {
+ // ONE recap per turn. The same turn can close from two independent sources that race — the watcher
+ // parsing the `end_turn` line, and the Claude Stop hook force-closing — each emitting `turn_ended`.
+ // A real close always follows a `turn_started` (which set turnOpen=true); a duplicate close finds
+ // turnOpen already false → skip, so the second source can't trigger (or supersede) a second recap.
+ if (!st.turnOpen) {
+ // A close for a session that never opened a turn is NOT the dedup case: the turn ran and its
+ // recap is being dropped. That used to return in silence, which is why a whole turn could go
+ // missing on the device with nothing in this log to explain it.
+ if (!st.everOpened) {
+ this.trace(
+ sessionId,
+ `${sessionId.slice(0, 8)} turn-end · DROPPED (no turn_started was ever seen for this session — ` +
+ `the turn opened before the session was attached), no recap for this turn`,
+ true,
+ )
+ }
+ return
+ }
+ const fallbackText = st.lastAssistantText.trim()
+ const fallbackUserMessage = st.lastUserMessage
+ st.turnOpen = false
+ st.lastTool = null
+ st.lastTodos = null
+ st.lastAssistantText = ''
+
+ const sid = sessionId.slice(0, 8)
+ const device = this.opts.hasDevice()
+
+ // Device-gated: only run the (costly) LLM recap while a device is connected (mirrors the hosted runtime's
+ // isDeviceConnected()). No device → no card, and the summaries map is left untouched.
+ if (!device && !this.opts.recapForce) {
+ // Console-only: no device means no recap flow to watch.
+ console.log(`[recap] ${sid} turn-end · SKIP (no device connected) · textLen=${fallbackText.length}`)
+ return
+ }
+
+ st.abort?.abort()
+ const ac = new AbortController()
+ st.abort = ac
+ st.summarizing = true
+ const t0 = Date.now()
+
+ void this.resolveTurnText(sessionId, fallbackText, fallbackUserMessage)
+ .then(({ text, userMessage, source }) => {
+ if (ac.signal.aborted) return
+ this.startSummary(sessionId, st, ac, t0, sid, text, userMessage, device, source)
+ })
+ .catch((err) => {
+ if (ac.signal.aborted) return
+ this.trace(sessionId, `${sid} JSON session read failed: ${err instanceof Error ? err.message : String(err)} — using live buffer`, true)
+ this.startSummary(sessionId, st, ac, t0, sid, fallbackText, fallbackUserMessage, device, 'live')
+ })
+ }
+
+ private async resolveTurnText(
+ sessionId: string,
+ fallbackText: string,
+ fallbackUserMessage: string,
+ ): Promise<{ text: string; userMessage: string; source: 'session-json' | 'live' }> {
+ const turn = this.opts.readLastTurn ? await this.opts.readLastTurn(sessionId) : null
+ if (turn?.assistantText.trim()) {
+ return {
+ text: turn.assistantText.trim(),
+ userMessage: turn.userMessage || fallbackUserMessage,
+ source: 'session-json',
+ }
+ }
+ return { text: fallbackText, userMessage: fallbackUserMessage, source: 'live' }
+ }
+
+ private startSummary(
+ sessionId: string,
+ st: SessionState,
+ ac: AbortController,
+ t0: number,
+ sid: string,
+ text: string,
+ userMessage: string,
+ device: boolean,
+ source: 'session-json' | 'live',
+ ): void {
+ if (!text) {
+ // No assistant TEXT block accumulated this turn (thinking/tools don't count) → nothing to
+ // summarize. Happens when: a new prompt closed the turn before any text arrived (back-to-back
+ // messages), or a tools/thinking-only turn ended with no final text. Graceful: clear busy, no recap.
+ const ask = userMessage.replace(/\s+/g, ' ').trim().slice(0, 60)
+ st.summarizing = false
+ this.trace(sessionId, `${sid} turn-end · empty assistant text → done · source=${source}${ask ? ` · ask="${ask}"` : ' · (no user prompt captured this turn)'}`)
+ this.emit(sessionId, { kind: 'done', text: 'done' })
+ return
+ }
+
+ const ask = userMessage.replace(/\s+/g, ' ').trim().slice(0, 60)
+ this.trace(sessionId, `${sid} summarizing · source=${source} · textLen=${text.length} · device=${device}${this.opts.recapForce ? ' · recapForce' : ''}${ask ? ` · ask="${ask}"` : ''}`)
+ // Device: busy "Summarizing…" card. Web: the "Summarizing for device…" indicator (mirrors the
+ // node's handleBrainSummaryEvent — the web ignores the summary text, only toggles the flag).
+ this.emit(sessionId, { kind: 'processing', text: 'Summarizing…' })
+ this.opts.sendWeb({ type: 'turn_summary_pending', dbSessionId: sessionId, payload: { sessionId } })
+
+ this.opts
+ .summarize(text, ac.signal, userMessage, sessionId)
+ .then((summary) => {
+ const ms = Date.now() - t0
+ if (ac.signal.aborted) { this.trace(sessionId, `${sid} superseded after ${ms}ms (newer turn) — dropping result`); return }
+ st.summarizing = false
+ if (summary) {
+ this.summaries.set(sessionId, summary)
+ this.saveSoon()
+ const { recap, body } = splitSummary(summary)
+ this.trace(sessionId, `${sid} done in ${ms}ms · recap="${recap}" · bodyLen=${body.length}`)
+ this.emit(sessionId, { kind: 'done', text: 'done' })
+ this.emit(sessionId, { kind: 'summary', text: body || recap, recap })
+ this.opts.sendWeb({ type: 'turn_summary', dbSessionId: sessionId, payload: { summary, sessionId } })
+ } else {
+ this.trace(sessionId, `${sid} summarizer returned NULL after ${ms}ms → done`)
+ this.emit(sessionId, { kind: 'done', text: 'done' })
+ this.opts.sendWeb({ type: 'turn_summary_pending', dbSessionId: sessionId, payload: { sessionId, done: true } })
+ }
+ })
+ .catch((err) => {
+ const ms = Date.now() - t0
+ if (ac.signal.aborted) return
+ st.summarizing = false
+ this.trace(sessionId, `${sid} FAILED after ${ms}ms: ${err instanceof Error ? err.message : String(err)}`, true)
+ this.emit(sessionId, { kind: 'done', text: 'done' })
+ this.opts.sendWeb({ type: 'turn_summary_pending', dbSessionId: sessionId, payload: { sessionId, done: true } })
+ })
+ }
+
+ /** Converge on commander (re)join — fires when a device joins OR when the adapter reconnects to the backend
+ * with a device still attached (the adapter has no periodic heartbeat). For an OPEN turn, re-assert its
+ * live processing/tool state. For an IDLE session, re-assert a terminal `done`: its turn-end summary may
+ * have been emitted into a WS that dropped right after (see the ETH case — `done` then `close 1006`), so a
+ * device that missed it is stuck "Working…" forever. A bare `done` clears that stale busy WITHOUT a beep or
+ * recap card, and is a harmless no-op on a tile that isn't busy; the device's recent-poll restores the
+ * stored summary text afterwards. */
+ replayAll(): void {
+ for (const sessionId of this.states.keys()) {
+ // Busy session → re-assert its live processing/summarizing state (shared with heartbeat()).
+ // Idle session → re-assert a terminal `done` (heartbeat() returns false and emits nothing).
+ if (!this.heartbeat(sessionId)) this.emit(sessionId, { kind: 'done', text: 'done' })
+ }
+ }
+
+ /** 5s heartbeat fan-out to the device (called from cli.ts's per-session turn timer). Re-emits the current
+ * BUSY state so the device's busy tile stays fresh through BOTH the turn (Processing) AND the summarize
+ * window (Summarizing…) — the device clears a busy tile only via a live terminal, and has a busy-timeout
+ * watchdog that fires if these stop arriving. Returns true while the session is busy (turnOpen ||
+ * summarizing) so the caller knows when to self-cancel the timer; false (emitting nothing) when idle. */
+ heartbeat(sessionId: string): boolean {
+ const st = this.states.get(sessionId)
+ if (!st) return false
+ if (st.turnOpen) {
+ this.emit(sessionId, st.lastTodos
+ ? { kind: 'processing', text: 'Processing', todos: st.lastTodos }
+ : { kind: 'processing', text: 'Processing' })
+ if (st.lastTool) this.emit(sessionId, st.lastTool)
+ return true
+ }
+ if (st.summarizing) {
+ this.emit(sessionId, { kind: 'processing', text: 'Summarizing…' })
+ return true
+ }
+ return false
+ }
+
+ /** Device tile restore at boot (project_recent): the stored last summary, split for the tile. */
+ recent(sessionId: string, _n = 2): Array<{ kind: string; text: string; recap?: string }> {
+ const summary = this.summaries.get(sessionId)
+ if (!summary || !summary.trim()) return []
+ const { recap, body } = splitSummary(summary)
+ return [{ kind: 'summary', text: body || recap, recap }]
+ }
+
+ /** Turn cancelled (web/device C-c). The claude turn is killed with no end_turn line, so no turn_ended
+ * fires and the recap flow never closes the device's busy tile — it would spin "Working…" forever. Abort
+ * any in-flight recap (so a killed turn can't emit a late summary + beep) and send a bare `done`, which
+ * the device treats as "clear the processing status, keep the last card" (no recap, no beep). The session
+ * stays alive; the next prompt reopens a fresh turn. Mirrors forget() but WITHOUT dropping the state. */
+ cancel(sessionId: string): void {
+ const st = this.states.get(sessionId)
+ if (!st) return
+ st.abort?.abort()
+ st.abort = null
+ st.summarizing = false
+ st.turnOpen = false
+ st.lastTool = null
+ st.lastTodos = null
+ // A cancel outranks a held turn-end: the user threw the turn away, sub-agents and all.
+ this.clearEndTimers(st)
+ st.endPending = false
+ this.emit(sessionId, { kind: 'done', text: 'done' })
+ }
+
+ /** Session gone (SessionEnd / reaper / clear): abort any in-flight recap + drop the EPHEMERAL live
+ * state, and clear the device tile — but KEEP the persisted summary. summaries.json is add/update-only
+ * (never deleted here), so when the SAME sessionId comes back (`claude --resume`, or the tmux pane
+ * reopening) its last recap is reused via recent()/project_recent instead of being lost. */
+ /**
+ * Move the stored recap to a new session id, for a rotation (`/clear`) inside the same live launcher.
+ *
+ * The device tile shows the last recap; without this, clearing the context blanks the tile even though
+ * the agent, its pane and its launcher never went anywhere.
+ */
+ inheritSummary(fromSessionId: string, toSessionId: string): void {
+ const summary = this.summaries.get(fromSessionId)
+ if (!summary || this.summaries.get(toSessionId)) return
+ this.summaries.set(toSessionId, summary)
+ this.save()
+ }
+
+ forget(sessionId: string): void {
+ const st = this.states.get(sessionId)
+ st?.abort?.abort()
+ // The state object is about to be dropped; a held turn-end timer would fire against a dead session.
+ if (st) this.clearEndTimers(st)
+ this.states.delete(sessionId)
+ // NB: intentionally do NOT delete this.summaries[sessionId] — reuse it on the next resume.
+ this.emit(sessionId, { kind: 'done', text: 'done' })
+ }
+
+ // ── persistence ──────────────────────────────────────────────────────────────────────────────
+ private load(): void {
+ try {
+ const obj = JSON.parse(readFileSync(this.file, 'utf-8')) as Record<string, string>
+ for (const [k, v] of Object.entries(obj)) if (typeof v === 'string') this.summaries.set(k, v)
+ } catch { /* no file yet */ }
+ }
+
+ private saveSoon(): void {
+ if (this.saveTimer) clearTimeout(this.saveTimer)
+ this.saveTimer = setTimeout(() => this.save(), 200)
+ }
+
+ private save(): void {
+ try {
+ mkdirSync(this.opts.dataDir, { recursive: true })
+ writeFileSync(this.file, JSON.stringify(Object.fromEntries(this.summaries), null, 2))
+ } catch (err) {
+ console.error('[commander] save summaries failed:', err)
+ }
+ }
+}
+
+// Used by other modules only for potential reuse — kept exported.
+export { splitSummary }
diff --git a/cli/src/lib/commanderReplay.spec.ts b/cli/src/lib/commanderReplay.spec.ts
new file mode 100644
index 000000000..a49602934
--- /dev/null
+++ b/cli/src/lib/commanderReplay.spec.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from 'vitest'
+import { shouldReplayCommander } from './commanderReplay.js'
+
+describe('shouldReplayCommander', () => {
+ it('detects a new attach even when the aggregate count is unchanged', () => {
+ expect(shouldReplayCommander(1, 1, 10, 11, false)).toBe(true)
+ expect(shouldReplayCommander(1, 1, 11, 11, false)).toBe(false)
+ })
+
+ it('keeps count-rise compatibility when generation is absent', () => {
+ expect(shouldReplayCommander(0, 1, undefined, undefined, false)).toBe(true)
+ })
+
+ it('forces one replay after transport reconnect but only with a commander present', () => {
+ expect(shouldReplayCommander(1, 0, 10, 10, true)).toBe(false)
+ expect(shouldReplayCommander(0, 1, 10, 10, true)).toBe(true)
+ })
+})
diff --git a/cli/src/lib/commanderReplay.ts b/cli/src/lib/commanderReplay.ts
new file mode 100644
index 000000000..fee51d798
--- /dev/null
+++ b/cli/src/lib/commanderReplay.ts
@@ -0,0 +1,12 @@
+/** Decide whether an absolute `__clients` snapshot represents a commander that needs live-state replay. */
+export function shouldReplayCommander(
+ previousCount: number,
+ nextCount: number,
+ replayedGeneration: number | undefined,
+ incomingGeneration: number | undefined,
+ replayOnNextSnapshot: boolean,
+): boolean {
+ if (nextCount <= 0) return false
+ if (replayOnNextSnapshot || nextCount > previousCount) return true
+ return incomingGeneration != null && incomingGeneration !== replayedGeneration
+}
diff --git a/cli/src/lib/daemonState.ts b/cli/src/lib/daemonState.ts
new file mode 100644
index 000000000..9be03a005
--- /dev/null
+++ b/cli/src/lib/daemonState.ts
@@ -0,0 +1,50 @@
+/**
+ * On-disk daemon state that BOTH the daemon (`cli.ts`) and short-lived CLI commands need to read —
+ * the pid file, the saved credential, and the fixed loopback control port.
+ *
+ * Kept in its own module so `launch.ts` (the `harness <engine>` wrapper) can check "is the daemon
+ * joined and running?" without importing `cli.ts`, which would be circular (cli.ts dispatches into
+ * launch.ts).
+ */
+
+import { existsSync, readFileSync } from 'fs'
+import { join } from 'path'
+import { env } from '../config/env.js'
+
+export const TOKEN_FILE = join(env.ADAPTER_DATA_DIR, 'token')
+export const PID_FILE = join(env.ADAPTER_DATA_DIR, 'adapter.pid')
+
+// The saved credential IS the agent apiKey — 32 random bytes as hex (64 chars).
+const TOKEN_RE = /^[0-9a-f]{64}$/i
+
+/** The daemon's localhost control port — FIXED at env.PORT (no fallback), so pair/status/stop always
+ * reach it and a leftover is findable with `lsof :<PORT>`. */
+export function daemonPort(): number {
+ return env.PORT
+}
+
+export function readPid(): number | null {
+ try {
+ const pid = parseInt(readFileSync(PID_FILE, 'utf-8').trim(), 10)
+ return Number.isFinite(pid) ? pid : null
+ } catch { return null }
+}
+
+export function isAlive(pid: number): boolean {
+ try { process.kill(pid, 0); return true } catch { return false }
+}
+
+/** Has this computer ever joined? (env override, else a well-formed token file.) Deliberately returns a
+ * boolean, not the token — callers here only need to pick the right "how to fix it" message. */
+export function hasSavedToken(): boolean {
+ const fromEnv = env.ADAPTER_TOKEN
+ if (fromEnv && TOKEN_RE.test(fromEnv.trim())) return true
+ if (!existsSync(TOKEN_FILE)) return false
+ try { return TOKEN_RE.test(readFileSync(TOKEN_FILE, 'utf-8').trim()) } catch { return false }
+}
+
+/** Is the background daemon process alive right now? (pid file present AND that pid still exists) */
+export function isDaemonRunning(): boolean {
+ const pid = readPid()
+ return pid !== null && isAlive(pid)
+}
diff --git a/cli/src/lib/deleteAgentFallback.spec.ts b/cli/src/lib/deleteAgentFallback.spec.ts
new file mode 100644
index 000000000..32f5a0723
--- /dev/null
+++ b/cli/src/lib/deleteAgentFallback.spec.ts
@@ -0,0 +1,147 @@
+import { describe, expect, it } from 'vitest'
+import { terminateDeletedAgent, type TerminateDeps } from './deleteAgentFallback.js'
+import type { RegisteredSession } from './registry.js'
+
+/**
+ * The one place in the adapter that signals somebody else's process. Everything here is about NOT hitting
+ * the wrong target and NOT going quiet when it fails: by the time this runs the UI already told the user
+ * the agent is gone, so an unreported failure leaves a running engine nothing accounts for.
+ */
+
+const SESSION = {
+ sessionId: 's1',
+ engine: 'claude',
+ tmuxPane: '%3',
+ processIdentity: { pid: 4242, executable: 'claude', startMarker: 'Mon Aug 3 09:00:00 2026' },
+} as unknown as RegisteredSession
+
+/** Deps whose clock is instant, so the real (multi-second) waits do not slow the suite down. */
+function deps(over: Partial<TerminateDeps> = {}): TerminateDeps & { kills: Array<[number, string]>; logs: string[] } {
+ const kills: Array<[number, string]> = []
+ const logs: string[] = []
+ return {
+ kills,
+ logs,
+ isAlive: async () => true,
+ kill: (pid, signal) => { kills.push([pid, signal]) },
+ sleep: async () => { /* instant */ },
+ log: (m) => { logs.push(m) },
+ ...over,
+ }
+}
+
+describe('delete-agent fallback', () => {
+ it('does nothing when the engine already left', async () => {
+ // The normal case on a current build: the launcher got the request and shut its child down.
+ const d = deps({ isAlive: async () => false })
+ await expect(terminateDeletedAgent(SESSION, d)).resolves.toBe('gone')
+ expect(d.kills).toEqual([])
+ })
+
+ it('SIGTERMs an engine that is still there, and stops once it goes', async () => {
+ let alive = true
+ const d = deps({ isAlive: async () => alive, kill: (pid, signal) => { alive = false; d.kills.push([pid, signal]) } })
+ await expect(terminateDeletedAgent(SESSION, d)).resolves.toBe('terminated')
+ expect(d.kills).toEqual([[4242, 'SIGTERM']])
+ })
+
+ it('escalates to SIGKILL for an engine that ignores SIGTERM', async () => {
+ // Some CLIs trap SIGTERM for a "press again to quit" prompt. Delete has to mean deleted.
+ let alive = true
+ const d = deps({
+ isAlive: async () => alive,
+ kill: (pid, signal) => { if (signal === 'SIGKILL') alive = false; d.kills.push([pid, signal]) },
+ })
+ await expect(terminateDeletedAgent(SESSION, d)).resolves.toBe('killed')
+ expect(d.kills).toEqual([[4242, 'SIGTERM'], [4242, 'SIGKILL']])
+ expect(d.logs.join('\n')).toContain('SIGKILL')
+ })
+
+ it('never signals a pane that now holds a different process', async () => {
+ // isAlive compares pid AND start time, so a recycled pid reads as not-alive — the pid-reuse guard.
+ const d = deps({ isAlive: async () => false })
+ await terminateDeletedAgent({ ...SESSION, processIdentity: { pid: 4242, executable: 'x', startMarker: 'later' } } as RegisteredSession, d)
+ expect(d.kills).toEqual([])
+ })
+
+ it('has nothing to signal when the session never had a pid on record', async () => {
+ const d = deps()
+ await expect(terminateDeletedAgent({ ...SESSION, processIdentity: null } as RegisteredSession, d))
+ .resolves.toBe('not-ours')
+ expect(d.kills).toEqual([])
+ })
+
+ it('reports a refused signal instead of swallowing it', async () => {
+ // EPERM: a differently-owned engine (sudo, another account). The delete silently did not happen, and
+ // the user was already told it did — so this must be loud, and must not throw.
+ const d = deps({
+ kill: () => { throw Object.assign(new Error('operation not permitted'), { code: 'EPERM' }) },
+ })
+ await expect(terminateDeletedAgent(SESSION, d)).resolves.toBe('failed')
+ expect(d.logs.join('\n')).toContain('operation not permitted')
+ })
+
+ it('treats a process that vanished mid-signal as gone, not as a failure', async () => {
+ let alive = true
+ const d = deps({
+ isAlive: async () => alive,
+ kill: () => { alive = false; throw Object.assign(new Error('no such process'), { code: 'ESRCH' }) },
+ })
+ await expect(terminateDeletedAgent(SESSION, d)).resolves.toBe('gone')
+ expect(d.logs.join('\n')).not.toContain('could not') // ESRCH is not an error worth reporting
+ })
+
+ it('says failed — loudly — when even SIGKILL does not take', async () => {
+ const d = deps() // alive forever
+ await expect(terminateDeletedAgent(SESSION, d)).resolves.toBe('failed')
+ expect(d.logs.join('\n')).toContain('STILL running')
+ })
+
+ it('waits for the launcher before touching anything', async () => {
+ // The budgets are coupled: this delay must outlast the launcher's own SIGTERM→SIGKILL grace, so a
+ // launcher that understood the request always finishes first and this never fires at all.
+ const waits: number[] = []
+ const d = deps({ isAlive: async () => false, sleep: async (ms) => { waits.push(ms) } })
+ await terminateDeletedAgent(SESSION, d)
+ expect(waits[0]).toBeGreaterThan(3_000) // LAUNCHER_EXIT_GRACE_MS in launch.ts
+ })
+
+ it('never rejects, whatever the probe does', async () => {
+ const d = deps({ isAlive: async () => { throw new Error('tmux is gone') } })
+ await expect(terminateDeletedAgent(SESSION, d)).resolves.toBe('gone')
+ })
+})
+
+describe('delete-agent fallback timing', () => {
+ it('polls during the kill grace rather than sleeping through it', async () => {
+ // A polled grace lets a well-behaved engine's exit be noticed immediately; one long sleep would make
+ // every SIGTERM cost the full grace before the outcome is known.
+ let alive = true
+ const sleeps: number[] = []
+ let calls = 0
+ const d = deps({
+ isAlive: async () => { calls += 1; if (calls > 3) alive = false; return alive },
+ sleep: async (ms) => { sleeps.push(ms) },
+ })
+ await expect(terminateDeletedAgent(SESSION, d)).resolves.toBe('terminated')
+ expect(sleeps.filter((ms) => ms < 1_000).length).toBeGreaterThan(0)
+ })
+
+ it('honours caller-supplied budgets', async () => {
+ const sleeps: number[] = []
+ const d = deps({ isAlive: async () => false, sleep: async (ms) => { sleeps.push(ms) } })
+ await terminateDeletedAgent(SESSION, d, 10, 20)
+ expect(sleeps[0]).toBe(10)
+ })
+})
+
+describe('delete-agent fallback wiring', () => {
+ it('uses the session it was handed, not a lookup', async () => {
+ // The registry entry is already gone by the time this runs (forgetSession removed it), so the caller
+ // must pass the captured session. Pinning it here keeps that ordering from being "fixed" later.
+ const seen: RegisteredSession[] = []
+ const d = deps({ isAlive: async (s) => { seen.push(s); return false } })
+ await terminateDeletedAgent(SESSION, d)
+ expect(seen[0]).toBe(SESSION)
+ })
+})
diff --git a/cli/src/lib/deleteAgentFallback.ts b/cli/src/lib/deleteAgentFallback.ts
new file mode 100644
index 000000000..6ab7acf00
--- /dev/null
+++ b/cli/src/lib/deleteAgentFallback.ts
@@ -0,0 +1,102 @@
+/**
+ * The backstop for deleting an agent: make sure the engine actually stopped.
+ *
+ * Deleting asks the launcher to shut its child down over the machine socket. That is the good path — the
+ * launcher owns its child and can end it cleanly, leaving the tmux pane alive. But it cannot be relied
+ * on alone: OTA ships one bundle while a launcher already running keeps its old build for hours, and an
+ * old launcher does not know the `exit` frame — it ignores it in silence, exactly as designed.
+ *
+ * So this does not GUESS whether the request was understood, it MEASURES: wait past the launcher's own
+ * shutdown budget, look at the pane again, and only then signal the engine directly. Killing the engine
+ * makes even an ancient launcher exit, because its child-exit handler ends the process.
+ *
+ * What it deliberately does NOT do is kill the tmux pane. That is the whole point of the change: the
+ * agent belongs to machine, the window belongs to the user. The trade is real and accepted — a pane kill
+ * used to hang up the entire foreground process group, so anything the agent had spawned (a dev server, an
+ * MCP subprocess) died with it, and now it does not.
+ */
+
+import type { RegisteredSession } from './registry.js'
+
+/**
+ * Must exceed the launcher's own SIGTERM→SIGKILL budget (`LAUNCHER_EXIT_GRACE_MS` in launch.ts), so a
+ * launcher that DID understand the request always finishes first and this never fires. The two constants
+ * are coupled; changing one without the other either kills a graceful shutdown mid-way (too short) or
+ * leaves a deleted agent running (too long).
+ */
+export const FALLBACK_CHECK_MS = 4_500
+/** After SIGTERM. Matches the daemon's own stop sequence rather than inventing a tighter one. */
+export const FALLBACK_KILL_GRACE_MS = 3_000
+const POLL_MS = 250
+
+export type TerminateOutcome =
+ /** It left on its own — the launcher did its job, or the user closed it. */
+ | 'gone'
+ /** SIGTERM was enough. */
+ | 'terminated'
+ /** It ignored SIGTERM and had to be killed. */
+ | 'killed'
+ /** The pane holds a DIFFERENT process now; signalling it would hit an innocent bystander. */
+ | 'not-ours'
+ /** We could not signal it (permissions, gone mid-flight). The engine may still be running. */
+ | 'failed'
+
+export interface TerminateDeps {
+ /** `validateSessionRuntime`: the pane still holds THIS session's engine (pid + start time match). */
+ isAlive: (session: RegisteredSession) => Promise<boolean>
+ /** `process.kill`. Throws on EPERM/ESRCH like the real one. */
+ kill: (pid: number, signal: NodeJS.Signals) => void
+ sleep: (ms: number) => Promise<void>
+ log: (message: string) => void
+}
+
+/**
+ * Wait out the launcher, then stop the engine if it is still there. Never throws.
+ *
+ * Failures are logged loudly on purpose: by the time this runs the UI already says the agent is gone, so
+ * a silently-swallowed EPERM would leave a running engine that nothing on screen accounts for.
+ */
+export async function terminateDeletedAgent(
+ session: RegisteredSession,
+ deps: TerminateDeps,
+ checkAfterMs = FALLBACK_CHECK_MS,
+ killGraceMs = FALLBACK_KILL_GRACE_MS,
+): Promise<TerminateOutcome> {
+ await deps.sleep(checkAfterMs)
+
+ // isAlive compares pid AND start time, so a pane that now runs something else reads as not-alive here —
+ // which is why the pid below can never land on a recycled pid.
+ if (!await deps.isAlive(session).catch(() => false)) return 'gone'
+
+ const pid = session.processIdentity?.pid
+ if (!pid) return 'not-ours'
+
+ const signal = (sig: NodeJS.Signals): boolean => {
+ try { deps.kill(pid, sig); return true } catch (err) {
+ const code = (err as NodeJS.ErrnoException)?.code
+ // ESRCH = it exited between the check and the signal. Anything else (EPERM…) is a real failure to
+ // enforce the delete, and the person who pressed delete has already been told it worked.
+ if (code !== 'ESRCH') {
+ deps.log(`[delete] could not ${sig} ${session.engine} pid ${pid}: ${err instanceof Error ? err.message : String(err)}`)
+ }
+ return false
+ }
+ }
+
+ deps.log(`[delete] ${session.engine} did not exit on request — SIGTERM pid ${pid}`)
+ if (!signal('SIGTERM')) return await deps.isAlive(session).catch(() => false) ? 'failed' : 'gone'
+
+ for (let waited = 0; waited < killGraceMs; waited += POLL_MS) {
+ await deps.sleep(POLL_MS)
+ if (!await deps.isAlive(session).catch(() => false)) return 'terminated'
+ }
+
+ deps.log(`[delete] ${session.engine} ignored SIGTERM — SIGKILL pid ${pid}`)
+ if (!signal('SIGKILL')) return await deps.isAlive(session).catch(() => false) ? 'failed' : 'gone'
+ await deps.sleep(POLL_MS)
+ if (await deps.isAlive(session).catch(() => false)) {
+ deps.log(`[delete] ${session.engine} pid ${pid} is STILL running after SIGKILL`)
+ return 'failed'
+ }
+ return 'killed'
+}
diff --git a/cli/src/lib/deletedSessions.ts b/cli/src/lib/deletedSessions.ts
new file mode 100644
index 000000000..b83ec9578
--- /dev/null
+++ b/cli/src/lib/deletedSessions.ts
@@ -0,0 +1,47 @@
+/**
+ * Sessions deleted moments ago — a short tombstone so a dying agent cannot re-register itself.
+ *
+ * Deleting an agent used to kill its tmux pane, which killed the engine almost instantly; nothing could
+ * announce itself afterwards. Now the engine is asked to exit and keeps running for a second or two, and
+ * in that window its hooks still fire. The catch hook (`UserPromptSubmit`) POSTs on every turn boundary
+ * and is gated only on the LAUNCHER being alive — which it is — so without this the tile the user just
+ * deleted comes straight back, and the resumed-session adoption loop would re-adopt it for good measure.
+ *
+ * Deliberately time-based and tiny: this is a race window, not a state machine. The entry is dropped as
+ * soon as the process is confirmed gone, and expires on its own if that confirmation never comes.
+ */
+
+/** Long enough to outlast the whole delete sequence (ask, verify, SIGTERM, grace, SIGKILL) with margin. */
+export const DELETED_TTL_MS = 15_000
+
+const tombstones = new Map<string, number>()
+
+function sweep(now: number): void {
+ for (const [sessionId, expiresAt] of tombstones) if (expiresAt <= now) tombstones.delete(sessionId)
+}
+
+export function markDeleted(sessionId: string, ttlMs = DELETED_TTL_MS): void {
+ const now = Date.now()
+ sweep(now)
+ tombstones.set(sessionId, now + ttlMs)
+}
+
+/** True while re-registering this session would resurrect something the user just deleted. */
+export function isRecentlyDeleted(sessionId: string | undefined): boolean {
+ if (!sessionId) return false
+ const expiresAt = tombstones.get(sessionId)
+ if (expiresAt === undefined) return false
+ if (expiresAt > Date.now()) return true
+ tombstones.delete(sessionId)
+ return false
+}
+
+/** The agent is provably gone — nothing left to resurrect, so stop blocking the id. */
+export function clearDeleted(sessionId: string): void {
+ tombstones.delete(sessionId)
+}
+
+/** Test seam. */
+export function resetDeleted(): void {
+ tombstones.clear()
+}
diff --git a/cli/src/lib/deviceErrors.spec.ts b/cli/src/lib/deviceErrors.spec.ts
new file mode 100644
index 000000000..3f5f81f4c
--- /dev/null
+++ b/cli/src/lib/deviceErrors.spec.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from 'vitest'
+import { deviceErrorText } from './deviceErrors.js'
+
+describe('deviceErrorText', () => {
+ it('makes Claude submit-verification failures device-friendly', () => {
+ expect(deviceErrorText('The agent did not accept the message. Please try again.', 'claude'))
+ .toBe("Claude didn't start. Check the terminal, then try again.")
+ })
+
+ it('keeps the generic text for non-Claude engines and unrelated errors', () => {
+ expect(deviceErrorText('The agent did not accept the message. Please try again.', 'codex'))
+ .toBe('The agent did not accept the message. Please try again.')
+ expect(deviceErrorText('This agent process is no longer running.', 'claude'))
+ .toBe('This agent process is no longer running.')
+ })
+
+ it('reduces the Codex usage limit to what the device can act on', () => {
+ // Verbatim from a real rollout: a purchase link the device cannot follow, and a reset time that is
+ // the only thing the reader can do something about.
+ expect(deviceErrorText(
+ "You've hit your usage limit. Visit https://chatgpt.com/codex/settings/usage to purchase more"
+ + ' credits or try again at Aug 5th, 2026 11:09 AM.',
+ 'codex',
+ )).toBe('Codex usage limit reached — try again Aug 5th, 2026 11:09 AM.')
+
+ // Same limit, no reset time offered.
+ expect(deviceErrorText("You've hit your usage limit.", 'codex')).toBe('Codex usage limit reached.')
+ })
+
+ it('drops links and trace ids from any other engine error', () => {
+ expect(deviceErrorText(
+ 'Error: 500 [object Object] Type "continue" to try again. If the issue persists, contact support:'
+ + ' https://commandcode.ai/discord',
+ 'commandcode',
+ )).toBe('Error: 500 [object Object] Type "continue" to try again. If the issue persists, contact support:')
+
+ expect(deviceErrorText(
+ 'Permission denied: high demand for this model. (trace ID: acb60788b786ddfb16a00ddb3d83b053)',
+ 'devin',
+ )).toBe('Permission denied: high demand for this model.')
+
+ // A message with nothing to strip is passed through untouched.
+ expect(deviceErrorText('This agent process is no longer running.', 'pi'))
+ .toBe('This agent process is no longer running.')
+ })
+})
diff --git a/cli/src/lib/deviceErrors.ts b/cli/src/lib/deviceErrors.ts
new file mode 100644
index 000000000..995e4c7c7
--- /dev/null
+++ b/cli/src/lib/deviceErrors.ts
@@ -0,0 +1,41 @@
+/**
+ * Engine errors, rewritten for a 1.9" round screen.
+ *
+ * A CLI writes for someone sitting at a terminal: it links to a settings page, quotes a trace id, tells
+ * you to check the pane. None of that is actionable on a device — the reader cannot follow a URL, and a
+ * long sentence pushes the one fact that matters off the card. So each rule here keeps the WHAT and the
+ * WHEN and drops the rest, rather than truncating, which cuts the end — where the useful part usually is.
+ */
+
+const AGENT_DID_NOT_ACCEPT = 'The agent did not accept the message. Please try again.'
+
+/**
+ * Codex, when the account runs out. Verified against a real rollout (`task_complete.error.message`):
+ * "You've hit your usage limit. Visit https://chatgpt.com/codex/settings/usage to purchase more
+ * credits or try again at Aug 5th, 2026 11:09 AM."
+ * Two facts survive — that it is a usage limit, and when it clears. The purchase link cannot be followed
+ * from the device, so it goes.
+ */
+const CODEX_USAGE_LIMIT = /you'?ve hit your usage limit/i
+const TRY_AGAIN_AT = /try again at\s+([^.]+(?:\.[^.\s]+)*?)\s*\.?\s*$/i
+
+/** Any http(s) link, together with the "Visit …" lead-in that introduces one. */
+const URL_CLAUSE = /\s*(?:visit|see|go to|open)?\s+https?:\/\/\S+/gi
+
+export function deviceErrorText(message: string, engine?: string | null): string {
+ if (message === AGENT_DID_NOT_ACCEPT && engine === 'claude') {
+ return "Claude didn't start. Check the terminal, then try again."
+ }
+ if (CODEX_USAGE_LIMIT.test(message)) {
+ const when = TRY_AGAIN_AT.exec(message)?.[1]?.trim()
+ return when ? `Codex usage limit reached — try again ${when}.` : 'Codex usage limit reached.'
+ }
+ // Nothing engine-specific matched: still drop what the device can never act on.
+ const stripped = message
+ .replace(URL_CLAUSE, '')
+ .replace(/\s*\(trace ID:\s*[0-9a-f]+\)/i, '')
+ .replace(/\s{2,}/g, ' ')
+ .replace(/\s+([.,])/g, '$1')
+ .trim()
+ return stripped || message
+}
diff --git a/cli/src/lib/deviceRecentTrim.spec.ts b/cli/src/lib/deviceRecentTrim.spec.ts
new file mode 100644
index 000000000..226b3736d
--- /dev/null
+++ b/cli/src/lib/deviceRecentTrim.spec.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it } from 'vitest'
+import * as C from './e2ee/core.js'
+import {
+ DEVICE_RECENT_SAFE_FRAME_BYTES,
+ fitRecentReplyPayloadForDevice,
+ truncateUtf8,
+} from './deviceRecentTrim.js'
+
+const key = new Uint8Array(32).fill(7)
+
+function encryptedRecentFrameBytes(payload: Record<string, unknown>): number {
+ const full = { requestId: 1, ...payload }
+ const wrapped = C.wrapPayload(key, 'p', 0, 'agent_recent_result', undefined, full)
+ return Buffer.byteLength(JSON.stringify({ type: 'agent_recent_result', payload: wrapped }), 'utf8')
+}
+
+describe('device recent trim', () => {
+ it('keeps small encrypted recent payloads unchanged', () => {
+ const payload = {
+ agentId: 'agent-1',
+ events: [{ kind: 'summary', text: 'Short body', recap: 'Short recap' }],
+ }
+ const result = fitRecentReplyPayloadForDevice(payload, encryptedRecentFrameBytes)
+ expect(result.trimmed).toBe(false)
+ expect(result.payload).toBe(payload)
+ expect(result.finalBytes).toBeLessThan(DEVICE_RECENT_SAFE_FRAME_BYTES)
+ })
+
+ it('trims huge ascii body to fit the encrypted 90%-of-16KB frame budget', () => {
+ const payload = {
+ agentId: 'agent-1',
+ events: [{ kind: 'summary', text: 'a'.repeat(100_000), recap: 'Important recap stays' }],
+ }
+ const result = fitRecentReplyPayloadForDevice(payload, encryptedRecentFrameBytes)
+ const event = (result.payload.events as Array<{ text: string; recap: string }>)[0]
+ expect(result.trimmed).toBe(true)
+ expect(result.finalBytes).toBeLessThan(DEVICE_RECENT_SAFE_FRAME_BYTES)
+ expect(event.recap).toBe('Important recap stays')
+ expect(event.text.length).toBeGreaterThan(0)
+ expect(event.text.length).toBeLessThan(100_000)
+ })
+
+ it('trims huge unicode body without splitting utf8 characters', () => {
+ const payload = {
+ agentId: 'agent-1',
+ events: [{ kind: 'summary', text: 'Đây là nội dung tiếng Việt rất dài. '.repeat(10_000), recap: 'Tóm tắt tiếng Việt' }],
+ }
+ const result = fitRecentReplyPayloadForDevice(payload, encryptedRecentFrameBytes)
+ const event = (result.payload.events as Array<{ text: string; recap: string }>)[0]
+ expect(result.finalBytes).toBeLessThan(DEVICE_RECENT_SAFE_FRAME_BYTES)
+ expect(Buffer.from(event.text, 'utf8').toString('utf8')).toBe(event.text)
+ expect(event.recap).toBe('Tóm tắt tiếng Việt')
+ })
+
+ it('trims recap only after body is exhausted', () => {
+ const payload = {
+ agentId: 'agent-1',
+ events: [{ kind: 'summary', text: 'body', recap: 'r'.repeat(100_000) }],
+ }
+ const result = fitRecentReplyPayloadForDevice(payload, encryptedRecentFrameBytes)
+ const event = (result.payload.events as Array<{ text: string; recap: string }>)[0]
+ expect(result.finalBytes).toBeLessThan(DEVICE_RECENT_SAFE_FRAME_BYTES)
+ expect(event.text).toBe('body')
+ expect(event.recap.length).toBeLessThan(100_000)
+ })
+
+ it('truncateUtf8 respects byte limits', () => {
+ expect(Buffer.byteLength(truncateUtf8('ááá', 4), 'utf8')).toBeLessThanOrEqual(4)
+ expect(truncateUtf8('abc', 2)).toBe('ab')
+ })
+})
diff --git a/cli/src/lib/deviceRecentTrim.ts b/cli/src/lib/deviceRecentTrim.ts
new file mode 100644
index 000000000..d321806ce
--- /dev/null
+++ b/cli/src/lib/deviceRecentTrim.ts
@@ -0,0 +1,146 @@
+export const DEVICE_RECENT_ENCRYPTED_FRAME_CAP_BYTES = 16 * 1024
+export const DEVICE_RECENT_SAFE_RATIO = 0.9
+export const DEVICE_RECENT_SAFE_FRAME_BYTES = Math.floor(DEVICE_RECENT_ENCRYPTED_FRAME_CAP_BYTES * DEVICE_RECENT_SAFE_RATIO)
+
+type Payload = Record<string, unknown>
+type MeasureFn = (payload: Payload) => number | null
+
+export interface RecentTrimResult {
+ payload: Payload
+ trimmed: boolean
+ originalBytes: number | null
+ finalBytes: number | null
+ textBytes: number
+ recapBytes: number
+}
+
+function byteLen(s: string): number {
+ return Buffer.byteLength(s, 'utf8')
+}
+
+export function truncateUtf8(input: string, maxBytes: number): string {
+ if (maxBytes <= 0) return ''
+ if (byteLen(input) <= maxBytes) return input
+ let out = ''
+ let used = 0
+ for (const ch of input) {
+ const n = byteLen(ch)
+ if (used + n > maxBytes) break
+ out += ch
+ used += n
+ }
+ return out
+}
+
+function normalizeString(v: unknown): string {
+ return typeof v === 'string' ? v : ''
+}
+
+function oneEventPayload(base: Payload, kind: string, text: string, recap: string): Payload {
+ return {
+ ...base,
+ events: [{
+ kind,
+ text,
+ ...(recap ? { recap } : {}),
+ }],
+ }
+}
+
+function maxFittingBytes(input: string, makePayload: (value: string) => Payload, measure: MeasureFn, targetBytes: number): string {
+ let lo = 0
+ let hi = byteLen(input)
+ let best = ''
+ while (lo <= hi) {
+ const mid = Math.floor((lo + hi) / 2)
+ const candidate = truncateUtf8(input, mid)
+ const bytes = measure(makePayload(candidate))
+ if (bytes !== null && bytes < targetBytes) {
+ best = candidate
+ lo = mid + 1
+ } else {
+ hi = mid - 1
+ }
+ }
+ return best
+}
+
+export function fitRecentReplyPayloadForDevice(
+ payload: Payload,
+ measure: MeasureFn,
+ targetBytes = DEVICE_RECENT_SAFE_FRAME_BYTES,
+): RecentTrimResult {
+ const originalBytes = measure(payload)
+ if (originalBytes !== null && originalBytes < targetBytes) {
+ const events = Array.isArray(payload.events) ? payload.events : []
+ const e = (events[0] ?? {}) as Record<string, unknown>
+ const text = normalizeString(e.text)
+ const recap = normalizeString(e.recap)
+ return { payload, trimmed: false, originalBytes, finalBytes: originalBytes, textBytes: byteLen(text), recapBytes: byteLen(recap) }
+ }
+
+ const events = Array.isArray(payload.events) ? payload.events : []
+ const raw = (events[0] ?? {}) as Record<string, unknown>
+ const kind = normalizeString(raw.kind) || 'summary'
+ const originalText = normalizeString(raw.text)
+ const originalRecap = normalizeString(raw.recap)
+
+ let fitted = oneEventPayload(payload, kind, originalText, originalRecap)
+ let finalBytes = measure(fitted)
+ if (finalBytes !== null && finalBytes < targetBytes) {
+ return { payload: fitted, trimmed: true, originalBytes, finalBytes, textBytes: byteLen(originalText), recapBytes: byteLen(originalRecap) }
+ }
+
+ const fitTextForRecap = (recap: string) => maxFittingBytes(
+ originalText,
+ (text) => oneEventPayload(payload, kind, text || recap || kind, recap),
+ measure,
+ targetBytes,
+ )
+
+ const fittedText = fitTextForRecap(originalRecap)
+ fitted = oneEventPayload(payload, kind, fittedText || originalRecap || kind, originalRecap)
+ finalBytes = measure(fitted)
+ if (finalBytes !== null && finalBytes < targetBytes) {
+ return { payload: fitted, trimmed: true, originalBytes, finalBytes, textBytes: byteLen(fittedText), recapBytes: byteLen(originalRecap) }
+ }
+
+ let lo = 0
+ let hi = byteLen(originalRecap)
+ let fittedRecap = ''
+ while (lo <= hi) {
+ const mid = Math.floor((lo + hi) / 2)
+ const recap = truncateUtf8(originalRecap, mid)
+ const bytes = measure(oneEventPayload(payload, kind, originalText || recap || kind, recap))
+ if (bytes !== null && bytes < targetBytes) {
+ fittedRecap = recap
+ lo = mid + 1
+ } else {
+ hi = mid - 1
+ }
+ }
+ let finalText = originalText
+ if (!fittedRecap && originalRecap) {
+ lo = 0
+ hi = byteLen(originalRecap)
+ while (lo <= hi) {
+ const mid = Math.floor((lo + hi) / 2)
+ const recap = truncateUtf8(originalRecap, mid)
+ const text = fitTextForRecap(recap)
+ const candidateText = text || recap || kind
+ const bytes = measure(oneEventPayload(payload, kind, candidateText, recap))
+ const hasRequiredText = !originalText || text.length > 0
+ if (hasRequiredText && bytes !== null && bytes < targetBytes) {
+ fittedRecap = recap
+ finalText = text || candidateText
+ lo = mid + 1
+ } else {
+ hi = mid - 1
+ }
+ }
+ }
+ if (fittedRecap) finalText = fitTextForRecap(fittedRecap) || finalText || fittedRecap || kind
+ fitted = oneEventPayload(payload, kind, finalText, fittedRecap)
+ finalBytes = measure(fitted)
+ return { payload: fitted, trimmed: true, originalBytes, finalBytes, textBytes: byteLen(finalText), recapBytes: byteLen(fittedRecap) }
+}
diff --git a/cli/src/lib/devinTrust.spec.ts b/cli/src/lib/devinTrust.spec.ts
new file mode 100644
index 000000000..98ef17d19
--- /dev/null
+++ b/cli/src/lib/devinTrust.spec.ts
@@ -0,0 +1,64 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+
+/**
+ * Devin 3000.3.22 refuses to run in a directory it has not been trusted in, and the recap runs in a
+ * throwaway scratch dir — so every devin recap failed until the dir is added to its trust list. The list
+ * is the USER's file: other entries and any unrelated keys must survive.
+ */
+const dirs: string[] = []
+afterEach(() => {
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
+ vi.resetModules()
+})
+
+async function loadOneShot(devinHome: string) {
+ vi.resetModules()
+ process.env.DEVIN_HOME = devinHome
+ return import('./oneshot.js')
+}
+
+function devinHome(seed?: unknown): { home: string; file: string } {
+ const home = mkdtempSync(join(tmpdir(), 'adapter-devin-trust-'))
+ dirs.push(home)
+ const file = join(home, 'trusted_workspaces.json')
+ if (seed !== undefined) writeFileSync(file, JSON.stringify(seed))
+ return { home, file }
+}
+
+const read = (file: string): Record<string, unknown> =>
+ JSON.parse(readFileSync(file, 'utf-8')) as Record<string, unknown>
+
+describe('devin scratch-dir trust', () => {
+ it('appends the scratch dir, keeping the paths and keys already there', async () => {
+ const { home, file } = devinHome({ trusted_paths: ['/Users/me/project'], other_setting: true })
+ const { runDevinOneShot } = await loadOneShot(home)
+
+ // The spawn fails (no `devin` on PATH under this test) — the trust write happens first, by design.
+ await runDevinOneShot({ prompt: 'x', cwd: '/tmp/scratch-a', timeoutMs: 200 }).catch(() => {})
+
+ expect(read(file)).toEqual({
+ trusted_paths: ['/Users/me/project', '/tmp/scratch-a'],
+ other_setting: true,
+ })
+ })
+
+ it('is idempotent and starts a list when the file is absent or junk', async () => {
+ const { home, file } = devinHome({ trusted_paths: ['/tmp/scratch-a'] })
+ const { runDevinOneShot } = await loadOneShot(home)
+ await runDevinOneShot({ prompt: 'x', cwd: '/tmp/scratch-a', timeoutMs: 200 }).catch(() => {})
+ expect(read(file).trusted_paths).toEqual(['/tmp/scratch-a'])
+
+ const fresh = devinHome()
+ const one = await loadOneShot(fresh.home)
+ await one.runDevinOneShot({ prompt: 'x', cwd: '/tmp/scratch-b', timeoutMs: 200 }).catch(() => {})
+ expect(read(fresh.file).trusted_paths).toEqual(['/tmp/scratch-b'])
+
+ const junk = devinHome('not an object')
+ const two = await loadOneShot(junk.home)
+ await two.runDevinOneShot({ prompt: 'x', cwd: '/tmp/scratch-c', timeoutMs: 200 }).catch(() => {})
+ expect(read(junk.file).trusted_paths).toEqual(['/tmp/scratch-c'])
+ })
+})
diff --git a/cli/src/lib/discoveryScripts.spec.ts b/cli/src/lib/discoveryScripts.spec.ts
new file mode 100644
index 000000000..0dfb32818
--- /dev/null
+++ b/cli/src/lib/discoveryScripts.spec.ts
@@ -0,0 +1,53 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, readFileSync, rmSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+
+/**
+ * Pi and OpenCode are the only two engines that do NOT register through notify.mjs — they register from a
+ * script the adapter generates and drops into the engine's own extension/plugin directory. When the
+ * launcher landed, `registry.register` began refusing any session without a `launcherId`; notify.mjs was
+ * taught to forward `MACHINE_ID` but these two scripts were not, so pi and opencode silently stopped
+ * producing agents at all. These assertions are on the GENERATED SOURCE, because that is the artifact
+ * that was wrong.
+ */
+const dirs: string[] = []
+afterEach(() => {
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
+ vi.resetModules()
+})
+
+function scratch(): string {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-discovery-'))
+ dirs.push(dir)
+ return dir
+}
+
+describe('generated discovery scripts', () => {
+ it('makes the Pi extension carry the launcher id', async () => {
+ const piHome = scratch()
+ vi.resetModules()
+ process.env.PI_HOME = piHome
+ const { installPiExtension } = await import('./hooks.js')
+ installPiExtension(18473)
+
+ const src = readFileSync(join(piHome, 'agent', 'extensions', 'launcher-register.ts'), 'utf-8')
+ expect(src).toContain('process.env.MACHINE_ID')
+ expect(src).toContain('launcherId,') // sent in the POST body
+ expect(src).toMatch(/if \(!launcherId\) return/) // and no registration without one
+ })
+
+ it('makes the OpenCode plugin carry the launcher id', async () => {
+ const pluginDir = scratch()
+ vi.resetModules()
+ process.env.OPENCODE_PLUGIN_DIR = pluginDir
+ const { installOpencodePlugin } = await import('./hooks.js')
+ installOpencodePlugin(18473)
+
+ const src = readFileSync(join(pluginDir, 'launcher-register.js'), 'utf-8')
+ expect(src).toContain('process.env.MACHINE_ID')
+ expect(src).toContain('launcherId,')
+ // The bail is folded into the existing guard rather than added as a second early return.
+ expect(src).toMatch(/if \(!pane \|\| !launcherId/)
+ })
+})
diff --git a/cli/src/lib/disposableOneShotPool.spec.ts b/cli/src/lib/disposableOneShotPool.spec.ts
new file mode 100644
index 000000000..45033b62a
--- /dev/null
+++ b/cli/src/lib/disposableOneShotPool.spec.ts
@@ -0,0 +1,208 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import {
+ DisposableOneShotPool,
+ poolTargetForActiveSessions,
+ type DisposableWorker,
+ type OneShotEngine,
+} from './disposableOneShotPool.js'
+
+type Result = { workerId: number; engine: OneShotEngine }
+
+class FakeWorker implements DisposableWorker<string, Result> {
+ readonly createdAt = Date.now()
+ private alive = true
+ private used = false
+ private readonly listeners = new Set<() => void>()
+
+ constructor(readonly engine: OneShotEngine, readonly id: number) {}
+
+ isAlive(): boolean { return this.alive }
+ onExit(listener: () => void): void { this.listeners.add(listener) }
+ async run(_options: string): Promise<Result> {
+ if (this.used) throw new Error('worker reused')
+ this.used = true
+ return { workerId: this.id, engine: this.engine }
+ }
+ dispose(): void { this.alive = false }
+ crash(): void {
+ this.alive = false
+ for (const listener of this.listeners) listener()
+ }
+}
+
+async function settle(): Promise<void> {
+ await Promise.resolve()
+ await Promise.resolve()
+}
+
+afterEach(() => vi.useRealTimers())
+
+describe('DisposableOneShotPool', () => {
+ it('sizes each active engine independently at ceil(active / 3), minimum one', () => {
+ expect([0, 1, 2, 3, 4, 6, 7].map(poolTargetForActiveSessions)).toEqual([0, 1, 1, 1, 2, 2, 3])
+ })
+
+ it('consumes a ready worker once and immediately replenishes that engine', async () => {
+ let id = 0
+ const created: FakeWorker[] = []
+ const pool = new DisposableOneShotPool<string, Result>(async (engine) => {
+ const worker = new FakeWorker(engine, ++id)
+ created.push(worker)
+ return worker
+ }, 300_000, () => {})
+
+ pool.setActiveCounts({ claude: 4, codex: 1, cursor: 2, opencode: 0, pi: 0, commandcode: 0 })
+ pool.setDeviceConnected(true)
+ await settle()
+ expect(pool.snapshot()).toMatchObject({
+ claude: { target: 2, ready: 2 },
+ codex: { target: 1, ready: 1 },
+ cursor: { target: 1, ready: 1 },
+ })
+
+ const first = await pool.run('claude', 'recap A')
+ await settle()
+ const second = await pool.run('claude', 'recap B')
+ await settle()
+
+ expect(first.engine).toBe('claude')
+ expect(second.engine).toBe('claude')
+ expect(second.workerId).not.toBe(first.workerId)
+ expect(created.filter((worker) => worker.engine === 'codex')).toHaveLength(1)
+ expect(created.filter((worker) => worker.engine === 'cursor')).toHaveLength(1)
+ expect(pool.snapshot().claude).toMatchObject({ target: 2, ready: 2 })
+ pool.shutdown()
+ })
+
+ it('cold-spawns immediately instead of waiting for a pooled worker that is still starting', async () => {
+ const deferred: { resolve?: (worker: FakeWorker) => void } = {}
+ let calls = 0
+ const pool = new DisposableOneShotPool<string, Result>((engine) => {
+ calls++
+ if (calls === 1) return new Promise((resolve) => { deferred.resolve = resolve })
+ return Promise.resolve(new FakeWorker(engine, calls))
+ }, 300_000, () => {})
+
+ pool.setActiveCounts({ claude: 1, codex: 0, cursor: 0, opencode: 0, pi: 0, commandcode: 0 })
+ pool.setDeviceConnected(true)
+ expect(pool.snapshot().claude.starting).toBe(1)
+
+ await expect(pool.run('claude', 'cold')).resolves.toEqual({ workerId: 2, engine: 'claude' })
+ expect(calls).toBe(2)
+ deferred.resolve?.(new FakeWorker('claude', 1))
+ await settle()
+ expect(pool.snapshot().claude).toMatchObject({ target: 1, starting: 0, ready: 1 })
+ pool.shutdown()
+ })
+
+ it('keeps workers for five minutes after device disconnect and cancels grace on reconnect', async () => {
+ vi.useFakeTimers()
+ let id = 0
+ const pool = new DisposableOneShotPool<string, Result>(
+ async (engine) => new FakeWorker(engine, ++id),
+ 5 * 60_000,
+ () => {},
+ )
+ pool.setActiveCounts({ claude: 1, codex: 0, cursor: 0, opencode: 0, pi: 0, commandcode: 0 })
+ pool.setDeviceConnected(true)
+ await settle()
+
+ pool.setDeviceConnected(false)
+ await vi.advanceTimersByTimeAsync(4 * 60_000)
+ expect(pool.snapshot()).toMatchObject({ enabled: true, connected: false, claude: { ready: 1 } })
+
+ pool.setDeviceConnected(true)
+ await vi.advanceTimersByTimeAsync(2 * 60_000)
+ expect(pool.snapshot()).toMatchObject({ enabled: true, connected: true, claude: { ready: 1 } })
+
+ pool.setDeviceConnected(false)
+ await vi.advanceTimersByTimeAsync(5 * 60_000)
+ expect(pool.snapshot()).toMatchObject({ enabled: false, connected: false, claude: { target: 0, ready: 0 } })
+ pool.shutdown()
+ })
+
+ it('replenishes an idle worker crash with backoff', async () => {
+ vi.useFakeTimers()
+ const created: FakeWorker[] = []
+ const pool = new DisposableOneShotPool<string, Result>(async (engine) => {
+ const worker = new FakeWorker(engine, created.length + 1)
+ created.push(worker)
+ return worker
+ }, 300_000, () => {})
+ pool.setActiveCounts({ claude: 1, codex: 0, cursor: 0, opencode: 0, pi: 0, commandcode: 0 })
+ pool.setDeviceConnected(true)
+ await settle()
+ expect(created).toHaveLength(1)
+
+ created[0].crash()
+ expect(pool.snapshot().claude.ready).toBe(0)
+ await vi.advanceTimersByTimeAsync(999)
+ expect(created).toHaveLength(1)
+ await vi.advanceTimersByTimeAsync(1)
+ await settle()
+ expect(created).toHaveLength(2)
+ expect(pool.snapshot().claude.ready).toBe(1)
+ pool.shutdown()
+ })
+
+ it('never hands out a warm worker that has aged past its idle ceiling', async () => {
+ vi.useFakeTimers()
+ let id = 0
+ const created: FakeWorker[] = []
+ const pool = new DisposableOneShotPool<string, Result>(
+ async (engine) => {
+ const worker = new FakeWorker(engine, ++id)
+ created.push(worker)
+ return worker
+ },
+ 300_000,
+ () => {},
+ 60_000, // idle ceiling
+ )
+
+ pool.setActiveCounts({ claude: 1, codex: 0, cursor: 0, opencode: 0, pi: 0, commandcode: 0 })
+ pool.setDeviceConnected(true)
+ await settle()
+ expect(pool.snapshot()).toMatchObject({ claude: { ready: 1 } })
+ const stale = created[0]
+
+ // Past the ceiling: the parked process is a leak and its model session is cold.
+ await vi.advanceTimersByTimeAsync(61_000)
+ const result = await pool.run('claude', 'prompt')
+
+ expect(stale.isAlive()).toBe(false)
+ expect(result.workerId).not.toBe(stale.id)
+ pool.shutdown()
+ })
+
+ it('retires an idle warm worker on its own, with no recap to trigger it', async () => {
+ // The leak in the field: nobody asked for a recap for over an hour, so nothing ever looked at
+ // the pool, and a warm worker sat on its stdin the whole time.
+ vi.useFakeTimers()
+ let id = 0
+ const created: FakeWorker[] = []
+ const pool = new DisposableOneShotPool<string, Result>(
+ async (engine) => {
+ const worker = new FakeWorker(engine, ++id)
+ created.push(worker)
+ return worker
+ },
+ 300_000,
+ () => {},
+ 60_000,
+ )
+
+ pool.setActiveCounts({ claude: 1, codex: 0, cursor: 0, opencode: 0, pi: 0, commandcode: 0 })
+ pool.setDeviceConnected(true)
+ await settle()
+ const first = created[0]
+
+ await vi.advanceTimersByTimeAsync(90_000)
+
+ expect(first.isAlive()).toBe(false)
+ // Replaced, not merely dropped: the pool still owes its target a warm worker.
+ expect(pool.snapshot()).toMatchObject({ claude: { ready: 1 } })
+ expect(created.length).toBeGreaterThan(1)
+ pool.shutdown()
+ })
+})
diff --git a/cli/src/lib/disposableOneShotPool.ts b/cli/src/lib/disposableOneShotPool.ts
new file mode 100644
index 000000000..9ab718f89
--- /dev/null
+++ b/cli/src/lib/disposableOneShotPool.ts
@@ -0,0 +1,277 @@
+export type OneShotEngine = 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'commandcode'
+
+const ONE_SHOT_ENGINES: readonly OneShotEngine[] = ['claude', 'codex', 'cursor', 'opencode', 'pi', 'commandcode']
+
+export interface DisposableWorker<Options, Result> {
+ readonly engine: OneShotEngine
+ readonly createdAt: number
+ isAlive(): boolean
+ run(options: Options): Promise<Result>
+ dispose(): void
+ onExit(listener: () => void): void
+}
+
+export type ActiveEngineCounts = Record<OneShotEngine, number>
+
+export function poolTargetForActiveSessions(active: number): number {
+ if (!Number.isFinite(active) || active <= 0) return 0
+ return Math.max(1, Math.ceil(active / 3))
+}
+
+interface EngineState<Options, Result> {
+ active: number
+ target: number
+ starting: number
+ ready: Set<DisposableWorker<Options, Result>>
+ retryTimer: NodeJS.Timeout | null
+}
+
+export interface PoolSnapshot {
+ enabled: boolean
+ connected: boolean
+ claude: { active: number; target: number; starting: number; ready: number }
+ codex: { active: number; target: number; starting: number; ready: number }
+ cursor: { active: number; target: number; starting: number; ready: number }
+ opencode: { active: number; target: number; starting: number; ready: number }
+ pi: { active: number; target: number; starting: number; ready: number }
+ commandcode: { active: number; target: number; starting: number; ready: number }
+}
+
+/** Maintains disposable, pre-spawned workers. A checked-out worker is never returned to the pool. */
+export class DisposableOneShotPool<Options, Result> {
+ private readonly states: Record<OneShotEngine, EngineState<Options, Result>> = {
+ claude: { active: 0, target: 0, starting: 0, ready: new Set(), retryTimer: null },
+ codex: { active: 0, target: 0, starting: 0, ready: new Set(), retryTimer: null },
+ cursor: { active: 0, target: 0, starting: 0, ready: new Set(), retryTimer: null },
+ opencode: { active: 0, target: 0, starting: 0, ready: new Set(), retryTimer: null },
+ pi: { active: 0, target: 0, starting: 0, ready: new Set(), retryTimer: null },
+ commandcode: { active: 0, target: 0, starting: 0, ready: new Set(), retryTimer: null },
+ }
+ private readonly all = new Set<DisposableWorker<Options, Result>>()
+ private connected = false
+ private enabled = false
+ private closed = false
+ private generation = 0
+ private unwarmTimer: NodeJS.Timeout | null = null
+ private sweepTimer: NodeJS.Timeout | null = null
+
+ constructor(
+ private readonly factory: (engine: OneShotEngine) => Promise<DisposableWorker<Options, Result>>,
+ private readonly graceMs = 5 * 60_000,
+ private readonly log: (line: string) => void = (line) => console.log(line),
+ /** How long a warm worker may sit unused before it is replaced. A pooled worker is a real
+ * process parked on its stdin: with no ceiling it survives for as long as the adapter does.
+ * One was observed being handed out after 84 minutes, and another idling for 94 — a leak, and
+ * a stale model session for whoever eventually got it. `run()`'s timeout cannot help here; it
+ * only arms once a worker is assigned work. */
+ private readonly maxIdleMs = 10 * 60_000,
+ ) {}
+
+ setActiveCounts(counts: ActiveEngineCounts): void {
+ for (const engine of ONE_SHOT_ENGINES) {
+ this.states[engine].active = Math.max(0, Math.floor(counts[engine] || 0))
+ }
+ this.reconcileAll()
+ }
+
+ setDeviceConnected(connected: boolean): void {
+ if (this.closed) return
+ this.connected = connected
+ if (this.unwarmTimer) {
+ clearTimeout(this.unwarmTimer)
+ this.unwarmTimer = null
+ }
+ if (connected) {
+ this.enabled = true
+ this.startSweep()
+ this.reconcileAll()
+ return
+ }
+ if (!this.enabled) return
+ this.unwarmTimer = setTimeout(() => {
+ this.unwarmTimer = null
+ if (this.connected || this.closed) return
+ this.enabled = false
+ this.reconcileAll()
+ this.log('[recap-pool] device grace expired · unwarmed')
+ }, this.graceMs)
+ }
+
+ async run(engine: OneShotEngine, options: Options): Promise<Result> {
+ const state = this.states[engine]
+ let worker: DisposableWorker<Options, Result> | undefined
+ for (const candidate of state.ready) {
+ state.ready.delete(candidate)
+ if (candidate.isAlive() && !this.expired(candidate)) { worker = candidate; break }
+ if (candidate.isAlive()) this.log(`[recap-pool] ${engine} dropped a stale warm worker · age=${Date.now() - candidate.createdAt}ms`)
+ candidate.dispose()
+ this.all.delete(candidate)
+ }
+
+ const hit = !!worker
+ // The direct worker used by a miss is busy, not pool capacity. Refill the ready target now so a
+ // concurrent recap can still hit a warm worker instead of waiting for this one to finish.
+ this.reconcile(engine)
+ const selected = worker ?? await this.createWorker(engine)
+
+ const age = Date.now() - selected.createdAt
+ this.log(`[recap-pool] ${engine} ${hit ? 'hit' : 'miss'} · workerAge=${age}ms · ready=${state.ready.size}/${state.target}`)
+ try {
+ return await selected.run(options)
+ } finally {
+ selected.dispose()
+ this.all.delete(selected)
+ this.reconcile(engine)
+ }
+ }
+
+ /** Drop idle workers after a runtime config/model change; in-flight work remains isolated. */
+ recycleReady(): void {
+ this.generation++
+ for (const engine of ONE_SHOT_ENGINES) {
+ const state = this.states[engine]
+ for (const worker of state.ready) worker.dispose()
+ state.ready.clear()
+ }
+ this.reconcileAll()
+ }
+
+ shutdown(): void {
+ if (this.closed) return
+ this.closed = true
+ this.enabled = false
+ if (this.unwarmTimer) clearTimeout(this.unwarmTimer)
+ this.unwarmTimer = null
+ if (this.sweepTimer) clearInterval(this.sweepTimer)
+ this.sweepTimer = null
+ for (const worker of this.all) worker.dispose()
+ this.all.clear()
+ for (const engine of ONE_SHOT_ENGINES) {
+ if (this.states[engine].retryTimer) clearTimeout(this.states[engine].retryTimer)
+ this.states[engine].retryTimer = null
+ this.states[engine].ready.clear()
+ this.states[engine].target = 0
+ }
+ }
+
+ snapshot(): PoolSnapshot {
+ const item = (engine: OneShotEngine) => {
+ const s = this.states[engine]
+ return { active: s.active, target: s.target, starting: s.starting, ready: s.ready.size }
+ }
+ return {
+ enabled: this.enabled,
+ connected: this.connected,
+ claude: item('claude'),
+ codex: item('codex'),
+ cursor: item('cursor'),
+ opencode: item('opencode'),
+ pi: item('pi'),
+ commandcode: item('commandcode'),
+ }
+ }
+
+ private expired(worker: DisposableWorker<Options, Result>): boolean {
+ return this.maxIdleMs > 0 && Date.now() - worker.createdAt >= this.maxIdleMs
+ }
+
+ /** Retire warm workers that have aged out. Runs on its own timer, because a pool nobody asks for
+ * a recap from is exactly the case where they would otherwise sit forever. */
+ private sweepExpired(): void {
+ for (const engine of ONE_SHOT_ENGINES) {
+ const state = this.states[engine]
+ for (const worker of [...state.ready]) {
+ if (!this.expired(worker)) continue
+ state.ready.delete(worker)
+ worker.dispose()
+ this.all.delete(worker)
+ this.log(`[recap-pool] ${engine} retired an idle warm worker · age=${Date.now() - worker.createdAt}ms`)
+ }
+ }
+ this.reconcileAll()
+ }
+
+ private startSweep(): void {
+ if (this.sweepTimer || this.closed || this.maxIdleMs <= 0) return
+ this.sweepTimer = setInterval(() => this.sweepExpired(), Math.max(1_000, Math.floor(this.maxIdleMs / 4)))
+ // Never a reason to hold the process open for this.
+ this.sweepTimer.unref?.()
+ }
+
+ private reconcileAll(): void {
+ for (const engine of ONE_SHOT_ENGINES) this.reconcile(engine)
+ }
+
+ private reconcile(engine: OneShotEngine): void {
+ if (this.closed) return
+ const state = this.states[engine]
+ const previousTarget = state.target
+ state.target = this.enabled ? poolTargetForActiveSessions(state.active) : 0
+ if (state.target !== previousTarget) {
+ this.log(`[recap-pool] ${engine} target ${previousTarget}→${state.target} · active=${state.active}`)
+ }
+
+ if (state.target === 0 && state.retryTimer) {
+ clearTimeout(state.retryTimer)
+ state.retryTimer = null
+ }
+
+ while (state.ready.size > state.target) {
+ const worker = state.ready.values().next().value as DisposableWorker<Options, Result> | undefined
+ if (!worker) break
+ state.ready.delete(worker)
+ worker.dispose()
+ this.all.delete(worker)
+ }
+ while (!state.retryTimer && state.ready.size + state.starting < state.target) this.spawnPooled(engine)
+ }
+
+ private spawnPooled(engine: OneShotEngine): void {
+ const state = this.states[engine]
+ const generation = this.generation
+ state.starting++
+ void this.createWorker(engine)
+ .then((worker) => {
+ state.starting--
+ if (generation !== this.generation || this.closed || !this.enabled || state.ready.size >= state.target || !worker.isAlive()) {
+ worker.dispose()
+ this.all.delete(worker)
+ if (!this.closed && this.enabled && state.ready.size < state.target) this.scheduleRetry(engine)
+ } else {
+ state.ready.add(worker)
+ this.log(`[recap-pool] ${engine} warm ready=${state.ready.size}/${state.target}`)
+ this.reconcile(engine)
+ }
+ })
+ .catch((err) => {
+ state.starting--
+ this.log(`[recap-pool] ${engine} warm spawn failed: ${err instanceof Error ? err.message : String(err)}`)
+ this.scheduleRetry(engine)
+ })
+ }
+
+ private async createWorker(engine: OneShotEngine): Promise<DisposableWorker<Options, Result>> {
+ const worker = await this.factory(engine)
+ this.all.add(worker)
+ worker.onExit(() => {
+ this.all.delete(worker)
+ const wasReady = this.states[engine].ready.delete(worker)
+ if (wasReady) this.scheduleRetry(engine)
+ })
+ if (this.closed) {
+ worker.dispose()
+ this.all.delete(worker)
+ throw new Error('recap pool shut down while worker was starting')
+ }
+ return worker
+ }
+
+ private scheduleRetry(engine: OneShotEngine): void {
+ const state = this.states[engine]
+ if (this.closed || !this.enabled || state.target === 0 || state.retryTimer) return
+ state.retryTimer = setTimeout(() => {
+ state.retryTimer = null
+ this.reconcile(engine)
+ }, 1000)
+ }
+}
diff --git a/cli/src/lib/e2ee/core.test.ts b/cli/src/lib/e2ee/core.test.ts
new file mode 100644
index 000000000..d1fa89b99
--- /dev/null
+++ b/cli/src/lib/e2ee/core.test.ts
@@ -0,0 +1,173 @@
+import { describe, it, expect } from 'vitest'
+import { createHash } from 'node:crypto'
+import { readFileSync } from 'fs'
+import { fileURLToPath } from 'url'
+import { dirname, join } from 'path'
+import * as C from './core.js'
+import type { Rng } from './core.js'
+
+// Deterministic RNG for reproducible key material in tests.
+function seeded(seed: number): Rng {
+ let s = seed >>> 0
+ return (n: number) => {
+ const o = new Uint8Array(n)
+ for (let i = 0; i < n; i++) { s = (Math.imul(s, 1103515245) + 12345) & 0x7fffffff; o[i] = s & 0xff }
+ return o
+ }
+}
+
+const AGENT = 'f2e0383771b734e4fc00f0bc8ccf060f'
+
+describe('e2ee core — CPace exchange', () => {
+ it('adapter and web derive the same ISK from the same code', () => {
+ const ci = C.pairContext(AGENT)
+ const sid = C.newPairId(seeded(42))
+ const code = 'K7P4X9'
+ const g = C.cpaceGenerator(code, sid, ci)
+ const a = C.cpaceStart(g, seeded(1)) // adapter
+ const b = C.cpaceStart(g, seeded(2)) // web
+ const Ka = C.cpaceShared(b.Y, a.y)
+ const Kb = C.cpaceShared(a.Y, b.y)
+ const iskA = C.cpaceISK(sid, Ka, a.Y, b.Y)
+ const iskB = C.cpaceISK(sid, Kb, a.Y, b.Y)
+ expect(Buffer.from(iskA).equals(Buffer.from(iskB))).toBe(true)
+ })
+
+ it('regression vector: fixed seeds → known ISK (guards against crypto-lib drift)', () => {
+ const ci = C.pairContext(AGENT)
+ const sid = C.newPairId(seeded(42))
+ const g = C.cpaceGenerator('K7P4X9', sid, ci)
+ const a = C.cpaceStart(g, seeded(1))
+ const b = C.cpaceStart(g, seeded(2))
+ const isk = C.cpaceISK(sid, C.cpaceShared(b.Y, a.y), a.Y, b.Y)
+ expect(Buffer.from(sid).toString('hex')).toBe('1bb891f6f764cd8293d0c9ceeffc85da')
+ expect(Buffer.from(isk).toString('hex')).toBe(
+ '33fe6d15608411dec3174c7acba71622697b1c93751f934418bba8a9b77ca2913f5e39ed07361df51d550d95e519ad661fa1317764f69fb6bbcb2847fb29095c',
+ )
+ })
+
+ it('a WRONG code yields a different ISK → confirmation MAC fails', () => {
+ const ci = C.pairContext(AGENT)
+ const sid = C.newPairId(seeded(42))
+ const g = C.cpaceGenerator('K7P4X9', sid, ci)
+ const gWrong = C.cpaceGenerator('WRONG1', sid, ci)
+ const a = C.cpaceStart(g, seeded(1))
+ const bWrong = C.cpaceStart(gWrong, seeded(2))
+ const th = C.transcriptHash(sid, ci, a.Y, bWrong.Y)
+ // web (wrong code) makes its MAC; adapter (right code) computes ISK its own way → mismatch
+ const iskWeb = C.cpaceISK(sid, C.cpaceShared(a.Y, bWrong.y), a.Y, bWrong.Y)
+ const iskAdapter = C.cpaceISK(sid, C.cpaceShared(bWrong.Y, a.y), a.Y, bWrong.Y)
+ const macWeb = C.macTag(C.kcKeys(iskWeb, ci).web, th)
+ expect(C.macVerify(C.kcKeys(iskAdapter, ci).web, th, macWeb)).toBe(false)
+ })
+
+ it('full exchange: identity pinning via pairKey + bind signature', () => {
+ const ci = C.pairContext(AGENT)
+ const sid = C.newPairId(seeded(42))
+ const A = C.newIdentity(seeded(10)) // adapter identity
+ const B = C.newIdentity(seeded(20)) // web identity
+ const g = C.cpaceGenerator('K7P4X9', sid, ci)
+ const a = C.cpaceStart(g, seeded(1))
+ const b = C.cpaceStart(g, seeded(2))
+ const isk = C.cpaceISK(sid, C.cpaceShared(b.Y, a.y), a.Y, b.Y)
+ const th = C.transcriptHash(sid, ci, a.Y, b.Y)
+ const pk = C.pairKey(isk, ci)
+ // adapter seals its identity + bind sig
+ const sealed = C.aeadSeal(pk, 3, C.utf8('e2e-id'), C.utf8(JSON.stringify({ id: C.b64e(A.pub), sig: C.b64e(C.pairBindSig(A.priv, th)) })))
+ const opened = C.aeadOpen(pk, 3, C.utf8('e2e-id'), sealed)!
+ const got = JSON.parse(new TextDecoder().decode(opened)) as { id: string; sig: string }
+ expect(C.pairBindVerify(C.b64d(got.id), th, C.b64d(got.sig))).toBe(true)
+ // a signature bound to a DIFFERENT transcript is rejected
+ const otherTh = C.transcriptHash(C.newPairId(seeded(99)), ci, a.Y, b.Y)
+ expect(C.pairBindVerify(C.b64d(got.id), otherTh, C.b64d(got.sig))).toBe(false)
+ expect(B).toBeTruthy()
+ })
+})
+
+describe('e2ee core — session + AEAD envelope', () => {
+ it('X25519 session keys agree between both ends', () => {
+ const eW = C.newEphemeral(seeded(3)), eA = C.newEphemeral(seeded(4))
+ const w = C.sessionKeys(eW.priv, eA.pub, AGENT, eW.pub, eA.pub)
+ const s = C.sessionKeys(eA.priv, eW.pub, AGENT, eW.pub, eA.pub)
+ expect(Buffer.from(w.c2s).equals(Buffer.from(s.c2s))).toBe(true)
+ expect(Buffer.from(w.s2c).equals(Buffer.from(s.s2c))).toBe(true)
+ })
+
+ it('group envelope round-trips and is bound to (type, dbSessionId, epoch) via AAD', () => {
+ const key = seeded(5)(32)
+ const wrapped = C.wrapPayload(key, 'g', 0, 'text_delta', 'sess1', { content: 'hi user' }, 'ab12cd34')
+ expect(C.isWrapped(wrapped)).toBe(true)
+ expect(C.unwrapPayload(key, wrapped.__e2e, 'text_delta', 'sess1')).toEqual({ content: 'hi user' })
+ // AAD mismatch (wrong frame type / session / epoch) → cannot open
+ expect(C.unwrapPayload(key, wrapped.__e2e, 'tool_start', 'sess1')).toBeNull()
+ expect(C.unwrapPayload(key, wrapped.__e2e, 'text_delta', 'other')).toBeNull()
+ const tampered = { ...wrapped.__e2e, epoch: 'ffffffff' }
+ expect(C.unwrapPayload(key, tampered, 'text_delta', 'sess1')).toBeNull()
+ })
+
+ it('ciphertext tamper is rejected', () => {
+ const key = seeded(6)(32)
+ const w = C.wrapPayload(key, 'p', 1, 'session_get_result', undefined, { ok: true })
+ const bad = { ...w.__e2e, ct: C.b64e(new Uint8Array(C.b64d(w.__e2e.ct).map((x, i) => (i === 0 ? x ^ 1 : x)))) }
+ expect(C.unwrapPayload(key, bad, 'session_get_result', undefined)).toBeNull()
+ })
+
+ it('counter nonce is distinct per counter', () => {
+ expect(Buffer.from(C.counterNonce(0)).equals(Buffer.from(C.counterNonce(1)))).toBe(false)
+ })
+})
+
+describe('e2ee core — codes + fingerprint + classification', () => {
+ it('normalizeCode maps look-alikes and strips separators', () => {
+ expect(C.normalizeCode('k7p-4x9')).toBe('K7P4X9')
+ expect(C.normalizeCode('IL O U')).toBe('110V')
+ })
+ it('fingerprint is stable, grouped', () => {
+ const id = C.newIdentity(seeded(11))
+ expect(C.fingerprint(id.pub)).toMatch(/^[0-9A-F]{4}·[0-9A-F]{4}·[0-9A-F]{4}·[0-9A-F]{4}$/)
+ })
+ it('frame classification', () => {
+ expect(C.isEncryptedUpType('text_delta')).toBe(true)
+ expect(C.isEncryptedUpType('agent_synced')).toBe(true)
+ expect(C.isEncryptedUpType('node_status')).toBe(false)
+ expect(C.isEncryptedDownType('agents_list')).toBe(true)
+ expect(C.isEncryptedDownType('agent_update')).toBe(true)
+ expect(C.ENCRYPTED_RPC_RESULT_TYPES.has('session_get_result')).toBe(true)
+ expect(C.ENCRYPTED_RPC_RESULT_TYPES.has('agents_list_result')).toBe(true)
+ expect(C.ENCRYPTED_RPC_RESULT_TYPES.has('agent_update_result')).toBe(true)
+ expect(C.isEncryptedDownType('models_list')).toBe(true)
+ expect(C.ENCRYPTED_RPC_RESULT_TYPES.has('models_list_result')).toBe(true)
+ })
+
+ it('round trips runtime catalog request and result only as pairwise ciphertext', () => {
+ const key = seeded(23)(32)
+ const request = C.wrapPayload(key, 'p', 1, 'models_list', undefined, { requestId: 'models-1' })
+ expect(request).not.toHaveProperty('requestId')
+ expect(C.unwrapPayload(key, request.__e2e, 'models_list', undefined)).toEqual({ requestId: 'models-1' })
+
+ const result = C.wrapPayload(key, 'p', 2, 'models_list_result', undefined, {
+ requestId: 'models-1', models: [{ id: 'runtime-v1:s1:codex:gpt@high' }],
+ })
+ expect(result).not.toHaveProperty('models')
+ expect(C.unwrapPayload(key, result.__e2e, 'models_list_result', undefined)).toEqual({
+ requestId: 'models-1', models: [{ id: 'runtime-v1:s1:codex:gpt@high' }],
+ })
+ })
+})
+
+/**
+ * Interop keystone.
+ *
+ * This file is one end of a three-way contract: the same protocol is implemented by the browser client
+ * (TypeScript) and by a paired hardware device (C). Those live in other repositories, so nothing here can
+ * compare bytes with them directly — instead every implementation pins the SAME hash of this file. Change
+ * `core.ts` and this test goes red; update the hash here and the other implementations go red until they
+ * are re-derived from it. A silent divergence would break every already-paired client, with no error.
+ */
+describe('e2ee core — interop keystone', () => {
+ it('core.ts still hashes to the pinned value shared with the other implementations', () => {
+ const here = dirname(fileURLToPath(import.meta.url))
+ const actual = createHash('sha256').update(readFileSync(join(here, 'core.ts'))).digest('hex')
+ expect(actual).toBe('9044aa2e2da62fb4bee401ee06941440daabc6265058f34e941c849661ccf167')
+ })
+})
diff --git a/cli/src/lib/e2ee/core.ts b/cli/src/lib/e2ee/core.ts
new file mode 100644
index 000000000..da82e77d5
--- /dev/null
+++ b/cli/src/lib/e2ee/core.ts
@@ -0,0 +1,383 @@
+/**
+ * E2EE shared crypto core — web ↔ adapter end-to-end encryption.
+ *
+ * ⚠ EVERY COPY OF THIS FILE MUST BE BYTE-IDENTICAL (CLI, browser client). A drift-guard test asserts
+ * the two are equal (see core.test.ts). Edit BOTH together, or the interop guarantee is lost. It uses
+ * only environment-portable APIs (works in Node ≥20 and the browser): noble curves/hashes/ciphers,
+ * plus a portable base64 that prefers Buffer and falls back to atob/btoa.
+ *
+ * Scheme:
+ * - identity keypair (Ed25519) — signs ephemerals + pairing proof-of-possession; pinned once.
+ * - CPace-style PAKE (ristretto255) — the 6-char pairing code bootstraps a shared secret over the
+ * untrusted relay; one online guess only, no offline attack. NOTE: not wire-compatible with the
+ * IETF CPace draft (uses noble hashToRistretto255 for the generator) — interop is guaranteed by
+ * the identical twin + committed self-vectors, not by draft vectors.
+ * - per-connection (X25519) — ephemeral DH → HKDF → pairwise session keys (c2s/s2c).
+ * - group key (random 32B, per adapter process, epoch id) — encrypts 1→many `up` events once.
+ * - AEAD (ChaCha20-Poly1305) — per-frame, counter nonce, AAD binds frame type/session.
+ */
+import { ed25519, x25519, RistrettoPoint, hashToRistretto255 } from '@noble/curves/ed25519'
+import { bytesToNumberLE, concatBytes } from '@noble/curves/abstract/utils'
+import { mod } from '@noble/curves/abstract/modular'
+import { sha512, sha256 } from '@noble/hashes/sha2'
+import { hkdf } from '@noble/hashes/hkdf'
+import { hmac } from '@noble/hashes/hmac'
+import { randomBytes } from '@noble/hashes/utils'
+import { chacha20poly1305 } from '@noble/ciphers/chacha'
+
+// ── portable helpers ──────────────────────────────────────────────────────────────────────────────
+
+const HAS_BUFFER = typeof Buffer !== 'undefined'
+
+export function b64e(u: Uint8Array): string {
+ if (HAS_BUFFER) return Buffer.from(u).toString('base64')
+ let s = ''
+ for (let i = 0; i < u.length; i++) s += String.fromCharCode(u[i])
+ return btoa(s)
+}
+export function b64d(s: string): Uint8Array {
+ if (HAS_BUFFER) return new Uint8Array(Buffer.from(s, 'base64'))
+ const bin = atob(s)
+ const u = new Uint8Array(bin.length)
+ for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i)
+ return u
+}
+function b64urlEncode(s: string): string {
+ const b64 = b64e(utf8(s))
+ return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '')
+}
+function b64urlDecode(s: string): string | null {
+ try {
+ const b64 = s.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (s.length % 4)) % 4)
+ return fromUtf8(b64d(b64))
+ } catch { return null }
+}
+export function utf8(s: string): Uint8Array {
+ return new TextEncoder().encode(s)
+}
+function fromUtf8(u: Uint8Array): string {
+ return new TextDecoder().decode(u)
+}
+/** Length-prefixed concat (4-byte BE length per field) — unambiguous transcript encoding. */
+export function lvCat(...parts: Array<Uint8Array | string>): Uint8Array {
+ const chunks: Uint8Array[] = []
+ for (const p of parts) {
+ const b = typeof p === 'string' ? utf8(p) : p
+ const len = new Uint8Array(4)
+ new DataView(len.buffer).setUint32(0, b.length, false)
+ chunks.push(len, b)
+ }
+ return concatBytes(...chunks)
+}
+function ctEqual(a: Uint8Array, b: Uint8Array): boolean {
+ if (a.length !== b.length) return false
+ let d = 0
+ for (let i = 0; i < a.length; i++) d |= a[i] ^ b[i]
+ return d === 0
+}
+
+export type Rng = (n: number) => Uint8Array
+const defaultRng: Rng = (n) => randomBytes(n)
+
+const CURVE_L = ed25519.CURVE.n
+
+/** Uniform scalar in [1, L). */
+function randScalar(rng: Rng): bigint {
+ for (let i = 0; i < 8; i++) {
+ const s = mod(bytesToNumberLE(rng(64)), CURVE_L)
+ if (s !== 0n) return s
+ }
+ throw new Error('randScalar: exhausted')
+}
+
+// ── identity (Ed25519) ──────────────────────────────────────────────────────────────────────────────
+
+export interface Identity { priv: Uint8Array; pub: Uint8Array }
+
+export function newIdentity(rng: Rng = defaultRng): Identity {
+ const priv = rng(32)
+ return { priv, pub: ed25519.getPublicKey(priv) }
+}
+export function sign(priv: Uint8Array, msg: Uint8Array): Uint8Array {
+ return ed25519.sign(msg, priv)
+}
+export function verify(pub: Uint8Array, msg: Uint8Array, sig: Uint8Array): boolean {
+ try { return ed25519.verify(sig, msg, pub) } catch { return false }
+}
+/** Human-comparable fingerprint of a public key: 4 groups of 4 hex, dot-separated. */
+export function fingerprint(pub: Uint8Array): string {
+ const h = sha256(pub)
+ const hex = b64eHex(h.slice(0, 8)).toUpperCase()
+ return `${hex.slice(0, 4)}·${hex.slice(4, 8)}·${hex.slice(8, 12)}·${hex.slice(12, 16)}`
+}
+function b64eHex(u: Uint8Array): string {
+ let s = ''
+ for (let i = 0; i < u.length; i++) s += u[i].toString(16).padStart(2, '0')
+ return s
+}
+
+// ── CPace-style PAKE over ristretto255 ──────────────────────────────────────────────────────────────
+
+const CPACE_DSI = 'e2e-cpace-ristretto255-v1'
+
+/** Channel-binding string: pins the pairing to this agent + roles (adapter=a initiator; b = the client
+ * being paired). `role` is the responder class — 'web' (browser, default → back-compat with pinned
+ * vectors) or 'device' (the device firmware). A device and a browser therefore derive different
+ * transcripts/ISK/MACs even on the same agent, so their pairings can never be spliced. */
+export type PairRole = 'web' | 'device'
+export function pairContext(machineId: string, role: PairRole = 'web'): string {
+ return `autonomous-e2e-pair|agent:${machineId}|a:adapter|b:${role}`
+}
+
+/** Generator g = hashToGroup(DSI, PRS, sid, CI). PRS = the code; sid = pairId; CI = pairContext. */
+export function cpaceGenerator(code: string, sid: Uint8Array, ci: string): InstanceType<typeof RistrettoPoint> {
+ const genStr = lvCat(CPACE_DSI, normalizeCode(code), sid, ci)
+ return hashToRistretto255(genStr, { DST: CPACE_DSI })
+}
+
+export interface CpaceStart { y: bigint; Y: Uint8Array }
+export function cpaceStart(g: InstanceType<typeof RistrettoPoint>, rng: Rng = defaultRng): CpaceStart {
+ const y = randScalar(rng)
+ return { y, Y: g.multiply(y).toRawBytes() }
+}
+/** Shared secret K = peerY^y (encoded). Rejects the identity point (invalid/attack input). */
+export function cpaceShared(peerY: Uint8Array, y: bigint): Uint8Array {
+ const P = RistrettoPoint.fromHex(peerY) // throws on invalid encoding
+ const K = P.multiply(y)
+ if (K.equals(RistrettoPoint.ZERO)) throw new Error('cpace: identity shared point')
+ return K.toRawBytes()
+}
+/** Intermediate session key. Ya/Yb carry role tags 'a'/'b' so the two directions can't be confused. */
+export function cpaceISK(sid: Uint8Array, K: Uint8Array, Ya: Uint8Array, Yb: Uint8Array): Uint8Array {
+ return sha512(lvCat(`${CPACE_DSI}_ISK`, sid, K, lvCat(Ya, 'a'), lvCat(Yb, 'b')))
+}
+/** Transcript hash bound into confirmation MACs + identity signatures. */
+export function transcriptHash(sid: Uint8Array, ci: string, Ya: Uint8Array, Yb: Uint8Array): Uint8Array {
+ return sha512(lvCat(sid, ci, lvCat(Ya, 'a'), lvCat(Yb, 'b')))
+}
+/** Confirmation MAC keys (adapter half, web half) derived from ISK. */
+export function kcKeys(isk: Uint8Array, ci: string): { adapter: Uint8Array; web: Uint8Array } {
+ const kc = hkdf(sha256, isk, utf8(ci), utf8('e2e-kc-v1'), 64)
+ return { adapter: kc.slice(0, 32), web: kc.slice(32, 64) }
+}
+export function macTag(key: Uint8Array, th: Uint8Array): Uint8Array {
+ return hmac(sha256, key, th)
+}
+export function macVerify(key: Uint8Array, th: Uint8Array, tag: Uint8Array): boolean {
+ return ctEqual(macTag(key, th), tag)
+}
+/** Key that wraps the identity-exchange messages inside the PAKE. */
+export function pairKey(isk: Uint8Array, ci: string): Uint8Array {
+ return hkdf(sha256, isk, utf8(ci), utf8('e2e-id-v1'), 32)
+}
+/** Ed25519 signature proving possession of the identity key, bound to this pairing transcript. */
+export function pairBindSig(priv: Uint8Array, th: Uint8Array): Uint8Array {
+ return sign(priv, concatBytes(utf8('e2e-pair-bind'), th))
+}
+export function pairBindVerify(pub: Uint8Array, th: Uint8Array, sig: Uint8Array): boolean {
+ return verify(pub, concatBytes(utf8('e2e-pair-bind'), th), sig)
+}
+
+// ── setup-link token (adapter CLI → web) ───────────────────────────────────────────────────────────
+
+export interface SetupTokenPayload {
+ v: 1
+ typ: 'adapter-e2ee-setup'
+ pub: string
+ nonce: string
+ exp: number
+ machineId?: string
+}
+
+export interface VerifiedSetupToken {
+ payload: SetupTokenPayload
+ adapterPub: Uint8Array
+}
+
+function canonicalSetupPayload(p: SetupTokenPayload): string {
+ const ordered: SetupTokenPayload = { v: 1, typ: 'adapter-e2ee-setup', pub: p.pub, nonce: p.nonce, exp: p.exp }
+ if (p.machineId) ordered.machineId = p.machineId
+ return JSON.stringify(ordered)
+}
+
+export function encodeSetupToken(payload: SetupTokenPayload, adapterPriv: Uint8Array): string {
+ const p = canonicalSetupPayload(payload)
+ const sig = b64e(sign(adapterPriv, utf8(p)))
+ return b64urlEncode(JSON.stringify({ p: payload, sig }))
+}
+
+export function verifySetupToken(token: string, now = Date.now(), expectedMachineId?: string): VerifiedSetupToken | null {
+ const raw = b64urlDecode(token)
+ if (!raw) return null
+ let parsed: { p?: Partial<SetupTokenPayload>; sig?: unknown }
+ try { parsed = JSON.parse(raw) as { p?: Partial<SetupTokenPayload>; sig?: unknown } } catch { return null }
+ const p = parsed.p
+ if (!p || p.v !== 1 || p.typ !== 'adapter-e2ee-setup' || typeof p.pub !== 'string' || typeof p.nonce !== 'string' || typeof p.exp !== 'number') return null
+ if (typeof p.machineId !== 'undefined' && typeof p.machineId !== 'string') return null
+ if (expectedMachineId && p.machineId && p.machineId !== expectedMachineId) return null
+ if (p.exp < now) return null
+ if (typeof parsed.sig !== 'string') return null
+ const payload: SetupTokenPayload = { v: 1, typ: 'adapter-e2ee-setup', pub: p.pub, nonce: p.nonce, exp: p.exp }
+ if (p.machineId) payload.machineId = p.machineId
+ const adapterPub = b64d(payload.pub)
+ if (!verify(adapterPub, utf8(canonicalSetupPayload(payload)), b64d(parsed.sig))) return null
+ return { payload, adapterPub }
+}
+
+export function setupClaimSig(priv: Uint8Array, machineId: string, token: string, identityPub: Uint8Array): Uint8Array {
+ return sign(priv, lvCat('e2e-setup-claim-v1', machineId, token, identityPub))
+}
+export function setupClaimVerify(pub: Uint8Array, machineId: string, token: string, sig: Uint8Array): boolean {
+ return verify(pub, lvCat('e2e-setup-claim-v1', machineId, token, pub), sig)
+}
+
+// ── per-connection session (X25519 ephemeral → HKDF) ─────────────────────────────────────────────────
+
+export interface Ephemeral { priv: Uint8Array; pub: Uint8Array }
+export function newEphemeral(rng: Rng = defaultRng): Ephemeral {
+ const priv = rng(32)
+ return { priv, pub: x25519.getPublicKey(priv) }
+}
+/** Derive directional session keys. Both sides pass the SAME (webEphPub, adapterEphPub) ordering. */
+export function sessionKeys(
+ ephPriv: Uint8Array,
+ peerEphPub: Uint8Array,
+ machineId: string,
+ webEphPub: Uint8Array,
+ adapterEphPub: Uint8Array,
+): { c2s: Uint8Array; s2c: Uint8Array } {
+ const shared = x25519.getSharedSecret(ephPriv, peerEphPub)
+ const sess = hkdf(sha256, shared, lvCat(machineId, webEphPub, adapterEphPub), utf8('e2e-sess-v1'), 64)
+ return { c2s: sess.slice(0, 32), s2c: sess.slice(32, 64) }
+}
+export function helloSig(priv: Uint8Array, machineId: string, ephPub: Uint8Array): Uint8Array {
+ return sign(priv, lvCat('e2e-hello-v1', machineId, ephPub))
+}
+export function helloVerify(pub: Uint8Array, machineId: string, ephPub: Uint8Array, sig: Uint8Array): boolean {
+ return verify(pub, lvCat('e2e-hello-v1', machineId, ephPub), sig)
+}
+export function welcomeSig(priv: Uint8Array, machineId: string, webEphPub: Uint8Array, adapterEphPub: Uint8Array): Uint8Array {
+ return sign(priv, lvCat('e2e-welcome-v1', machineId, webEphPub, adapterEphPub))
+}
+export function welcomeVerify(pub: Uint8Array, machineId: string, webEphPub: Uint8Array, adapterEphPub: Uint8Array, sig: Uint8Array): boolean {
+ return verify(pub, lvCat('e2e-welcome-v1', machineId, webEphPub, adapterEphPub), sig)
+}
+
+// ── AEAD (ChaCha20-Poly1305, counter nonce) ──────────────────────────────────────────────────────────
+
+/** 12-byte nonce = 8-byte BE counter || 4 zero bytes. Counter uniqueness is the caller's contract. */
+export function counterNonce(counter: number): Uint8Array {
+ const n = new Uint8Array(12)
+ const dv = new DataView(n.buffer)
+ // JS numbers are safe to 2^53; split high/low 32 bits for the BE counter.
+ dv.setUint32(0, Math.floor(counter / 0x100000000), false)
+ dv.setUint32(4, counter >>> 0, false)
+ return n
+}
+export function aeadSeal(key: Uint8Array, counter: number, aad: Uint8Array, plaintext: Uint8Array): Uint8Array {
+ const n = counterNonce(counter)
+ return chacha20poly1305(key, n, aad).encrypt(plaintext)
+}
+export function aeadOpen(key: Uint8Array, counter: number, aad: Uint8Array, ct: Uint8Array): Uint8Array | null {
+ try { return chacha20poly1305(key, counterNonce(counter), aad).decrypt(ct) } catch { return null }
+}
+
+// ── frame-payload envelope ────────────────────────────────────────────────────────────────────────
+
+export const E2E_VERSION = 1
+export type KeyKind = 'g' | 'p' // g = group key (up broadcast), p = pairwise session
+
+export interface E2eEnvelope {
+ v: number
+ k: KeyKind
+ epoch?: string
+ n: number // counter
+ ct: string // base64
+}
+export interface WrappedPayload { __e2e: E2eEnvelope }
+
+function aadFor(v: number, frameType: string, dbSessionId: string, k: KeyKind, epoch: string): Uint8Array {
+ return utf8(`${v}|${frameType}|${dbSessionId}|${k}|${epoch}`)
+}
+
+/** Encrypt a frame payload → { __e2e }. `payload` is the frame's plaintext payload object. */
+export function wrapPayload(
+ key: Uint8Array,
+ k: KeyKind,
+ counter: number,
+ frameType: string,
+ dbSessionId: string | undefined,
+ payload: unknown,
+ epoch?: string,
+): WrappedPayload {
+ const aad = aadFor(E2E_VERSION, frameType, dbSessionId ?? '', k, epoch ?? '')
+ const pt = utf8(JSON.stringify(payload ?? null))
+ const ct = aeadSeal(key, counter, aad, pt)
+ const env: E2eEnvelope = { v: E2E_VERSION, k, n: counter, ct: b64e(ct) }
+ if (epoch !== undefined) env.epoch = epoch
+ return { __e2e: env }
+}
+/** Decrypt an { __e2e } payload back to the plaintext payload object, or null if it can't be opened. */
+export function unwrapPayload(
+ key: Uint8Array,
+ env: E2eEnvelope,
+ frameType: string,
+ dbSessionId: string | undefined,
+): unknown | null {
+ const aad = aadFor(env.v, frameType, dbSessionId ?? '', env.k, env.epoch ?? '')
+ const pt = aeadOpen(key, env.n, aad, b64d(env.ct))
+ if (!pt) return null
+ try { return JSON.parse(fromUtf8(pt)) } catch { return null }
+}
+export function isWrapped(payload: unknown): payload is WrappedPayload {
+ return !!payload && typeof payload === 'object' && '__e2e' in (payload as Record<string, unknown>)
+}
+
+// ── frame classification ────────────────────────────────────────────────────────────────────────────
+
+/** `up` events (adapter→web, group key) whose payload carries user content. */
+export const ENCRYPTED_UP_TYPES = new Set<string>([
+ 'user_message', 'text_delta', 'thinking_delta', 'thinking_title', 'tool_start', 'tool_end',
+ 'turn_started', 'turn_ended', 'done', 'context_compact', 'turn_summary', 'turn_summary_pending',
+ 'agent_created', 'agent_synced', 'agent_renamed', 'agent_deleted',
+])
+/** RPC replies (`<x>_result`) whose payload is encrypted ONLY when the requester has a session. */
+export const ENCRYPTED_RPC_RESULT_TYPES = new Set<string>([
+ 'session_get_result', 'sessions_list_result', 'agents_list_result', 'models_list_result',
+ 'agent_files_result', 'agent_read_file_result', 'agent_update_result', 'agent_delete_result',
+ 'e2ee_pairings_list_result', 'e2ee_pairing_unpair_result',
+ 'e2ee_pairings_unpair_all_result', 'e2ee_browser_link_create_result',
+ // Device RPC replies that carry adapter content (recap headline/body, new agent name). Must be
+ // ciphertext so the backend relay can't read them — device↔adapter E2EE parity with web.
+ 'agent_recent_result', 'agent_create_result',
+])
+/** Client→adapter frames that carry or can trigger adapter-local user data. */
+export const ENCRYPTED_DOWN_TYPES = new Set<string>([
+ 'message',
+ 'agents_list', 'sessions_list', 'session_get', 'models_list',
+ 'agent_create', 'agent_delete', 'agent_recent', 'agent_update', 'agent_files', 'agent_read_file',
+ 'device_e2ee_pair', 'e2ee_pairings_list', 'e2ee_pairing_unpair',
+ 'e2ee_pairings_unpair_all', 'e2ee_browser_link_create',
+])
+export function isEncryptedUpType(t: string): boolean { return ENCRYPTED_UP_TYPES.has(t) }
+export function isEncryptedRpcResultType(t: string): boolean { return ENCRYPTED_RPC_RESULT_TYPES.has(t) }
+export function isEncryptedDownType(t: string): boolean { return ENCRYPTED_DOWN_TYPES.has(t) }
+
+// ── pairing code ──────────────────────────────────────────────────────────────────────────────────
+
+// Crockford base32 minus ambiguous chars (I,L,O,U) → ~30 bits over 6 chars.
+const CODE_ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'
+export function newPairCode(rng: Rng = defaultRng): string {
+ const bytes = rng(6)
+ let out = ''
+ for (let i = 0; i < 6; i++) out += CODE_ALPHABET[bytes[i] % CODE_ALPHABET.length]
+ return out
+}
+/** Normalize user-typed codes: uppercase, strip separators, map look-alikes to the alphabet. */
+export function normalizeCode(code: string): string {
+ return code.toUpperCase().replace(/[\s\-·_]/g, '')
+ .replace(/I/g, '1').replace(/L/g, '1').replace(/O/g, '0').replace(/U/g, 'V')
+}
+export function newPairId(rng: Rng = defaultRng): Uint8Array {
+ return rng(16)
+}
diff --git a/cli/src/lib/e2ee/manager.test.ts b/cli/src/lib/e2ee/manager.test.ts
new file mode 100644
index 000000000..c987eca35
--- /dev/null
+++ b/cli/src/lib/e2ee/manager.test.ts
@@ -0,0 +1,329 @@
+import { describe, it, expect, beforeAll, beforeEach } from 'vitest'
+import { mkdtempSync, rmSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+
+// The manager transitively imports config/env (validated at load) + writes the paired store to disk,
+// so point ADAPTER_DATA_DIR at a temp dir BEFORE importing it (dynamic import in beforeAll).
+type Frame = Record<string, unknown>
+let C: typeof import('./core.js')
+let makeManager: typeof import('./manager.js')['E2eeManager']
+
+const AGENT = 'f2e0383771b734e4fc00f0bc8ccf060f'
+
+beforeAll(async () => {
+ process.env.ADAPTER_DATA_DIR = mkdtempSync(join(tmpdir(), 'e2ee-mgr-'))
+ C = await import('./core.js')
+ makeManager = (await import('./manager.js')).E2eeManager
+})
+
+// Fresh persisted store (identity + paired.json) per test — the store is disk-backed and shared by
+// every manager instance, so without this pairs accumulate across tests.
+beforeEach(() => {
+ try { rmSync(join(process.env.ADAPTER_DATA_DIR as string, 'e2e'), { recursive: true, force: true }) } catch { /* none */ }
+})
+
+/** A minimal web peer that runs the CPace responder + session handshake against the manager. */
+class WebPeer {
+ identity = C.newIdentity()
+ session?: { c2s: Uint8Array; s2c: Uint8Array; groupKey: Uint8Array; epoch: string; myEph: import('./core.js').Ephemeral }
+ adapterPub?: Uint8Array
+ private pr?: { code: string; pairId: Uint8Array; pairIdB64: string; y?: bigint; Ya?: Uint8Array; Yb?: Uint8Array; isk?: Uint8Array; th?: Uint8Array }
+
+ intent(pairId: Uint8Array): Frame {
+ this.pr = { code: '', pairId, pairIdB64: C.b64e(pairId) }
+ return { type: 'e2e_pair_intent', payload: { requestId: 'r1', pairId: this.pr.pairIdB64, label: 'Chrome · macOS' } }
+ }
+ setCode(code: string): void { if (this.pr) this.pr.code = code }
+
+ /** Handle an adapter→web pake frame; return the reply frame to feed back (or null). */
+ onPake(frame: Frame): Frame | null {
+ const p = frame.payload as Record<string, unknown>
+ const pr = this.pr!
+ const ci = C.pairContext(AGENT)
+ const round = Number(p.round)
+ if (round === 1) {
+ const g = C.cpaceGenerator(pr.code, pr.pairId, ci)
+ const { y, Y } = C.cpaceStart(g)
+ const Ya = C.b64d(String(p.ya))
+ const K = C.cpaceShared(Ya, y)
+ pr.y = y; pr.Ya = Ya; pr.Yb = Y
+ pr.isk = C.cpaceISK(pr.pairId, K, Ya, Y)
+ pr.th = C.transcriptHash(pr.pairId, ci, Ya, Y)
+ const kc = C.kcKeys(pr.isk, ci)
+ return { type: 'e2e_pake', payload: { pairId: pr.pairIdB64, round: 2, yb: C.b64e(Y), mac: C.b64e(C.macTag(kc.web, pr.th)) } }
+ }
+ if (round === 3) {
+ const kc = C.kcKeys(pr.isk!, ci)
+ if (!C.macVerify(kc.adapter, pr.th!, C.b64d(String(p.mac)))) throw new Error('adapter MAC failed')
+ const opened = C.aeadOpen(C.pairKey(pr.isk!, ci), 3, C.utf8('e2e-id'), C.b64d(String(p.enc)))!
+ const adId = JSON.parse(new TextDecoder().decode(opened)) as { id: string; sig: string }
+ if (!C.pairBindVerify(C.b64d(adId.id), pr.th!, C.b64d(adId.sig))) throw new Error('adapter bind sig failed')
+ this.adapterPub = C.b64d(adId.id) // pin
+
+ const sealed = C.aeadSeal(C.pairKey(pr.isk!, ci), 4, C.utf8('e2e-id'), C.utf8(JSON.stringify({ id: C.b64e(this.identity.pub), sig: C.b64e(C.pairBindSig(this.identity.priv, pr.th!)) })))
+ return { type: 'e2e_pake', payload: { pairId: pr.pairIdB64, round: 4, enc: C.b64e(sealed) } }
+ }
+ return null // round 5 (ok/error) — nothing to send
+ }
+
+ hello(): Frame {
+ const eph = C.newEphemeral()
+ this.session = { c2s: new Uint8Array(), s2c: new Uint8Array(), groupKey: new Uint8Array(), epoch: '', myEph: eph }
+ return { type: 'e2e_hello', payload: { identityPub: C.b64e(this.identity.pub), ephPub: C.b64e(eph.pub), sig: C.b64e(C.helloSig(this.identity.priv, AGENT, eph.pub)) } }
+ }
+ onWelcome(frame: Frame, adapterPub: Uint8Array): void {
+ const p = frame.payload as Record<string, unknown>
+ const adapterEphPub = C.b64d(String(p.ephPub))
+ const myEphPub = this.session!.myEph.pub
+ expect(C.welcomeVerify(adapterPub, AGENT, myEphPub, adapterEphPub, C.b64d(String(p.sig)))).toBe(true)
+ const keys = C.sessionKeys(this.session!.myEph.priv, adapterEphPub, AGENT, myEphPub, adapterEphPub)
+ const opened = C.aeadOpen(keys.s2c, 0, C.utf8('e2e-welcome'), C.b64d(String(p.enc)))!
+ const { groupKey, epoch } = JSON.parse(new TextDecoder().decode(opened)) as { groupKey: string; epoch: string }
+ this.session!.c2s = keys.c2s; this.session!.s2c = keys.s2c
+ this.session!.groupKey = C.b64d(groupKey); this.session!.epoch = epoch
+ }
+ onRekey(frame: Frame): void {
+ const p = frame.payload as Record<string, unknown>
+ const opened = C.aeadOpen(this.session!.s2c, Number(p.n), C.utf8('e2e-rekey'), C.b64d(String(p.enc)))!
+ const { groupKey, epoch } = JSON.parse(new TextDecoder().decode(opened)) as { groupKey: string; epoch: string }
+ this.session!.groupKey = C.b64d(groupKey); this.session!.epoch = epoch
+ }
+}
+
+function machine() {
+ const sent: Array<{ connId: string; frame: Frame }> = []
+ const mgr = new makeManager({ machineId: AGENT, sendTo: (connId, frame) => sent.push({ connId, frame }), isConnected: () => true })
+ const takeLast = (type: string): Frame => {
+ for (let i = sent.length - 1; i >= 0; i--) if (sent[i].frame.type === type) return sent[i].frame
+ throw new Error(`no ${type} sent`)
+ }
+ const lastFor = (connId: string, type: string): Frame | undefined => {
+ for (let i = sent.length - 1; i >= 0; i--) if (sent[i].connId === connId && sent[i].frame.type === type) return sent[i].frame
+ return undefined
+ }
+ return { mgr, sent, takeLast, lastFor }
+}
+
+/** Drive a full pairing + session for one connection; returns the established web peer. */
+async function fullPair(h: ReturnType<typeof machine>, conn: string): Promise<WebPeer> {
+ const web = new WebPeer()
+ h.mgr.handleFrame(conn, web.intent(C.newPairId()))
+ const code = C.newPairCode(); web.setCode(code)
+ const pairP = h.mgr.onPair(code)
+ h.mgr.handleFrame(conn, web.onPake(h.lastFor(conn, 'e2e_pake')!)!) // r2 → r3
+ h.mgr.handleFrame(conn, web.onPake(h.lastFor(conn, 'e2e_pake')!)!) // r4 → r5
+ await pairP
+ h.mgr.handleFrame(conn, web.hello())
+ web.onWelcome(h.lastFor(conn, 'e2e_welcome')!, web.adapterPub!)
+ return web
+}
+
+describe('E2eeManager pairing', () => {
+ it('setup-link claim auto-pairs the browser, then hello establishes a session', () => {
+ const h = machine()
+ const web = new WebPeer()
+ const conn = 'setup1'
+ const setup = h.mgr.createSetupToken()
+ const claim = {
+ type: 'e2e_setup_claim',
+ payload: {
+ requestId: 'setup-r1',
+ token: setup.token,
+ identityPub: C.b64e(web.identity.pub),
+ label: 'Chrome · macOS',
+ sig: C.b64e(C.setupClaimSig(web.identity.priv, AGENT, setup.token, web.identity.pub)),
+ },
+ }
+
+ h.mgr.handleFrame(conn, claim)
+ const result = h.lastFor(conn, 'e2e_setup_claim_result')!.payload as Record<string, unknown>
+ expect(result).toMatchObject({ ok: true, requestId: 'setup-r1', fingerprint: h.mgr.fingerprint() })
+ expect(h.mgr.listPaired()[0].fingerprint).toBe(C.fingerprint(web.identity.pub))
+
+ h.mgr.handleFrame(conn, web.hello())
+ web.adapterPub = C.b64d(C.verifySetupToken(setup.token)!.payload.pub)
+ web.onWelcome(h.lastFor(conn, 'e2e_welcome')!, web.adapterPub)
+ expect(h.mgr.hasSession(conn)).toBe(true)
+ })
+
+ it('setup-link claim rejects token reuse', () => {
+ const h = machine()
+ const web1 = new WebPeer()
+ const web2 = new WebPeer()
+ const setup = h.mgr.createSetupToken()
+ h.mgr.handleFrame('setup-a', {
+ type: 'e2e_setup_claim',
+ payload: {
+ requestId: 'a',
+ token: setup.token,
+ identityPub: C.b64e(web1.identity.pub),
+ label: 'Chrome',
+ sig: C.b64e(C.setupClaimSig(web1.identity.priv, AGENT, setup.token, web1.identity.pub)),
+ },
+ })
+ h.mgr.handleFrame('setup-b', {
+ type: 'e2e_setup_claim',
+ payload: {
+ requestId: 'b',
+ token: setup.token,
+ identityPub: C.b64e(web2.identity.pub),
+ label: 'Firefox',
+ sig: C.b64e(C.setupClaimSig(web2.identity.priv, AGENT, setup.token, web2.identity.pub)),
+ },
+ })
+ const result = h.lastFor('setup-b', 'e2e_setup_claim_result')!.payload as Record<string, unknown>
+ expect(result.error).toBe('UNKNOWN_TOKEN')
+ expect(h.mgr.listPaired().length).toBe(1)
+ })
+
+ it('completes a full pairing, pins the browser, and establishes a session + group key', async () => {
+ const { mgr, takeLast } = machine()
+ const web = new WebPeer()
+ const conn = 'conn1'
+ const pairId = C.newPairId()
+
+ mgr.handleFrame(conn, web.intent(pairId))
+ expect((takeLast('e2e_pair_intent_result').payload as Record<string, unknown>).accepted).toBe(true)
+
+ const code = C.newPairCode()
+ web.setCode(code)
+ const pairP = mgr.onPair(code) // sends round 1
+ const r2 = web.onPake(takeLast('e2e_pake'))! // → round 2
+ mgr.handleFrame(conn, r2) // → round 3
+ const r4 = web.onPake(takeLast('e2e_pake'))! // → round 4
+ mgr.handleFrame(conn, r4) // → round 5 + resolves
+ const result = await pairP
+ expect(result.ok).toBe(true)
+ if (result.ok) expect(result.fingerprint).toBe(mgr.fingerprint())
+
+ // session: hello → welcome
+ mgr.handleFrame(conn, web.hello())
+ const welcome = takeLast('e2e_welcome')
+ expect(mgr.hasSession(conn)).toBe(true)
+ web.onWelcome(welcome, web.adapterPub!) // adapter pub was pinned by the web during round 3
+
+ const up = mgr.wrapUp({ type: 'text_delta', dbSessionId: 'sX', payload: { content: 'hello user' } })
+ const env = (up.payload as import('./core.js').WrappedPayload).__e2e
+ expect(env.k).toBe('g')
+ const dec = C.unwrapPayload(web.session!.groupKey, env, 'text_delta', 'sX')
+ expect(dec).toEqual({ content: 'hello user' })
+
+ // down message: web encrypts under c2s → manager decrypts
+ const wrapped = C.wrapPayload(web.session!.c2s, 'p', 0, 'message', undefined, { content: 'fix the bug' })
+ const down = mgr.unwrapDown(conn, { type: 'message', payload: wrapped })
+ expect((down!.payload as Record<string, unknown>).content).toBe('fix the bug')
+ })
+
+ it('rejects a wrong code at the confirmation MAC (round 2)', async () => {
+ const { mgr, takeLast } = machine()
+ const web = new WebPeer()
+ const conn = 'c2'
+ mgr.handleFrame(conn, web.intent(C.newPairId()))
+ const realCode = C.newPairCode()
+ web.setCode('BADCOD') // web believes a different code
+ const pairP = mgr.onPair(realCode) // adapter uses the real code
+ const r2 = web.onPake(takeLast('e2e_pake'))!
+ mgr.handleFrame(conn, r2)
+ const result = await pairP
+ expect(result).toEqual({ ok: false, error: 'CODE_MISMATCH' })
+ const last = takeLast('e2e_pake').payload as Record<string, unknown>
+ expect(last.error).toBe('CODE_MISMATCH')
+ })
+
+ it('e2e_status reports supported + enabled + not-paired for an unknown browser', () => {
+ const { mgr, takeLast } = machine()
+ const id = C.newIdentity()
+ mgr.handleFrame('c3', { type: 'e2e_status', payload: { requestId: 'q', identityPub: C.b64e(id.pub) } })
+ const r = takeLast('e2e_status_result').payload as Record<string, unknown>
+ expect(r).toMatchObject({ supported: true, enabled: true, paired: false })
+ expect(typeof r.fingerprint).toBe('string')
+ })
+
+ it('rejects a hello from an unpaired identity with e2e_denied', () => {
+ const { mgr, takeLast } = machine()
+ const web = new WebPeer()
+ mgr.handleFrame('c4', web.hello())
+ expect((takeLast('e2e_denied').payload as Record<string, unknown>).reason).toBe('unpaired')
+ expect(mgr.hasSession('c4')).toBe(false)
+ })
+
+ it('a second concurrent pair_intent is rejected as PAIRING_BUSY while active', async () => {
+ const { mgr, takeLast } = machine()
+ const web = new WebPeer()
+ mgr.handleFrame('c5', web.intent(C.newPairId()))
+ mgr.onPair(C.newPairCode()) // becomes active (round 1 out)
+ mgr.handleFrame('c6', { type: 'e2e_pair_intent', payload: { requestId: 'r2', pairId: C.b64e(C.newPairId()), label: 'x' } })
+ expect((takeLast('e2e_pair_intent_result').payload as Record<string, unknown>).error).toBe('PAIRING_BUSY')
+ })
+})
+
+describe('E2eeManager revoke', () => {
+ it('lists paired browsers with fingerprint + online flag', async () => {
+ const h = machine()
+ const web = await fullPair(h, 'cx')
+ const list = h.mgr.listPaired()
+ expect(list.length).toBe(1)
+ expect(list[0].online).toBe(true)
+ expect(list[0].fingerprint).toBe(C.fingerprint(web.identity.pub))
+ })
+
+ it('revoke: signals the online browser (e2e_denied), rotates the group key, drops the pin', async () => {
+ const h = machine()
+ const conn = 'cy'
+ const web = await fullPair(h, conn)
+ const oldGroupKey = web.session!.groupKey
+ const before = h.mgr.wrapUp({ type: 'text_delta', dbSessionId: 's', payload: { content: 'pre' } })
+ const oldEpoch = (before.payload as import('./core.js').WrappedPayload).__e2e.epoch
+
+ const r = h.mgr.revoke('1')
+ expect(r.ok).toBe(true)
+ if (r.ok) expect(r.fingerprint).toBe(C.fingerprint(web.identity.pub))
+ // the online session got a revoke signal
+ expect(h.lastFor(conn, 'e2e_denied')).toBeTruthy()
+ expect((h.lastFor(conn, 'e2e_denied')!.payload as Record<string, unknown>).reason).toBe('revoked')
+ // store emptied, session dropped
+ expect(h.mgr.listPaired().length).toBe(0)
+ expect(h.mgr.hasSession(conn)).toBe(false)
+ // group key rotated → new epoch, and the revoked browser's OLD key can't decrypt new events
+ const after = h.mgr.wrapUp({ type: 'text_delta', dbSessionId: 's', payload: { content: 'post' } })
+ const newEnv = (after.payload as import('./core.js').WrappedPayload).__e2e
+ expect(newEnv.epoch).not.toBe(oldEpoch)
+ expect(C.unwrapPayload(oldGroupKey, newEnv, 'text_delta', 's')).toBeNull()
+ })
+
+ it('revoke re-keys the REMAINING browsers so they keep decrypting', async () => {
+ const h = machine()
+ const web1 = await fullPair(h, 'a1')
+ const web2 = await fullPair(h, 'a2')
+ // revoke web1 (list is sorted by pairedAt desc; select by fingerprint to be exact)
+ const r = h.mgr.revoke(C.fingerprint(web1.identity.pub))
+ expect(r.ok).toBe(true)
+ expect((h.lastFor('a1', 'e2e_denied')!.payload as Record<string, unknown>).reason).toBe('revoked')
+ // web2 received a rekey → apply it → can still decrypt the next event
+ web2.onRekey(h.lastFor('a2', 'e2e_rekey')!)
+ const after = h.mgr.wrapUp({ type: 'text_delta', dbSessionId: 's', payload: { content: 'still ok' } })
+ const env = (after.payload as import('./core.js').WrappedPayload).__e2e
+ expect(C.unwrapPayload(web2.session!.groupKey, env, 'text_delta', 's')).toEqual({ content: 'still ok' })
+ expect(h.mgr.listPaired().length).toBe(1)
+ })
+
+ it('revoke-all clears every pair and denies every session', async () => {
+ const h = machine()
+ await fullPair(h, 'z1')
+ await fullPair(h, 'z2')
+ const r = h.mgr.revokeAll()
+ expect(r.count).toBe(2)
+ expect(h.mgr.listPaired().length).toBe(0)
+ expect(h.lastFor('z1', 'e2e_denied')).toBeTruthy()
+ expect(h.lastFor('z2', 'e2e_denied')).toBeTruthy()
+ expect(h.mgr.hasSession('z1')).toBe(false)
+ expect(h.mgr.hasSession('z2')).toBe(false)
+ })
+
+ it('revoke NOT_FOUND for an unknown selector', async () => {
+ const h = machine()
+ await fullPair(h, 'q1')
+ expect(h.mgr.revoke('ZZZZ')).toEqual({ ok: false, error: 'NOT_FOUND' })
+ })
+})
diff --git a/cli/src/lib/e2ee/manager.ts b/cli/src/lib/e2ee/manager.ts
new file mode 100644
index 000000000..801eb13b9
--- /dev/null
+++ b/cli/src/lib/e2ee/manager.ts
@@ -0,0 +1,581 @@
+/**
+ * E2eeManager — the adapter side of web↔adapter E2EE .
+ *
+ * Responsibilities:
+ * - always-on group key (per process, epoch id) that encrypts 1→many `up` user events (wrapUp);
+ * - the CPace pairing state machine (single slot): browser sends e2e_pair_intent → user runs
+ * `harness pair <code>` → onPair() runs CPace toward that connId → pin the browser identity;
+ * - a per-connection session table (X25519 → pairwise keys) established by a signed e2e_hello,
+ * used to decrypt the down `message` frame and to encrypt targeted RPC replies + the group key.
+ *
+ * The relay never sees plaintext user content: only ciphertext envelopes + public PAKE messages.
+ */
+import * as C from './core.js'
+import { E2eeStore } from './store.js'
+
+type Frame = Record<string, unknown>
+
+export type PairResult =
+ | { ok: true; label: string; fingerprint: string }
+ | { ok: false; error: 'NO_INTENT' | 'EXPIRED' | 'CODE_MISMATCH' | 'BACKEND_DOWN' | 'RATE_LIMITED' | 'BUSY' | 'TIMEOUT' | 'CANCELLED' }
+
+interface PairSlot {
+ connId: string
+ pairId: Uint8Array
+ pairIdB64: string
+ label: string
+ role: C.PairRole // 'web' (browser) or 'device' (hardware device) — bound into the CPace channel-binding string
+ expiresAt: number
+ ttlTimer: ReturnType<typeof setTimeout>
+ // set once `harness pair <code>` starts CPace:
+ active?: {
+ y: bigint
+ Ya: Uint8Array
+ isk?: Uint8Array
+ th?: Uint8Array
+ resolve: (r: PairResult) => void
+ roundTimer?: ReturnType<typeof setTimeout>
+ }
+}
+
+export interface PendingPairInfo {
+ label: string
+ expiresAt: number
+ active: boolean
+ role: C.PairRole
+ pairId: string
+}
+
+interface Session {
+ webIdentityPub: string // base64 — the pinned pin used for this session
+ role: C.PairRole
+ c2s: Uint8Array // web → adapter (down message)
+ s2c: Uint8Array // adapter → web (welcome + targeted RPC replies)
+ s2cCounter: number // next send counter (0 was the welcome)
+ c2sRecv: number // highest counter seen (replay guard)
+}
+
+const PAIR_TTL_MS = 60_000
+const ROUND_TIMEOUT_MS = 15_000
+const RATE_WINDOW_MS = 5 * 60_000
+const RATE_MAX = 3
+const MAX_SESSIONS = 64
+
+export interface E2eeManagerDeps {
+ machineId: string
+ /** Send a frame targeted at ONE web connection (adapter→web, sets targetConnId on the wire). */
+ sendTo: (connId: string, frame: Frame) => void
+ /** Send a user-level notification to every logged-in browser for this machine owner. */
+ sendUser?: (frame: Frame) => void
+ /** Is the backend link up right now (for onPair BACKEND_DOWN)? */
+ isConnected: () => boolean
+}
+
+export class E2eeManager {
+ private store = new E2eeStore()
+ private groupKey: Uint8Array
+ private epoch: string
+ private groupCounter = 0
+ private slot: PairSlot | null = null
+ private sessions = new Map<string, Session>()
+ private attempts: number[] = [] // timestamps of FAILED pairings — anti online-guessing rate limit
+ private now: () => number
+ /** Local dashboard port (loopback) — surfaced to the web in e2e_status so it can link there to
+ * approve pairing. Not sensitive (a localhost port); set by the adapter after the hook server binds. */
+ dashboardPort: number | null = null
+
+ constructor(private deps: E2eeManagerDeps, now: () => number = () => Date.now()) {
+ this.store.init()
+ this.groupKey = crypto32()
+ this.epoch = hex8()
+ this.now = now
+ }
+
+ fingerprint(): string { return this.store.fingerprint() }
+ createSetupToken(machineId = this.deps.machineId): { token: string; expiresAt: number; fingerprint: string } {
+ return this.store.createSetupToken(machineId)
+ }
+ hasSession(connId: string): boolean { return this.sessions.has(connId) }
+ sessionRole(connId: string): C.PairRole | null { return this.sessions.get(connId)?.role ?? null }
+ deviceConnected(): boolean { return [...this.sessions.values()].some((s) => s.role === 'device') }
+ dropSessionsByRole(role: C.PairRole): void {
+ for (const [connId, s] of [...this.sessions.entries()]) {
+ if (s.role === role) this.sessions.delete(connId)
+ }
+ }
+
+ /** A browser currently waiting to pair (for the local dashboard), or null. `active` = CPace running. */
+ pendingPair(): PendingPairInfo | null {
+ if (!this.slot) return null
+ return {
+ label: this.slot.label,
+ expiresAt: this.slot.expiresAt,
+ active: !!this.slot.active,
+ role: this.slot.role,
+ pairId: this.slot.pairIdB64,
+ }
+ }
+
+ // ── pair management (list / revoke) ──────────────────────────────────────────────────────────────
+
+ /** Paired clients, most recent first, with a comparable fingerprint. */
+ listPaired(currentConnId?: string): Array<{ fingerprint: string; label: string; pairedAt: number; online: boolean; role: C.PairRole; current: boolean }> {
+ const onlinePubs = new Set([...this.sessions.values()].map((s) => s.webIdentityPub))
+ const currentPub = currentConnId ? this.sessions.get(currentConnId)?.webIdentityPub : undefined
+ return this.store.list()
+ .map((p) => ({ fingerprint: C.fingerprint(C.b64d(p.identityPub)), label: p.label, pairedAt: p.pairedAt, online: onlinePubs.has(p.identityPub), role: p.role, current: p.identityPub === currentPub }))
+ .sort((a, b) => b.pairedAt - a.pairedAt)
+ }
+
+ private findPaired(selector: string): { ok: true; identityPub: string; label: string; fingerprint: string } | { ok: false; error: 'NOT_FOUND' | 'AMBIGUOUS' } {
+ const paired = this.store.list()
+ const norm = (s: string): string => s.toUpperCase().replace(/[·\s-]/g, '')
+ const sel = norm(selector)
+ const idx = /^\d+$/.test(selector) ? Number(selector) - 1 : -1
+ const byIndex = idx >= 0 ? this.listPaired()[idx] : undefined
+ let target = byIndex ? paired.find((p) => C.fingerprint(C.b64d(p.identityPub)) === byIndex.fingerprint) : undefined
+ if (!target) {
+ const matches = paired.filter((p) => norm(C.fingerprint(C.b64d(p.identityPub))).startsWith(sel))
+ if (matches.length > 1) return { ok: false, error: 'AMBIGUOUS' }
+ target = matches[0]
+ }
+ if (!target) return { ok: false, error: 'NOT_FOUND' }
+ return { ok: true, identityPub: target.identityPub, label: target.label, fingerprint: C.fingerprint(C.b64d(target.identityPub)) }
+ }
+
+ private revokeIdentity(identityPub: string): void {
+ this.store.removePaired(identityPub)
+ this.denyAndDropSessionsFor(identityPub)
+ this.rotateGroupKey()
+ }
+
+ /** Revoke ONE paired browser, selected by fingerprint (full or unique prefix, case/·-insensitive) or
+ * by 1-based index into listPaired(). Signals any online session to re-pair + rotates the group key. */
+ revoke(selector: string): { ok: true; label: string; fingerprint: string } | { ok: false; error: 'NOT_FOUND' | 'AMBIGUOUS' } {
+ const found = this.findPaired(selector)
+ if (!found.ok) return found
+ this.revokeIdentity(found.identityPub)
+ return { ok: true, label: found.label, fingerprint: found.fingerprint }
+ }
+
+ revokeFromTrustedWeb(connId: string, p: Record<string, unknown>): void {
+ const requestId = p.requestId
+ const selector = typeof p.selector === 'string' ? p.selector : ''
+ const payload = selector ? this.findPaired(selector) : { ok: false as const, error: 'MISSING_SELECTOR' }
+ if (payload.ok) {
+ const reply = this.wrapRpcReply(connId, 'e2ee_pairing_unpair_result', requestId, { ok: true, label: payload.label, fingerprint: payload.fingerprint })
+ if (reply) this.deps.sendTo(connId, reply)
+ this.revokeIdentity(payload.identityPub)
+ return
+ }
+ const reply = this.wrapRpcReply(connId, 'e2ee_pairing_unpair_result', requestId, { error: payload.error })
+ if (reply) this.deps.sendTo(connId, reply)
+ }
+
+ /** Revoke every paired browser. Signals all online sessions to re-pair + rotates the group key. */
+ revokeAll(): { count: number } {
+ const count = this.store.count()
+ for (const s of [...this.sessions.entries()]) { this.deny(s[0]); this.sessions.delete(s[0]) }
+ this.store.clear()
+ this.rotateGroupKey()
+ return { count }
+ }
+
+ revokeAllFromTrustedWeb(connId: string, requestId: unknown): void {
+ const count = this.store.count()
+ const reply = this.wrapRpcReply(connId, 'e2ee_pairings_unpair_all_result', requestId, { count })
+ if (reply) this.deps.sendTo(connId, reply)
+ this.revokeAll()
+ }
+
+ private deny(connId: string): void {
+ this.deps.sendTo(connId, { type: 'e2e_denied', payload: { reason: 'revoked' } })
+ }
+ private denyAndDropSessionsFor(identityPubB64: string): void {
+ for (const [connId, s] of [...this.sessions.entries()]) {
+ if (s.webIdentityPub === identityPubB64) { this.deny(connId); this.sessions.delete(connId) }
+ }
+ }
+ /** New group key + epoch; re-deliver to the REMAINING (still-paired) sessions so a revoked browser
+ * (which still holds the old key) can no longer decrypt subsequent events. */
+ private rotateGroupKey(): void {
+ this.groupKey = crypto32()
+ this.epoch = hex8()
+ this.groupCounter = 0
+ for (const [connId, s] of this.sessions.entries()) {
+ const enc = C.aeadSeal(s.s2c, s.s2cCounter++, C.utf8('e2e-rekey'), C.utf8(JSON.stringify({ groupKey: C.b64e(this.groupKey), epoch: this.epoch })))
+ this.deps.sendTo(connId, { type: 'e2e_rekey', payload: { enc: C.b64e(enc), n: s.s2cCounter - 1 } })
+ }
+ }
+
+ // ── outbound wrapping ──────────────────────────────────────────────────────────────────────────
+
+ /** Encrypt a broadcast `up` event under the group key if it carries user content; else pass through. */
+ wrapUp(frame: Frame): Frame {
+ const type = frame.type as string | undefined
+ if (!type || !C.isEncryptedUpType(type)) return frame
+ const wrapped = C.wrapPayload(this.groupKey, 'g', this.groupCounter++, type, frame.dbSessionId as string | undefined, frame.payload, this.epoch)
+ return { ...frame, payload: wrapped }
+ }
+
+ /** Encrypt DEVICE-audience user/data frames under the group key. Same group key/epoch/counter space as
+ * wrapUp: one monotonic counter → unique nonces. A paired device holds the group key (delivered in
+ * e2e_welcome); an UNPAIRED device can't decrypt → mandatory pairing. */
+ wrapCommander(frame: Frame): Frame {
+ const type = frame.type as string | undefined
+ // `commander_question` carries the question + its option labels — user content, same as a recap, so it
+ // rides ciphertext too. The device's decrypt is envelope-driven (any `payload.__e2e`), so existing
+ // firmware handles it with no change.
+ if (!type || (type !== 'commander_event' && type !== 'commander_question' && !C.isEncryptedUpType(type))) return frame
+ const wrapped = C.wrapPayload(this.groupKey, 'g', this.groupCounter++, type, frame.dbSessionId as string | undefined, frame.payload, this.epoch)
+ return { ...frame, payload: wrapped }
+ }
+
+ /** Build an encrypted, connection-targeted RPC reply, or null if this conn has no session. */
+ wrapRpcReply(connId: string, resultType: string, requestId: unknown, payload: Record<string, unknown>): Frame | null {
+ const s = this.sessions.get(connId)
+ if (!s) return null
+ const full = { requestId, ...payload }
+ const wrapped = C.wrapPayload(s.s2c, 'p', s.s2cCounter++, resultType, undefined, full)
+ return { type: resultType, payload: wrapped }
+ }
+
+ /** Measure the exact encrypted targeted RPC frame without consuming the send counter. */
+ rpcReplyFrameBytes(connId: string, resultType: string, requestId: unknown, payload: Record<string, unknown>): number | null {
+ const s = this.sessions.get(connId)
+ if (!s) return null
+ const full = { requestId, ...payload }
+ const wrapped = C.wrapPayload(s.s2c, 'p', s.s2cCounter, resultType, undefined, full)
+ return Buffer.byteLength(JSON.stringify({ type: resultType, payload: wrapped }), 'utf8')
+ }
+
+ private wrapTarget(connId: string, type: string, payload: Record<string, unknown>): Frame | null {
+ const s = this.sessions.get(connId)
+ if (!s) return null
+ const wrapped = C.wrapPayload(s.s2c, 'p', s.s2cCounter++, type, undefined, payload)
+ return { type, payload: wrapped }
+ }
+
+ // ── inbound down `message` decryption ────────────────────────────────────────────────────────────
+
+ /** Decrypt an encrypted down `message`; plaintext passes through; undecryptable → null (drop). */
+ unwrapDown(connId: string, frame: Frame): Frame | null {
+ const payload = frame.payload as Record<string, unknown> | undefined
+ if (!payload || !C.isWrapped(payload)) return frame // plaintext (device/transition path)
+ const s = this.sessions.get(connId)
+ if (!s) return null
+ const env = (payload as C.WrappedPayload).__e2e
+ // The relay is NOT trusted, and a client can be buggy/hostile: a structurally malformed envelope
+ // (__e2e null, missing/non-string ct, non-number n) would make the deref / b64d below throw and
+ // crash the daemon. Anything that isn't the expected shape is dropped like an undecryptable frame.
+ if (!env || typeof env !== 'object' || typeof env.n !== 'number' || typeof env.ct !== 'string') return null
+ if (s.c2sRecv !== -1 && env.n <= s.c2sRecv) return null // replay / reorder — drop
+ const plain = C.unwrapPayload(s.c2s, env, frame.type as string, frame.dbSessionId as string | undefined)
+ if (plain === null) return null
+ s.c2sRecv = env.n
+ return { ...frame, payload: plain }
+ }
+
+ // ── e2e_* frame handling (returns true if consumed) ──────────────────────────────────────────────
+
+ handleFrame(connId: string, frame: Frame): boolean {
+ const type = frame.type as string
+ const payload = (frame.payload ?? {}) as Record<string, unknown>
+ switch (type) {
+ case 'e2e_status': return this.onStatus(connId, payload)
+ case 'e2e_setup_claim': return this.onSetupClaim(connId, payload)
+ case 'e2e_pair_intent': return this.onPairIntent(connId, payload)
+ case 'e2e_pair_cancel': return this.onPairCancel(connId, payload)
+ case 'e2e_pake': return this.onPake(connId, payload)
+ case 'e2e_hello': return this.onHello(connId, payload)
+ default: return type.startsWith('e2e_') // consume unknown e2e_* silently
+ }
+ }
+
+ private onStatus(connId: string, p: Record<string, unknown>): boolean {
+ const identityPub = typeof p.identityPub === 'string' ? p.identityPub : ''
+ this.deps.sendTo(connId, {
+ type: 'e2e_status_result',
+ payload: {
+ requestId: p.requestId,
+ supported: true,
+ enabled: true, // mandatory: user events are always group-encrypted
+ paired: identityPub ? this.store.isPaired(identityPub) : false,
+ fingerprint: this.fingerprint(),
+ dashboardPort: this.dashboardPort, // so the web can link to the local dashboard to approve
+ },
+ })
+ return true
+ }
+
+ private onPairIntent(connId: string, p: Record<string, unknown>): boolean {
+ if (this.slot?.active) {
+ this.deps.sendTo(connId, { type: 'e2e_pair_intent_result', payload: { requestId: p.requestId, error: 'PAIRING_BUSY' } })
+ return true
+ }
+ if (this.slot) clearTimeout(this.slot.ttlTimer)
+ const pairIdB64 = typeof p.pairId === 'string' ? p.pairId : ''
+ const label = typeof p.label === 'string' ? p.label.slice(0, 60) : 'browser'
+ const role: C.PairRole = p.role === 'device' ? 'device' : 'web' // the client declares its class
+ if (!pairIdB64) { this.deps.sendTo(connId, { type: 'e2e_pair_intent_result', payload: { requestId: p.requestId, error: 'BAD_INTENT' } }); return true }
+ const ttlTimer = setTimeout(() => { if (this.slot && !this.slot.active) this.slot = null }, PAIR_TTL_MS)
+ this.slot = { connId, pairId: C.b64d(pairIdB64), pairIdB64, label, role, expiresAt: this.now() + PAIR_TTL_MS, ttlTimer }
+ this.deps.sendTo(connId, { type: 'e2e_pair_intent_result', payload: { requestId: p.requestId, accepted: true, ttl: PAIR_TTL_MS / 1000 } })
+ if (role === 'device') this.notifyTrustedWebDevicePair(this.slot)
+ return true
+ }
+
+ private notifyTrustedWebDevicePair(slot: PairSlot): void {
+ const payload = {
+ machineId: this.deps.machineId,
+ label: slot.label,
+ pairId: slot.pairIdB64,
+ expiresAt: slot.expiresAt,
+ computerFingerprint: this.fingerprint(),
+ }
+ this.deps.sendUser?.({ type: 'device_e2ee_pair_pending', payload })
+ for (const [connId, session] of this.sessions.entries()) {
+ if (session.role !== 'web') continue
+ const wrapped = this.wrapTarget(connId, 'device_e2ee_pair_pending', payload)
+ if (wrapped) this.deps.sendTo(connId, wrapped)
+ }
+ }
+
+ private notifyTrustedWebDevicePairCleared(slot: PairSlot, result: 'paired' | 'failed' | 'cancelled'): void {
+ if (slot.role !== 'device') return
+ const payload = {
+ machineId: this.deps.machineId,
+ pairId: slot.pairIdB64,
+ result,
+ computerFingerprint: this.fingerprint(),
+ }
+ this.deps.sendUser?.({ type: 'device_e2ee_pair_cleared', payload })
+ for (const [connId, session] of this.sessions.entries()) {
+ if (session.role !== 'web') continue
+ const wrapped = this.wrapTarget(connId, 'device_e2ee_pair_cleared', payload)
+ if (wrapped) this.deps.sendTo(connId, wrapped)
+ }
+ }
+
+ private onPairCancel(connId: string, p: Record<string, unknown>): boolean {
+ const pairId = typeof p.pairId === 'string' ? p.pairId : ''
+ const slot = this.slot
+ if (!slot || slot.role !== 'device' || slot.connId !== connId || slot.pairIdB64 !== pairId) return true
+ this.notifyTrustedWebDevicePairCleared(slot, 'cancelled')
+ const resolve = slot.active?.resolve
+ this.clearSlot()
+ resolve?.({ ok: false, error: 'CANCELLED' })
+ return true
+ }
+
+ async pairDeviceFromTrustedWeb(connId: string, p: Record<string, unknown>): Promise<void> {
+ const requestId = p.requestId
+ const session = this.sessions.get(connId)
+ if (!session || session.role !== 'web') {
+ this.deps.sendTo(connId, { type: 'device_e2ee_pair_result', payload: { requestId, error: 'UNTRUSTED_WEB' } })
+ return
+ }
+ const slot = this.slot
+ const pairId = typeof p.pairId === 'string' ? p.pairId : ''
+ if (!slot || slot.role !== 'device') {
+ const reply = this.wrapRpcReply(connId, 'device_e2ee_pair_result', requestId, { error: 'NO_DEVICE_INTENT' })
+ if (reply) this.deps.sendTo(connId, reply)
+ return
+ }
+ if (!pairId || pairId !== slot.pairIdB64) {
+ const reply = this.wrapRpcReply(connId, 'device_e2ee_pair_result', requestId, { error: 'STALE_PAIR' })
+ if (reply) this.deps.sendTo(connId, reply)
+ return
+ }
+ const code = C.normalizeCode(String(p.code ?? ''))
+ if (!code) {
+ const reply = this.wrapRpcReply(connId, 'device_e2ee_pair_result', requestId, { error: 'BAD_CODE' })
+ if (reply) this.deps.sendTo(connId, reply)
+ return
+ }
+ const result = await this.onPair(code)
+ const payload = result.ok
+ ? { ok: true, label: result.label, fingerprint: result.fingerprint }
+ : { error: result.error }
+ const reply = this.wrapRpcReply(connId, 'device_e2ee_pair_result', requestId, payload)
+ if (reply) this.deps.sendTo(connId, reply)
+ }
+
+ private onSetupClaim(connId: string, p: Record<string, unknown>): boolean {
+ const requestId = p.requestId
+ const token = typeof p.token === 'string' ? p.token : ''
+ const identityPub = typeof p.identityPub === 'string' ? p.identityPub : ''
+ const sig = typeof p.sig === 'string' ? p.sig : ''
+ const label = typeof p.label === 'string' ? p.label.slice(0, 60) : 'browser'
+ const fail = (error: string): void => {
+ this.deps.sendTo(connId, { type: 'e2e_setup_claim_result', payload: { requestId, error } })
+ }
+ if (!token || !identityPub || !sig) { fail('BAD_CLAIM'); return true }
+ const consumed = this.store.consumeSetupToken(token, this.deps.machineId)
+ if (!consumed.ok) { fail(consumed.error); return true }
+ const pub = C.b64d(identityPub)
+ if (!C.setupClaimVerify(pub, this.deps.machineId, token, C.b64d(sig))) { fail('BAD_SIG'); return true }
+ this.store.addPaired(identityPub, label, this.now(), 'web')
+ this.deps.sendTo(connId, { type: 'e2e_setup_claim_result', payload: { requestId, ok: true, fingerprint: consumed.fingerprint } })
+ return true
+ }
+
+ /** Called by the hook server when the user runs `harness pair <code>`. Resolves when done/failed. */
+ onPair(code: string): Promise<PairResult> {
+ return new Promise<PairResult>((resolve) => {
+ // rate limit
+ // Rate-limit only recent FAILED attempts (anti online-guessing) — successful pairings don't
+ // count, so a user can legitimately pair several browsers in a row.
+ const t = this.now()
+ this.attempts = this.attempts.filter((a) => t - a < RATE_WINDOW_MS)
+ if (this.attempts.length >= RATE_MAX) { resolve({ ok: false, error: 'RATE_LIMITED' }); return }
+ const slot = this.slot
+ if (!slot) { resolve({ ok: false, error: 'NO_INTENT' }); return }
+ if (slot.active) { resolve({ ok: false, error: 'BUSY' }); return }
+ if (this.now() > slot.expiresAt) { this.slot = null; resolve({ ok: false, error: 'EXPIRED' }); return }
+ if (!this.deps.isConnected()) { resolve({ ok: false, error: 'BACKEND_DOWN' }); return }
+ clearTimeout(slot.ttlTimer)
+
+ const ci = C.pairContext(this.deps.machineId, slot.role)
+ const g = C.cpaceGenerator(code, slot.pairId, ci)
+ const { y, Y } = C.cpaceStart(g)
+ const roundTimer = setTimeout(() => this.failPair('TIMEOUT'), ROUND_TIMEOUT_MS)
+ slot.active = { y, Ya: Y, resolve, roundTimer }
+ // round 1 → web (targeted)
+ this.deps.sendTo(slot.connId, { type: 'e2e_pake', payload: { pairId: slot.pairIdB64, round: 1, ya: C.b64e(Y) } })
+ })
+ }
+
+ private onPake(connId: string, p: Record<string, unknown>): boolean {
+ const slot = this.slot
+ if (!slot?.active) return true
+ if (typeof p.pairId !== 'string' || p.pairId !== slot.pairIdB64) return true // not our session
+ const round = Number(p.round)
+ const ci = C.pairContext(this.deps.machineId, slot.role)
+ try {
+ if (round === 2) {
+ const Yb = C.b64d(String(p.yb))
+ const K = C.cpaceShared(Yb, slot.active.y)
+ const isk = C.cpaceISK(slot.pairId, K, slot.active.Ya, Yb)
+ const th = C.transcriptHash(slot.pairId, ci, slot.active.Ya, Yb)
+ const kc = C.kcKeys(isk, ci)
+ if (!C.macVerify(kc.web, th, C.b64d(String(p.mac)))) { this.failPair('CODE_MISMATCH'); return true }
+ slot.active.isk = isk
+ slot.active.th = th
+ // round 3 → adapter MAC + sealed identity (proof of possession)
+ const id = this.store.getIdentity()
+ const sealed = C.aeadSeal(C.pairKey(isk, ci), 3, C.utf8('e2e-id'), C.utf8(JSON.stringify({ id: C.b64e(id.pub), sig: C.b64e(C.pairBindSig(id.priv, th)) })))
+ this.resetRoundTimer(slot)
+ this.deps.sendTo(connId, { type: 'e2e_pake', payload: { pairId: slot.pairIdB64, round: 3, mac: C.b64e(C.macTag(kc.adapter, th)), enc: C.b64e(sealed) } })
+ return true
+ }
+ if (round === 4) {
+ if (!slot.active.isk || !slot.active.th) { this.failPair('TIMEOUT'); return true }
+ const opened = C.aeadOpen(C.pairKey(slot.active.isk, ci), 4, C.utf8('e2e-id'), C.b64d(String(p.enc)))
+ if (!opened) { this.failPair('CODE_MISMATCH'); return true }
+ const webId = JSON.parse(new TextDecoder().decode(opened)) as { id: string; sig: string }
+ if (!C.pairBindVerify(C.b64d(webId.id), slot.active.th, C.b64d(webId.sig))) { this.failPair('CODE_MISMATCH'); return true }
+ // pin the paired client identity
+ this.store.addPaired(webId.id, slot.label, this.now(), slot.role)
+ const fp = this.fingerprint()
+ this.deps.sendTo(connId, { type: 'e2e_pake', payload: { pairId: slot.pairIdB64, round: 5, ok: true, fingerprint: fp } })
+ const resolve = slot.active.resolve
+ this.notifyTrustedWebDevicePairCleared(slot, 'paired')
+ this.clearSlot()
+ resolve({ ok: true, label: slot.label, fingerprint: fp })
+ return true
+ }
+ } catch {
+ this.failPair('CODE_MISMATCH')
+ }
+ return true
+ }
+
+ private onHello(connId: string, p: Record<string, unknown>): boolean {
+ const identityPub = String(p.identityPub ?? '')
+ const ephPubB64 = String(p.ephPub ?? '')
+ const sigB64 = String(p.sig ?? '')
+ if (!identityPub || !ephPubB64 || !sigB64) return true
+ const webEphPub = C.b64d(ephPubB64)
+ const role = this.store.pairedRole(identityPub)
+ if (!role) {
+ this.deps.sendTo(connId, { type: 'e2e_denied', payload: { webEphPub: ephPubB64, reason: 'unpaired' } })
+ return true
+ }
+ if (!C.helloVerify(C.b64d(identityPub), this.deps.machineId, webEphPub, C.b64d(sigB64))) {
+ this.deps.sendTo(connId, { type: 'e2e_denied', payload: { webEphPub: ephPubB64, reason: 'bad_sig' } })
+ return true
+ }
+ const eph = C.newEphemeral()
+ // webEphPub is attacker-controlled: a wrong-length or low-order / invalid curve point makes
+ // x25519.getSharedSecret throw. Refuse such a hello instead of letting the throw crash the daemon.
+ let keys: { c2s: Uint8Array; s2c: Uint8Array }
+ try {
+ keys = C.sessionKeys(eph.priv, webEphPub, this.deps.machineId, webEphPub, eph.pub)
+ } catch {
+ this.deps.sendTo(connId, { type: 'e2e_denied', payload: { webEphPub: ephPubB64, reason: 'bad_key' } })
+ return true
+ }
+ this.evictIfFull()
+ this.sessions.set(connId, { webIdentityPub: identityPub, role, c2s: keys.c2s, s2c: keys.s2c, s2cCounter: 1, c2sRecv: -1 })
+ const id = this.store.getIdentity()
+ const enc = C.aeadSeal(keys.s2c, 0, C.utf8('e2e-welcome'), C.utf8(JSON.stringify({ groupKey: C.b64e(this.groupKey), epoch: this.epoch })))
+ this.deps.sendTo(connId, {
+ type: 'e2e_welcome',
+ payload: {
+ webEphPub: ephPubB64, // echo (self-addressing)
+ ephPub: C.b64e(eph.pub),
+ sig: C.b64e(C.welcomeSig(id.priv, this.deps.machineId, webEphPub, eph.pub)),
+ enc: C.b64e(enc),
+ },
+ })
+ return true
+ }
+
+ /** Drop a session when its web connection closes (called from backendSocket on down close is n/a —
+ * connections are relayed; sessions are pruned by LRU + overwrite-on-new-hello). */
+ dropSession(connId: string): void { this.sessions.delete(connId) }
+
+ // ── helpers ──────────────────────────────────────────────────────────────────────────────────
+
+ private resetRoundTimer(slot: PairSlot): void {
+ if (slot.active?.roundTimer) clearTimeout(slot.active.roundTimer)
+ if (slot.active) slot.active.roundTimer = setTimeout(() => this.failPair('TIMEOUT'), ROUND_TIMEOUT_MS)
+ }
+ private failPair(error: Extract<PairResult, { ok: false }>['error']): void {
+ const slot = this.slot
+ if (!slot?.active) return
+ this.attempts.push(this.now()) // a failed handshake counts toward the anti-guessing rate limit
+ const resolve = slot.active.resolve
+ if (error === 'CODE_MISMATCH') {
+ this.deps.sendTo(slot.connId, { type: 'e2e_pake', payload: { pairId: slot.pairIdB64, round: 5, error } })
+ }
+ this.notifyTrustedWebDevicePairCleared(slot, 'failed')
+ this.clearSlot()
+ resolve({ ok: false, error })
+ }
+ private clearSlot(): void {
+ if (this.slot?.active?.roundTimer) clearTimeout(this.slot.active.roundTimer)
+ if (this.slot) clearTimeout(this.slot.ttlTimer)
+ this.slot = null
+ }
+ private evictIfFull(): void {
+ if (this.sessions.size < MAX_SESSIONS) return
+ const oldest = this.sessions.keys().next().value
+ if (oldest) this.sessions.delete(oldest)
+ }
+}
+
+// Portable 32-byte random + 8-hex epoch (avoid importing extra symbols; reuse core's rng surface).
+function crypto32(): Uint8Array {
+ const a = C.newPairId(), b = C.newPairId()
+ const out = new Uint8Array(32)
+ out.set(a, 0); out.set(b, 16)
+ return out
+}
+function hex8(): string {
+ const b = C.newPairId().slice(0, 4)
+ let s = ''
+ for (let i = 0; i < 4; i++) s += b[i].toString(16).padStart(2, '0')
+ return s
+}
diff --git a/cli/src/lib/e2ee/setup-link.spec.ts b/cli/src/lib/e2ee/setup-link.spec.ts
new file mode 100644
index 000000000..b10d029e8
--- /dev/null
+++ b/cli/src/lib/e2ee/setup-link.spec.ts
@@ -0,0 +1,205 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, rmSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+
+const AGENT = 'f2e0383771b734e4fc00f0bc8ccf060f'
+
+let dataDir = ''
+
+beforeEach(() => {
+ dataDir = mkdtempSync(join(tmpdir(), 'e2ee-setup-'))
+ process.env.ADAPTER_DATA_DIR = dataDir
+ vi.resetModules()
+})
+
+afterEach(() => {
+ rmSync(dataDir, { recursive: true, force: true })
+ delete process.env.ADAPTER_DATA_DIR
+})
+
+async function loadE2ee() {
+ const C = await import('./core.js')
+ const { E2eeStore } = await import('./store.js')
+ const { E2eeManager } = await import('./manager.js')
+ return { C, E2eeStore, E2eeManager }
+}
+
+describe('E2EE setup links', () => {
+ it('creates one-time setup tokens bound to the adapter identity', async () => {
+ const { C, E2eeStore } = await loadE2ee()
+ const store = new E2eeStore()
+ store.init()
+ const setup = store.createSetupToken(AGENT)
+
+ expect(C.verifySetupToken(setup.token, Date.now(), AGENT)?.payload.machineId).toBe(AGENT)
+ expect(store.consumeSetupToken(setup.token, AGENT)).toMatchObject({ ok: true, fingerprint: setup.fingerprint })
+ expect(store.consumeSetupToken(setup.token, AGENT)).toEqual({ ok: false, error: 'UNKNOWN_TOKEN' })
+ })
+
+ it('auto-pairs a browser identity from a valid setup claim and rejects replay', async () => {
+ const { C, E2eeManager } = await loadE2ee()
+ const sent: Array<{ connId: string; frame: Record<string, unknown> }> = []
+ const mgr = new E2eeManager({
+ machineId: AGENT,
+ sendTo: (connId, frame) => sent.push({ connId, frame }),
+ isConnected: () => true,
+ })
+ const web1 = C.newIdentity()
+ const web2 = C.newIdentity()
+ const setup = mgr.createSetupToken()
+
+ mgr.handleFrame('a', {
+ type: 'e2e_setup_claim',
+ payload: {
+ requestId: 'r1',
+ token: setup.token,
+ identityPub: C.b64e(web1.pub),
+ label: 'Chrome',
+ sig: C.b64e(C.setupClaimSig(web1.priv, AGENT, setup.token, web1.pub)),
+ },
+ })
+ expect(sent.at(-1)?.frame.payload).toMatchObject({ requestId: 'r1', ok: true, fingerprint: setup.fingerprint })
+ expect(mgr.listPaired()).toHaveLength(1)
+ expect(mgr.listPaired()[0].fingerprint).toBe(C.fingerprint(web1.pub))
+
+ mgr.handleFrame('b', {
+ type: 'e2e_setup_claim',
+ payload: {
+ requestId: 'r2',
+ token: setup.token,
+ identityPub: C.b64e(web2.pub),
+ label: 'Firefox',
+ sig: C.b64e(C.setupClaimSig(web2.priv, AGENT, setup.token, web2.pub)),
+ },
+ })
+ expect(sent.at(-1)?.frame.payload).toMatchObject({ requestId: 'r2', error: 'UNKNOWN_TOKEN' })
+ expect(mgr.listPaired()).toHaveLength(1)
+ })
+})
+
+describe('trusted web device pairing', () => {
+ it('notifies every trusted web session when a device pairing intent appears', async () => {
+ const { C, E2eeManager } = await loadE2ee()
+ const sent: Array<{ connId: string; frame: Record<string, unknown> }> = []
+ const userSent: Array<Record<string, unknown>> = []
+ const mgr = new E2eeManager({
+ machineId: AGENT,
+ sendTo: (connId, frame) => sent.push({ connId, frame }),
+ sendUser: (frame) => userSent.push(frame),
+ isConnected: () => true,
+ })
+ const key = new Uint8Array(32).fill(7)
+ ;(mgr as unknown as { sessions: Map<string, unknown> }).sessions.set('web1', { webIdentityPub: 'w1', role: 'web', c2s: key, s2c: key, s2cCounter: 1, c2sRecv: -1 })
+ ;(mgr as unknown as { sessions: Map<string, unknown> }).sessions.set('web2', { webIdentityPub: 'w2', role: 'web', c2s: key, s2c: key, s2cCounter: 1, c2sRecv: -1 })
+ ;(mgr as unknown as { sessions: Map<string, unknown> }).sessions.set('device1', { webIdentityPub: 'd1', role: 'device', c2s: key, s2c: key, s2cCounter: 1, c2sRecv: -1 })
+
+ mgr.handleFrame('device-conn', {
+ type: 'e2e_pair_intent',
+ payload: { requestId: 'intent', pairId: C.b64e(C.newPairId()), label: 'Device', role: 'device' },
+ })
+
+ const pending = sent.filter((s) => s.frame.type === 'device_e2ee_pair_pending')
+ expect(pending.map((s) => s.connId).sort()).toEqual(['web1', 'web2'])
+ expect(pending.every((s) => C.isWrapped(s.frame.payload))).toBe(true)
+ expect(sent.some((s) => s.connId === 'device1' && s.frame.type === 'device_e2ee_pair_pending')).toBe(false)
+ expect(userSent).toHaveLength(1)
+ expect(userSent[0]).toMatchObject({
+ type: 'device_e2ee_pair_pending',
+ payload: { machineId: AGENT, label: 'Device' },
+ })
+ })
+
+ it('rejects stale trusted-web device pair requests without starting CPace', async () => {
+ const { C, E2eeManager } = await loadE2ee()
+ const sent: Array<{ connId: string; frame: Record<string, unknown> }> = []
+ const mgr = new E2eeManager({
+ machineId: AGENT,
+ sendTo: (connId, frame) => sent.push({ connId, frame }),
+ isConnected: () => true,
+ })
+ const key = new Uint8Array(32).fill(9)
+ ;(mgr as unknown as { sessions: Map<string, unknown> }).sessions.set('web1', { webIdentityPub: 'w1', role: 'web', c2s: key, s2c: key, s2cCounter: 1, c2sRecv: -1 })
+ mgr.handleFrame('device-conn', {
+ type: 'e2e_pair_intent',
+ payload: { requestId: 'intent', pairId: C.b64e(C.newPairId()), label: 'Device', role: 'device' },
+ })
+
+ await mgr.pairDeviceFromTrustedWeb('web1', { requestId: 'pair', pairId: 'old-pair', code: 'ABC123' })
+
+ const result = sent.find((s) => s.connId === 'web1' && s.frame.type === 'device_e2ee_pair_result')
+ expect(result?.frame.payload).toBeTruthy()
+ expect(C.isWrapped(result?.frame.payload)).toBe(true)
+ const opened = C.unwrapPayload(key, (result!.frame.payload as { __e2e: never }).__e2e, 'device_e2ee_pair_result', undefined) as { requestId?: string; error?: string } | null
+ expect(opened).toMatchObject({ requestId: 'pair', error: 'STALE_PAIR' })
+ })
+
+ it('clears trusted web popups when the device cancels pairing', async () => {
+ const { C, E2eeManager } = await loadE2ee()
+ const sent: Array<{ connId: string; frame: Record<string, unknown> }> = []
+ const userSent: Array<Record<string, unknown>> = []
+ const mgr = new E2eeManager({
+ machineId: AGENT,
+ sendTo: (connId, frame) => sent.push({ connId, frame }),
+ sendUser: (frame) => userSent.push(frame),
+ isConnected: () => true,
+ })
+ const key = new Uint8Array(32).fill(11)
+ ;(mgr as unknown as { sessions: Map<string, unknown> }).sessions.set('web1', { webIdentityPub: 'w1', role: 'web', c2s: key, s2c: key, s2cCounter: 1, c2sRecv: -1 })
+ const pairId = C.b64e(C.newPairId())
+ mgr.handleFrame('device-conn', {
+ type: 'e2e_pair_intent',
+ payload: { requestId: 'intent', pairId, label: 'Device', role: 'device' },
+ })
+
+ mgr.handleFrame('device-conn', { type: 'e2e_pair_cancel', payload: { pairId } })
+
+ expect(mgr.pendingPair()).toBeNull()
+ const cleared = sent.find((s) => s.connId === 'web1' && s.frame.type === 'device_e2ee_pair_cleared')
+ expect(C.isWrapped(cleared?.frame.payload)).toBe(true)
+ const opened = C.unwrapPayload(key, (cleared!.frame.payload as { __e2e: never }).__e2e, 'device_e2ee_pair_cleared', undefined) as { pairId?: string; result?: string } | null
+ expect(opened).toMatchObject({ pairId, result: 'cancelled' })
+ expect(userSent.at(-1)).toMatchObject({
+ type: 'device_e2ee_pair_cleared',
+ payload: { machineId: AGENT, pairId, result: 'cancelled' },
+ })
+ })
+})
+
+describe('trusted web pairing management', () => {
+ it('marks the requesting browser and sends encrypted unpair result before revoking it', async () => {
+ const { C, E2eeManager } = await loadE2ee()
+ const sent: Array<{ connId: string; frame: Record<string, unknown> }> = []
+ const mgr = new E2eeManager({
+ machineId: AGENT,
+ sendTo: (connId, frame) => sent.push({ connId, frame }),
+ isConnected: () => true,
+ })
+ const web = C.newIdentity()
+ const setup = mgr.createSetupToken()
+ mgr.handleFrame('setup', {
+ type: 'e2e_setup_claim',
+ payload: {
+ requestId: 'setup',
+ token: setup.token,
+ identityPub: C.b64e(web.pub),
+ label: 'Chrome',
+ sig: C.b64e(C.setupClaimSig(web.priv, AGENT, setup.token, web.pub)),
+ },
+ })
+
+ const key = new Uint8Array(32).fill(13)
+ ;(mgr as unknown as { sessions: Map<string, unknown> }).sessions.set('web1', { webIdentityPub: C.b64e(web.pub), role: 'web', c2s: key, s2c: key, s2cCounter: 1, c2sRecv: -1 })
+ const current = mgr.listPaired('web1')[0]
+ expect(current.current).toBe(true)
+
+ mgr.revokeFromTrustedWeb('web1', { requestId: 'revoke', selector: current.fingerprint })
+
+ const result = sent.find((s) => s.connId === 'web1' && s.frame.type === 'e2ee_pairing_unpair_result')
+ expect(C.isWrapped(result?.frame.payload)).toBe(true)
+ const opened = C.unwrapPayload(key, (result!.frame.payload as { __e2e: never }).__e2e, 'e2ee_pairing_unpair_result', undefined) as { requestId?: string; ok?: boolean; fingerprint?: string } | null
+ expect(opened).toMatchObject({ requestId: 'revoke', ok: true, fingerprint: current.fingerprint })
+ expect(sent.some((s) => s.connId === 'web1' && s.frame.type === 'e2e_denied')).toBe(true)
+ expect(mgr.listPaired()).toHaveLength(0)
+ })
+})
diff --git a/cli/src/lib/e2ee/store.ts b/cli/src/lib/e2ee/store.ts
new file mode 100644
index 000000000..d77462f63
--- /dev/null
+++ b/cli/src/lib/e2ee/store.ts
@@ -0,0 +1,142 @@
+/**
+ * E2EE persistence for the adapter: the computer's long-term identity keypair and the set of pinned
+ * (paired) browser identities. Both live under ${ADAPTER_DATA_DIR}/e2e/, written immediately with
+ * mode 0600 (pairs are rare — no debounce needed). The identity key is the root of trust; losing it
+ * forces every browser to re-pair.
+ */
+import { mkdirSync, readFileSync, writeFileSync } from 'fs'
+import { join } from 'path'
+import { env } from '../../config/env.js'
+import { newIdentity, newPairId, b64e, b64d, fingerprint, encodeSetupToken, verifySetupToken, type Identity, type PairRole } from './core.js'
+
+const DIR = join(env.ADAPTER_DATA_DIR, 'e2e')
+const IDENTITY_FILE = join(DIR, 'identity.json')
+const PAIRED_FILE = join(DIR, 'paired.json')
+const SETUP_FILE = join(DIR, 'setup-nonces.json')
+const SETUP_TTL_MS = 7 * 24 * 60 * 60 * 1000
+
+export interface PairedClient {
+ identityPub: string // base64 Ed25519 pubkey — the pin
+ label: string // UA-derived, for display
+ pairedAt: number
+ role: PairRole // old records without this field are treated as web
+}
+interface PendingSetupNonce {
+ nonce: string
+ expiresAt: number
+ machineId?: string
+}
+
+function writeSecure(file: string, data: unknown): void {
+ mkdirSync(DIR, { recursive: true })
+ writeFileSync(file, JSON.stringify(data, null, 2), { mode: 0o600 })
+}
+
+export class E2eeStore {
+ private identity: Identity | null = null
+ private paired = new Map<string, PairedClient>() // key = identityPub (base64)
+ private setupNonces = new Map<string, PendingSetupNonce>() // key = nonce
+
+ /** Load or create the computer identity keypair; load the paired set. Idempotent. */
+ init(): Identity {
+ if (this.identity) return this.identity
+ try {
+ const raw = JSON.parse(readFileSync(IDENTITY_FILE, 'utf-8')) as { priv: string; pub: string }
+ this.identity = { priv: b64d(raw.priv), pub: b64d(raw.pub) }
+ } catch {
+ const id = newIdentity()
+ writeSecure(IDENTITY_FILE, { priv: b64e(id.priv), pub: b64e(id.pub) })
+ this.identity = id
+ }
+ try {
+ const arr = JSON.parse(readFileSync(PAIRED_FILE, 'utf-8')) as Array<PairedClient & { role?: PairRole }>
+ for (const p of arr) {
+ if (p?.identityPub) this.paired.set(p.identityPub, { ...p, role: p.role === 'device' ? 'device' : 'web' })
+ }
+ } catch { /* none yet */ }
+ try {
+ const arr = JSON.parse(readFileSync(SETUP_FILE, 'utf-8')) as PendingSetupNonce[]
+ const now = Date.now()
+ for (const p of arr) {
+ if (p?.nonce && p.expiresAt > now) this.setupNonces.set(p.nonce, p)
+ }
+ } catch { /* none yet */ }
+ return this.identity
+ }
+
+ getIdentity(): Identity {
+ return this.identity ?? this.init()
+ }
+
+ /** The computer identity's human fingerprint (shown on both CLI and browser to compare). */
+ fingerprint(): string {
+ return fingerprint(this.getIdentity().pub)
+ }
+
+ isPaired(identityPubB64: string): boolean {
+ return this.paired.has(identityPubB64)
+ }
+
+ pairedRole(identityPubB64: string): PairRole | null {
+ return this.paired.get(identityPubB64)?.role ?? null
+ }
+
+ addPaired(identityPubB64: string, label: string, at: number, role: PairRole = 'web'): void {
+ this.paired.set(identityPubB64, { identityPub: identityPubB64, label, pairedAt: at, role })
+ writeSecure(PAIRED_FILE, [...this.paired.values()])
+ }
+
+ removePaired(identityPubB64: string): void {
+ if (this.paired.delete(identityPubB64)) writeSecure(PAIRED_FILE, [...this.paired.values()])
+ }
+
+ /** Revoke ALL paired browsers. Returns the number removed. */
+ clear(): number {
+ const n = this.paired.size
+ if (n) { this.paired.clear(); writeSecure(PAIRED_FILE, []) }
+ return n
+ }
+
+ list(): PairedClient[] {
+ return [...this.paired.values()]
+ }
+ count(): number {
+ return this.paired.size
+ }
+
+ createSetupToken(machineId?: string, ttlMs = SETUP_TTL_MS): { token: string; expiresAt: number; fingerprint: string } {
+ const id = this.getIdentity()
+ const nonce = b64e(newPairId()).replace(/=+$/g, '')
+ const expiresAt = Date.now() + ttlMs
+ const payload = { v: 1 as const, typ: 'adapter-e2ee-setup' as const, pub: b64e(id.pub), nonce, exp: expiresAt, ...(machineId ? { machineId } : {}) }
+ this.setupNonces.set(nonce, { nonce, expiresAt, ...(machineId ? { machineId } : {}) })
+ this.writeSetupNonces()
+ return { token: encodeSetupToken(payload, id.priv), expiresAt, fingerprint: this.fingerprint() }
+ }
+
+ consumeSetupToken(token: string, expectedMachineId?: string): { ok: true; fingerprint: string } | { ok: false; error: 'BAD_TOKEN' | 'WRONG_ADAPTER' | 'UNKNOWN_TOKEN' | 'EXPIRED' | 'WRONG_MACHINE' } {
+ const id = this.getIdentity()
+ const verified = verifySetupToken(token, Date.now(), expectedMachineId)
+ if (!verified) return { ok: false, error: 'BAD_TOKEN' }
+ if (b64e(id.pub) !== verified.payload.pub) return { ok: false, error: 'WRONG_ADAPTER' }
+ const pending = this.setupNonces.get(verified.payload.nonce)
+ if (!pending) return { ok: false, error: 'UNKNOWN_TOKEN' }
+ if (pending.expiresAt < Date.now() || verified.payload.exp < Date.now()) {
+ this.setupNonces.delete(verified.payload.nonce)
+ this.writeSetupNonces()
+ return { ok: false, error: 'EXPIRED' }
+ }
+ if (expectedMachineId && pending.machineId && pending.machineId !== expectedMachineId) return { ok: false, error: 'WRONG_MACHINE' }
+ this.setupNonces.delete(verified.payload.nonce)
+ this.writeSetupNonces()
+ return { ok: true, fingerprint: this.fingerprint() }
+ }
+
+ private writeSetupNonces(): void {
+ const now = Date.now()
+ for (const [nonce, p] of [...this.setupNonces.entries()]) {
+ if (p.expiresAt <= now) this.setupNonces.delete(nonce)
+ }
+ writeSecure(SETUP_FILE, [...this.setupNonces.values()])
+ }
+}
diff --git a/cli/src/lib/engineBin.spec.ts b/cli/src/lib/engineBin.spec.ts
new file mode 100644
index 000000000..edf9e91fd
--- /dev/null
+++ b/cli/src/lib/engineBin.spec.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest'
+import { ENGINES, aliasesFor, engineCommand, resolveEngine } from './engineBin.js'
+
+/**
+ * Help text is the only place these names are ever seen, so the danger is advertising a command that
+ * does not work — printing `harness cmd` while the parser only answers to `harness commandcode` would
+ * be a help page that lies. These tests tie the two together.
+ */
+describe('engine command names', () => {
+ it('advertises Command Code under the name its own CLI uses', () => {
+ // `cmd <command> [options]` is command-code 1.6.0's usage line, and `cmd` its package's first bin.
+ expect(engineCommand('commandcode')).toBe('cmd')
+ // The id keeps working — it is what the web, the device and the DB call this engine.
+ expect(aliasesFor('commandcode')).toContain('commandcode')
+ expect(aliasesFor('commandcode')).not.toContain('cmd')
+ })
+
+ it('every name it prints is a name it accepts', () => {
+ for (const engine of ENGINES) {
+ expect(resolveEngine(engineCommand(engine)), `primary for ${engine}`).toBe(engine)
+ for (const alias of aliasesFor(engine)) {
+ expect(resolveEngine(alias), `alias ${alias}`).toBe(engine)
+ }
+ }
+ })
+
+ it('leaves engines whose CLI matches their id alone', () => {
+ expect(engineCommand('claude')).toBe('claude')
+ expect(aliasesFor('claude')).toEqual([])
+ // Cursor ships extra binaries but is still called cursor here.
+ expect(engineCommand('cursor')).toBe('cursor')
+ expect(aliasesFor('cursor')).toEqual(['agent', 'cursor-agent'])
+ })
+})
diff --git a/cli/src/lib/engineBin.ts b/cli/src/lib/engineBin.ts
new file mode 100644
index 000000000..3c44fca18
--- /dev/null
+++ b/cli/src/lib/engineBin.ts
@@ -0,0 +1,85 @@
+/**
+ * Per-engine CLI binary resolution — the single source of truth shared by the recap one-shots
+ * (`oneshot.ts`) and the `harness <engine>` launcher (`launch.ts`).
+ *
+ * Each engine honours its own `*_PATH` override (see `config/env.ts`) and otherwise resolves the plain
+ * command name from PATH. `codex` reads `process.env` directly because it has no entry in the validated
+ * env schema (only `CODEX_HOME` does) — kept as-is so behaviour matches what oneshot.ts already shipped.
+ */
+
+import { env } from '../config/env.js'
+import type { AgentEngine } from '../engines/types.js'
+
+/** Every engine the adapter can drive — also the set of `harness <engine>` launch subcommands. */
+export const ENGINES: readonly AgentEngine[] = [
+ 'claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin',
+] as const
+
+/**
+ * Names users actually type. Several CLIs install more than one binary for the same product, and people
+ * reach for whichever one they know — `machine cmd` must mean Command Code, not "unknown command".
+ * Verified on disk: command-code ships `commandcode`/`command-code`/`cmd`/`cmdc` (all the same file), and
+ * Cursor's CLI is installed as `agent` / `cursor-agent`.
+ */
+const ENGINE_ALIASES: Readonly<Record<string, AgentEngine>> = {
+ cmd: 'commandcode',
+ cmdc: 'commandcode',
+ 'command-code': 'commandcode',
+ agent: 'cursor',
+ 'cursor-agent': 'cursor',
+}
+
+/**
+ * The spelling machine ADVERTISES for an engine, which is not always its id. The id is an internal name
+ * — it travels to the web, the device and the database, so it stays put — but help should tell you to
+ * type what the vendor calls their CLI. Command Code's own usage line reads `cmd <command> [options]`
+ * and `cmd` is the first entry in its package `bin`, so the command to show is `machine cmd`.
+ */
+const PRIMARY_COMMAND: Partial<Record<AgentEngine, string>> = {
+ commandcode: 'cmd',
+}
+
+/** What to print as `machine <this>` for an engine. Every spelling still works — see aliasesFor. */
+export function engineCommand(engine: AgentEngine): string {
+ return PRIMARY_COMMAND[engine] ?? engine
+}
+
+export function isEngine(value: string): value is AgentEngine {
+ return (ENGINES as readonly string[]).includes(value)
+}
+
+/** The canonical engine for a name the user typed (its own id or a known alias), else null. */
+export function resolveEngine(value: string): AgentEngine | null {
+ if (isEngine(value)) return value
+ return ENGINE_ALIASES[value] ?? null
+}
+
+/**
+ * The other accepted spellings for an engine, for help text — everything it answers to except the one
+ * already shown as primary. That includes the engine's own id when the primary is a vendor name, so
+ * `harness commandcode` is still documented as working, just no longer the headline.
+ */
+export function aliasesFor(engine: AgentEngine): string[] {
+ const primary = engineCommand(engine)
+ const spellings = [
+ engine as string,
+ ...Object.entries(ENGINE_ALIASES).filter(([, e]) => e === engine).map(([a]) => a),
+ ]
+ return spellings.filter((name) => name !== primary)
+}
+
+export function engineBin(engine: AgentEngine): string {
+ switch (engine) {
+ case 'claude': return env.CLAUDE_PATH || 'claude'
+ case 'codex': return process.env.CODEX_PATH || 'codex'
+ // Cursor's CLI is installed as `agent`, not `cursor`.
+ case 'cursor': return env.CURSOR_PATH || 'agent'
+ case 'opencode': return env.OPENCODE_PATH || 'opencode'
+ case 'pi': return env.PI_PATH || 'pi'
+ case 'hermes': return env.HERMES_PATH || 'hermes'
+ // command-code's package `bin` lists `cmd` first and its README uses it — that is the official
+ // command. (`cmdc`/`command-code`/`commandcode` are the same file, kept as aliases below.)
+ case 'commandcode': return env.COMMANDCODE_PATH || 'cmd'
+ case 'devin': return env.DEVIN_PATH || 'devin'
+ }
+}
diff --git a/cli/src/lib/enginePermissions.spec.ts b/cli/src/lib/enginePermissions.spec.ts
new file mode 100644
index 000000000..d79ddf2bf
--- /dev/null
+++ b/cli/src/lib/enginePermissions.spec.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it } from 'vitest'
+import { ENGINES } from './engineBin.js'
+import { permissionArgsFor, userChosePermissions } from './enginePermissions.js'
+
+/**
+ * This table is a contract with eight CLIs, read from their own `--help` on 2026-07-31. When one renames
+ * a flag the adapter cannot tell — the agent simply starts asking for permission again, from a pane
+ * nobody is watching. These assertions are the tripwire, so they name the flags literally.
+ */
+describe('default permission flags', () => {
+ it('gives every engine the flags read from its --help', () => {
+ const flags = Object.fromEntries(ENGINES.map((e) => [e, permissionArgsFor(e, [])]))
+ expect(flags).toEqual({
+ claude: ['--dangerously-skip-permissions'],
+ // Undocumented, but identical to --dangerously-bypass-approvals-and-sandbox: both land on
+ // "permissions: YOLO mode" (compared side by side on codex 0.145.0).
+ codex: ['--yolo'],
+ cursor: ['--force', '--trust'],
+ opencode: ['--auto'],
+ // Pi has no permission bypass at all — only the trust axis. Inventing one would fail to start.
+ pi: ['--approve'],
+ hermes: ['--yolo'],
+ commandcode: ['--yolo', '--trust'],
+ // Devin's flag takes a value. Its trust gate has no flag, and harness will not write config to get
+ // past one — so `harness devin` still asks once per directory, on purpose.
+ devin: ['--permission-mode', 'dangerous'],
+ })
+ })
+
+ it('adds nothing once the user has named a policy of their own', () => {
+ // The ONLY opt-out, so it has to cover flags machine would never add itself.
+ expect(permissionArgsFor('codex', ['--sandbox', 'read-only'])).toEqual([])
+ expect(permissionArgsFor('codex', ['-a', 'untrusted'])).toEqual([])
+ expect(permissionArgsFor('claude', ['--permission-mode', 'plan'])).toEqual([])
+ expect(permissionArgsFor('devin', ['--permission-mode', 'accept-edits'])).toEqual([])
+ expect(permissionArgsFor('hermes', ['--safe-mode'])).toEqual([])
+ // `--flag=value` is the same choice as `--flag value`.
+ expect(permissionArgsFor('claude', ['--permission-mode=plan'])).toEqual([])
+ })
+
+ it('keeps the two axes independent', () => {
+ // Trusting the directory says nothing about whether the agent may run a command.
+ expect(permissionArgsFor('cursor', ['--trust'])).toEqual(['--force'])
+ expect(permissionArgsFor('commandcode', ['-t'])).toEqual(['--yolo'])
+ // …and choosing a permission policy must not withdraw the trust flag.
+ expect(permissionArgsFor('commandcode', ['--permission-mode', 'standard'])).toEqual(['--trust'])
+ expect(permissionArgsFor('cursor', ['--force'])).toEqual(['--trust'])
+ })
+
+ it('leaves ordinary arguments alone', () => {
+ expect(permissionArgsFor('claude', ['--resume', 'abc', '--model', 'opus']))
+ .toEqual(['--dangerously-skip-permissions'])
+ expect(permissionArgsFor('devin', ['-r'])).toEqual(['--permission-mode', 'dangerous'])
+ // `-t` is Command Code's trust flag but Pi's TOOL allowlist — the same spelling, different axis.
+ expect(permissionArgsFor('pi', ['-t', 'read,bash'])).toEqual(['--approve'])
+ })
+
+ it('reports whether the user chose anything at all', () => {
+ expect(userChosePermissions('codex', ['--sandbox', 'read-only'])).toBe(true)
+ expect(userChosePermissions('cursor', ['--trust'])).toBe(true)
+ expect(userChosePermissions('claude', ['--resume', 'abc'])).toBe(false)
+ expect(userChosePermissions('hermes', [])).toBe(false)
+ })
+})
diff --git a/cli/src/lib/enginePermissions.ts b/cli/src/lib/enginePermissions.ts
new file mode 100644
index 000000000..2212393cd
--- /dev/null
+++ b/cli/src/lib/enginePermissions.ts
@@ -0,0 +1,130 @@
+/**
+ * How `harness <engine>` starts an agent that nobody is sitting in front of.
+ *
+ * A CLI's defaults assume a human at the keyboard: it asks before each action, and several ask "do you
+ * trust this directory?" before they will start at all. Driven from web or device there is no one to
+ * answer, so the session simply stops — verified on 2026-07-31, when devin, cursor and Command Code each
+ * sat on a trust prompt until someone walked to the computer. So the launcher supplies the flags itself.
+ *
+ * **Flags are the whole mechanism** (owner call, 2026-07-31): machine never edits a CLI's config to get
+ * past a gate. Where a CLI takes trust through its config file and offers no flag — devin, and codex
+ * since 0.145 — the prompt is left for the user to answer once, in the pane, at first start. A stale
+ * entry written into someone's real config outlives the session that wanted it; a one-time keypress does
+ * not.
+ *
+ * **Passing your own flag is the only opt-out**, by design — which is why `owned` below is deliberately
+ * wider than what gets added.
+ *
+ * Every flag here was read from the installed CLI's own `--help` on 2026-07-31. When a CLI renames one,
+ * this table goes silently wrong — `enginePermissions.spec.ts` is the tripwire.
+ */
+
+import type { AgentEngine } from '../engines/types.js'
+
+/**
+ * The two things a CLI can block on. They are kept apart because a user chooses them apart: `--trust`
+ * says nothing about whether the agent may run a command, so naming one must not suppress the other.
+ */
+type Axis = 'permission' | 'trust'
+
+interface EnginePermissions {
+ /** What the launcher adds, per axis. `args` is the whole flag — value included where one is needed. */
+ add: Array<{ axis: Axis; args: string[] }>
+ /**
+ * Flags meaning "the user already decided this axis", checked as whole argv entries (and `--flag=value`).
+ * WIDER than `add` on purpose: someone who typed `codex --sandbox read-only` has chosen a policy, and
+ * appending a bypass-everything flag on top would quietly invert what they asked for.
+ */
+ owned: Partial<Record<Axis, string[]>>
+}
+
+const PERMISSIONS: Readonly<Record<AgentEngine, EnginePermissions>> = {
+ claude: {
+ add: [{ axis: 'permission', args: ['--dangerously-skip-permissions'] }],
+ owned: {
+ permission: [
+ '--dangerously-skip-permissions', '--allow-dangerously-skip-permissions', '--permission-mode',
+ ],
+ },
+ },
+ // `--yolo` is undocumented (absent from `--help`) but real, and identical to the long spelling: both
+ // start the session at `permissions: YOLO mode`, compared side by side on 0.145.0. Codex also gates
+ // directory trust — no flag reaches it, and `-c projects."<dir>".trust_level` does not either (tried),
+ // so that one prompt stays with the user.
+ codex: {
+ add: [{ axis: 'permission', args: ['--yolo'] }],
+ owned: {
+ permission: [
+ '--yolo', '--dangerously-bypass-approvals-and-sandbox', '--full-auto',
+ '-a', '--ask-for-approval', '-s', '--sandbox',
+ ],
+ },
+ },
+ cursor: {
+ add: [
+ { axis: 'permission', args: ['--force'] },
+ { axis: 'trust', args: ['--trust'] },
+ ],
+ owned: {
+ permission: ['-f', '--force', '--yolo', '--sandbox'],
+ trust: ['--trust'],
+ },
+ },
+ opencode: {
+ add: [{ axis: 'permission', args: ['--auto'] }],
+ owned: { permission: ['--auto'] },
+ },
+ // Pi has NO permission bypass: its model is tool allow/deny lists (`--tools`, `--exclude-tools`) with no
+ // "approve everything" switch, so only the trust axis is set. Inventing a flag would just fail to start.
+ pi: {
+ add: [{ axis: 'trust', args: ['--approve'] }],
+ owned: {
+ permission: ['--tools', '-t', '--no-tools', '-nt', '--exclude-tools', '-xt'],
+ trust: ['--approve', '-a'],
+ },
+ },
+ hermes: {
+ add: [{ axis: 'permission', args: ['--yolo'] }],
+ owned: { permission: ['--yolo', '--safe-mode'] },
+ },
+ commandcode: {
+ add: [
+ { axis: 'permission', args: ['--yolo'] },
+ { axis: 'trust', args: ['--trust'] },
+ ],
+ owned: {
+ permission: ['--yolo', '--dangerously-skip-permissions', '--permission-mode'],
+ trust: ['-t', '--trust'],
+ },
+ },
+ // Devin's trust gate has no flag at all, so `harness devin` still shows it once per directory. (The
+ // recap one-shot, which runs headless in a scratch dir machine itself made, trusts that one path —
+ // see trustDevinWorkspace in oneshot.ts.)
+ devin: {
+ add: [{ axis: 'permission', args: ['--permission-mode', 'dangerous'] }],
+ owned: { permission: ['--permission-mode'] },
+ },
+}
+
+/** Whole-argv-entry match; `--flag=value` is the same choice as `--flag value`. */
+function mentions(argv: string[], flags: string[] | undefined): boolean {
+ if (!flags?.length) return false
+ const seen = new Set(argv.map((arg) => (arg.startsWith('--') ? arg.split('=')[0] : arg)))
+ return flags.some((flag) => seen.has(flag))
+}
+
+/** The flags to append for this engine — each axis dropped only if the user spoke to THAT axis. */
+export function permissionArgsFor(engine: AgentEngine, argv: string[] = []): string[] {
+ const spec = PERMISSIONS[engine]
+ const chosen: Record<Axis, boolean> = {
+ permission: mentions(argv, spec.owned.permission),
+ trust: mentions(argv, spec.owned.trust),
+ }
+ return spec.add.filter((entry) => !chosen[entry.axis]).flatMap((entry) => entry.args)
+}
+
+/** True when the user already chose a permission or trust policy for this engine. */
+export function userChosePermissions(engine: AgentEngine, argv: string[]): boolean {
+ const { owned } = PERMISSIONS[engine]
+ return mentions(argv, [...(owned.permission ?? []), ...(owned.trust ?? [])])
+}
diff --git a/cli/src/lib/files.ts b/cli/src/lib/files.ts
new file mode 100644
index 000000000..cadf9cc7f
--- /dev/null
+++ b/cli/src/lib/files.ts
@@ -0,0 +1,99 @@
+/**
+ * Project file listing + reading for the remote agent's SourceTree ("Files" panel).
+ * Root = the tmux session's working dir. Mirrors the hosted runtime’s tree/ignore/hidden-path rules
+ * (ProjectService.readDirRecursive / readFile) and ADDS the file-view guard: only files ≤ 5 MB and
+ * only text files (binary → rejected). Self-contained — no dependencies outside this package.
+ */
+
+import { readdirSync, statSync, readFileSync } from 'fs'
+import { join, resolve, sep, basename } from 'path'
+
+export interface FileNode {
+ name: string
+ type: 'file' | 'dir'
+ size?: number
+ children?: FileNode[]
+}
+
+export const MAX_FILE_BYTES = 5 * 1024 * 1024 // 5 MiB
+
+// Exact-name ignores (kept in sync with the hosted runtime’s readDirRecursive). Any dot-prefixed entry
+// (`.git`, `.next`, `.vite`, `.claude`, `.env`, `.node_modules`, …) is excluded separately below,
+// so only the non-dot names need listing here.
+const EXCLUDE = new Set(['node_modules', 'dist', 'logs', 'CLAUDE.md'])
+
+/** Hidden entry: any name starting with a dot (e.g. `.git`, `.env`, `.node_modules`). */
+const isHidden = (name: string): boolean => name.startsWith('.')
+
+// Soft caps so a giant arbitrary user dir can't hang / flood the walk (the hosted runtime has none, but the
+// remote root is an arbitrary machine dir).
+const MAX_NODES = 20_000
+const MAX_DEPTH = 12
+
+/** Recursive eager file tree under `root`, excluding EXCLUDE names, dirs-before-files sorted. */
+export function listFileTree(root: string): FileNode[] {
+ let count = 0
+ let truncated = false
+
+ const walk = (dir: string, depth: number): FileNode[] => {
+ if (depth > MAX_DEPTH || count >= MAX_NODES) { truncated = true; return [] }
+ let entries
+ try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return [] }
+ const nodes: FileNode[] = []
+ for (const entry of entries) {
+ if (isHidden(entry.name) || EXCLUDE.has(entry.name)) continue
+ if (count >= MAX_NODES) { truncated = true; break }
+ count++
+ const full = join(dir, entry.name)
+ if (entry.isDirectory()) {
+ nodes.push({ name: entry.name, type: 'dir', children: walk(full, depth + 1) })
+ } else if (entry.isFile()) {
+ let size = 0
+ try { size = statSync(full).size } catch { /* ignore */ }
+ nodes.push({ name: entry.name, type: 'file', size })
+ }
+ }
+ return nodes.sort((a, b) => (a.type !== b.type ? (a.type === 'dir' ? -1 : 1) : a.name.localeCompare(b.name)))
+ }
+
+ const tree = walk(root, 0)
+ if (truncated) console.warn(`[files] tree truncated at ${count} nodes for ${root}`)
+ return tree
+}
+
+/** First 8 KB has a NUL byte → treat as binary (git/grep heuristic; extension-agnostic). */
+function isBinary(buf: Buffer): boolean {
+ const n = Math.min(buf.length, 8192)
+ for (let i = 0; i < n; i++) if (buf[i] === 0) return true
+ return false
+}
+
+/**
+ * Read one project file. Throws a bare error CODE on any rule violation:
+ * NOT_FOUND | FILE_TOO_LARGE | NOT_TEXT
+ */
+export function readProjectFile(root: string, relPath: string): string {
+ // Hidden/internal blocks (mirror the hosted runtime). Any dot-prefixed path segment (`.env`, `.git/…`,
+ // `.claude/…`, and `..`) is hidden from the tree, so it must not be readable directly either.
+ if (
+ basename(relPath) === 'CLAUDE.md' ||
+ relPath.startsWith('logs/') ||
+ relPath.split(/[/\\]/).some((seg) => seg.startsWith('.'))
+ ) {
+ throw new Error('NOT_FOUND')
+ }
+ // Path-traversal safety: the resolved path must stay under root.
+ const rootResolved = resolve(root)
+ const full = resolve(rootResolved, relPath)
+ if (full !== rootResolved && !full.startsWith(rootResolved + sep)) throw new Error('NOT_FOUND')
+
+ let st
+ try { st = statSync(full) } catch { throw new Error('NOT_FOUND') }
+ if (!st.isFile()) throw new Error('NOT_FOUND')
+ if (st.size > MAX_FILE_BYTES) throw new Error('FILE_TOO_LARGE')
+
+ let buf: Buffer
+ try { buf = readFileSync(full) } catch { throw new Error('NOT_FOUND') }
+ if (isBinary(buf)) throw new Error('NOT_TEXT')
+ return buf.toString('utf-8')
+}
diff --git a/cli/src/lib/goalCommand.spec.ts b/cli/src/lib/goalCommand.spec.ts
new file mode 100644
index 000000000..26ad88d4f
--- /dev/null
+++ b/cli/src/lib/goalCommand.spec.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it } from 'vitest'
+import { adaptGoalCommand, adaptSlashCommand, engineSupportsGoal, engineSupportsLoop } from './goalCommand.js'
+
+const ALL_ENGINES = ['claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin'] as const
+const NON_LOOP = ['codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin'] as const
+
+describe('adaptGoalCommand', () => {
+ it('keeps /goal verbatim for engines with a native /goal (claude, codex)', () => {
+ for (const engine of ['claude', 'codex'] as const) {
+ expect(engineSupportsGoal(engine)).toBe(true)
+ expect(adaptGoalCommand('/goal fix the bug', engine)).toBe('/goal fix the bug')
+ expect(adaptGoalCommand('/goal', engine)).toBe('/goal')
+ }
+ })
+
+ it('drops the leading slash for engines without /goal (cursor, opencode, pi)', () => {
+ for (const engine of ['cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin'] as const) {
+ expect(engineSupportsGoal(engine)).toBe(false)
+ expect(adaptGoalCommand('/goal fix the bug', engine)).toBe('goal fix the bug')
+ expect(adaptGoalCommand('/goal', engine)).toBe('goal')
+ expect(adaptGoalCommand('/goal\nmulti line', engine)).toBe('goal\nmulti line')
+ }
+ })
+
+ it('leaves non-/goal content untouched for every engine', () => {
+ for (const engine of ['claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin'] as const) {
+ expect(adaptGoalCommand('just a normal message', engine)).toBe('just a normal message')
+ expect(adaptGoalCommand('/model gpt-5', engine)).toBe('/model gpt-5')
+ expect(adaptGoalCommand('/goalkeeper stats', engine)).toBe('/goalkeeper stats') // /goal must be a whole token
+ expect(adaptGoalCommand('tell me the /goal', engine)).toBe('tell me the /goal') // only a LEADING token is adapted
+ }
+ })
+})
+
+describe('adaptSlashCommand — /loop', () => {
+ it('keeps /loop verbatim for claude, the only engine that has one', () => {
+ expect(engineSupportsLoop('claude')).toBe(true)
+ expect(adaptSlashCommand('/loop keep fixing tests', 'claude')).toBe('/loop keep fixing tests')
+ expect(adaptSlashCommand('/loop', 'claude')).toBe('/loop')
+ })
+
+ it('drops the WHOLE token elsewhere — "loop" left behind is not an instruction', () => {
+ for (const engine of NON_LOOP) {
+ expect(engineSupportsLoop(engine)).toBe(false)
+ expect(adaptSlashCommand('/loop keep fixing tests', engine)).toBe('keep fixing tests')
+ expect(adaptSlashCommand('/loop\nmulti line', engine)).toBe('multi line')
+ }
+ })
+
+ it('never turns a bare /loop into an empty message', () => {
+ // An empty submission looks like the turn was sent and then does nothing at all, which is worse
+ // than a stray word.
+ for (const engine of NON_LOOP) expect(adaptSlashCommand('/loop', engine)).toBe('loop')
+ })
+
+ it('leaves non-/loop content untouched for every engine', () => {
+ for (const engine of ALL_ENGINES) {
+ expect(adaptSlashCommand('/loopback through the proxy', engine)).toBe('/loopback through the proxy')
+ expect(adaptSlashCommand('run it in a /loop', engine)).toBe('run it in a /loop')
+ expect(adaptSlashCommand('just a normal message', engine)).toBe('just a normal message')
+ }
+ })
+
+ it('adapts goal and loop independently on the same engine', () => {
+ // codex has /goal but not /loop — the two rules must not interfere.
+ expect(adaptSlashCommand('/goal ship it', 'codex')).toBe('/goal ship it')
+ expect(adaptSlashCommand('/loop ship it', 'codex')).toBe('ship it')
+ expect(adaptSlashCommand('/goal ship it', 'cursor')).toBe('goal ship it')
+ expect(adaptSlashCommand('/loop ship it', 'cursor')).toBe('ship it')
+ })
+})
diff --git a/cli/src/lib/goalCommand.ts b/cli/src/lib/goalCommand.ts
new file mode 100644
index 000000000..fdcb6b851
--- /dev/null
+++ b/cli/src/lib/goalCommand.ts
@@ -0,0 +1,67 @@
+import type { AgentEngine } from '../engines/types.js'
+
+/**
+ * Per-engine handling of the two slash commands the DEVICE can put in front of an utterance.
+ *
+ * The device sends a mode with each voice turn and the backend prepends the matching command, so a
+ * literal `/goal <text>` or `/loop <text>` arrives here as ordinary message content (a web-typed one
+ * looks identical). Injecting an unknown slash command into a CLI that has none trips a visible
+ * unknown-command error in the user's terminal, so each is adapted per engine.
+ *
+ * The backend prepends UNCONDITIONALLY — it does not know the engine. On the routed path it picks the
+ * agent only after transcribing, and `voice_route` replies without an engine field; the fixed-agent and
+ * route_confirm paths would each need their own lookup. This module is the one place that always knows
+ * the engine (`registry.get(sessionId).engine`), so the filtering lives here for every path at once.
+ */
+
+/**
+ * `/goal`:
+ * - claude — native Stop-hook goal mechanism
+ * - codex — goal-context (`<codex_internal_context source="goal">`) + CCR `thread/goal/set`
+ */
+export const GOAL_ENGINES: ReadonlySet<AgentEngine> = new Set<AgentEngine>(['claude', 'codex'])
+
+/**
+ * `/loop`: Claude only. Codex is deliberately NOT here — it has its own goal-context mechanism, and
+ * assuming a `/loop` it may not have would put an error in front of the user instead of running their
+ * turn. Add an engine here only once its `/loop` has actually been seen to work.
+ */
+export const LOOP_ENGINES: ReadonlySet<AgentEngine> = new Set<AgentEngine>(['claude'])
+
+export function engineSupportsGoal(engine: AgentEngine): boolean {
+ return GOAL_ENGINES.has(engine)
+}
+
+export function engineSupportsLoop(engine: AgentEngine): boolean {
+ return LOOP_ENGINES.has(engine)
+}
+
+/**
+ * Adapt a leading `/goal` or `/loop` token to what this engine can actually take. The two degrade
+ * DIFFERENTLY, on purpose:
+ *
+ * `/goal fix the bug` → `goal fix the bug` — the word survives, because it still reads as an
+ * instruction the agent can act on.
+ * `/loop fix the bug` → `fix the bug` — the whole token goes. "loop" left in the text is not
+ * an instruction, it is a stray word the agent would
+ * have to interpret; the turn should just run normally.
+ *
+ * Only a LEADING whole token is touched, so `/goalkeeper` and `/loopback` are never rewritten.
+ * Anything else is returned unchanged.
+ */
+export function adaptSlashCommand(content: string, engine: AgentEngine): string {
+ if (!engineSupportsGoal(engine)) content = content.replace(/^\/goal(?=\s|$)/, 'goal')
+ if (!engineSupportsLoop(engine)) {
+ content = content.replace(/^\/loop\s+/, '') // `/loop fix it` → `fix it`
+ // A BARE `/loop` degrades to the word instead of vanishing: stripping it would submit an empty
+ // message to the CLI, which is worse than a stray word — the turn would look like it was sent and
+ // nothing would happen.
+ content = content.replace(/^\/loop$/, 'loop')
+ }
+ return content
+}
+
+/** @deprecated Use {@link adaptSlashCommand}; kept so older call sites keep compiling. */
+export function adaptGoalCommand(content: string, engine: AgentEngine): string {
+ return adaptSlashCommand(content, engine)
+}
diff --git a/cli/src/lib/hooks.spec.ts b/cli/src/lib/hooks.spec.ts
new file mode 100644
index 000000000..e752efcc0
--- /dev/null
+++ b/cli/src/lib/hooks.spec.ts
@@ -0,0 +1,316 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
+import { join } from 'path'
+import { tmpdir } from 'os'
+
+let codexHome = ''
+let cursorHome = ''
+let hermesHome = ''
+let commandcodeHome = ''
+let devinConfigPath = ''
+
+async function loadHooks() {
+ vi.resetModules()
+ process.env.CODEX_HOME = codexHome
+ process.env.CURSOR_HOME = cursorHome
+ process.env.HERMES_HOME = hermesHome
+ process.env.COMMANDCODE_HOME = commandcodeHome
+ process.env.DEVIN_CONFIG_PATH = devinConfigPath
+ return import('./hooks.js')
+}
+
+describe('Codex hook installation', () => {
+ beforeEach(() => {
+ codexHome = mkdtempSync(join(tmpdir(), 'adapter-codex-hooks-'))
+ cursorHome = mkdtempSync(join(tmpdir(), 'adapter-cursor-hooks-'))
+ })
+
+ afterEach(() => {
+ rmSync(codexHome, { recursive: true, force: true })
+ rmSync(cursorHome, { recursive: true, force: true })
+ delete process.env.CODEX_HOME
+ delete process.env.CURSOR_HOME
+ })
+
+ it('merges foreign hooks and installs the canonical catch hooks idempotently', async () => {
+ const file = join(codexHome, 'hooks.json')
+ writeFileSync(file, JSON.stringify({
+ custom: { keep: true },
+ hooks: {
+ SessionStart: [{ matcher: 'resume', hooks: [{ type: 'command', command: 'foreign-start' }] }],
+ UserPromptSubmit: [{ hooks: [{ type: 'command', command: 'foreign-prompt' }] }],
+ },
+ }))
+
+ const { installCodexHooks } = await loadHooks()
+ installCodexHooks(19473)
+ const first = readFileSync(file, 'utf-8')
+ const parsed = JSON.parse(first)
+
+ expect(parsed.custom).toEqual({ keep: true })
+ expect(parsed.hooks.SessionStart).toHaveLength(2)
+ expect(parsed.hooks.SessionStart[1]).toMatchObject({ matcher: 'startup|resume|clear|compact' })
+ expect(parsed.hooks.UserPromptSubmit).toHaveLength(2)
+ expect(parsed.hooks.UserPromptSubmit[1]).not.toHaveProperty('matcher')
+ expect(parsed.hooks.UserPromptSubmit[1].hooks[0].command).toContain('--engine codex')
+
+ installCodexHooks(19473)
+ expect(readFileSync(file, 'utf-8')).toBe(first)
+ })
+
+ it('leaves malformed user hook configuration untouched', async () => {
+ const file = join(codexHome, 'hooks.json')
+ writeFileSync(file, '{not-json')
+
+ const { installCodexHooks } = await loadHooks()
+ installCodexHooks(19473)
+
+ expect(readFileSync(file, 'utf-8')).toBe('{not-json')
+ expect(existsSync(`${file}.${process.pid}.tmp`)).toBe(false)
+ })
+
+ it('merges Cursor lower-camel hooks and preserves foreign entries idempotently', async () => {
+ const file = join(cursorHome, 'hooks.json')
+ writeFileSync(file, JSON.stringify({
+ version: 7,
+ custom: true,
+ hooks: { preToolUse: [{ command: 'foreign-task', failClosed: true }] },
+ }))
+ const { installCursorHooks } = await loadHooks()
+ installCursorHooks(19473)
+ const first = readFileSync(file, 'utf8')
+ const parsed = JSON.parse(first)
+ expect(parsed.version).toBe(7)
+ expect(parsed.custom).toBe(true)
+ expect(parsed.hooks.preToolUse).toHaveLength(2)
+ expect(parsed.hooks.preToolUse[1]).toMatchObject({ failClosed: false })
+ expect(parsed.hooks.preToolUse[1].command).toContain('--engine cursor')
+ expect(Object.keys(parsed.hooks)).toEqual([
+ 'preToolUse', 'sessionStart', 'beforeSubmitPrompt', 'stop', 'sessionEnd',
+ ])
+
+ installCursorHooks(19473)
+ expect(readFileSync(file, 'utf8')).toBe(first)
+ })
+})
+
+describe('Command Code hook installation', () => {
+ let file = ''
+
+ beforeEach(() => {
+ commandcodeHome = mkdtempSync(join(tmpdir(), 'adapter-commandcode-hooks-'))
+ file = join(commandcodeHome, 'settings.json')
+ })
+
+ afterEach(() => {
+ rmSync(commandcodeHome, { recursive: true, force: true })
+ delete process.env.COMMANDCODE_HOME
+ })
+
+ it('installs SessionStart/PreToolUse/Stop, preserves foreign hooks, and is idempotent', async () => {
+ writeFileSync(file, JSON.stringify({
+ model: 'taste-1',
+ hooks: { SessionStart: [{ hooks: [{ type: 'command', command: '/usr/local/bin/my-own.sh' }] }] },
+ }))
+
+ const { installCommandCodeHooks } = await loadHooks()
+ installCommandCodeHooks(18473)
+
+ const out = JSON.parse(readFileSync(file, 'utf8')) as {
+ model: string
+ hooks: Record<string, Array<{ hooks: Array<{ command: string }> }>>
+ }
+ expect(out.model).toBe('taste-1') // untouched
+ expect(Object.keys(out.hooks).sort()).toEqual(['PreToolUse', 'SessionStart', 'Stop'])
+ expect(out.hooks.SessionStart[0].hooks[0].command).toBe('/usr/local/bin/my-own.sh') // foreign kept
+ expect(out.hooks.SessionStart[1].hooks[0].command).toContain('--engine commandcode')
+ expect(out.hooks.Stop[0].hooks[0].command).toContain('notify.mjs')
+ // PreToolUse is this engine's ONLY live turn-open signal — it has no UserPromptSubmit and flushes its
+ // transcript when the turn ends, so without this hook the device never shows a working state.
+ expect(out.hooks.PreToolUse[0].hooks[0].command).toContain('--engine commandcode')
+
+ const first = readFileSync(file, 'utf8')
+ installCommandCodeHooks(18473)
+ expect(readFileSync(file, 'utf8')).toBe(first)
+ })
+
+ it('collapses duplicate machine blocks left by an older path/port', async () => {
+ const stale = (port: number) => ({ hooks: [{ type: 'command', command: `node '/old/notify.mjs' --port ${port} --engine commandcode` }] })
+ writeFileSync(file, JSON.stringify({ hooks: { SessionStart: [stale(19918), stale(19919)], Stop: [stale(19918)] } }))
+
+ const { installCommandCodeHooks } = await loadHooks()
+ installCommandCodeHooks(18473)
+
+ const out = JSON.parse(readFileSync(file, 'utf8')) as { hooks: Record<string, unknown[]> }
+ expect(out.hooks.SessionStart).toHaveLength(1) // both stale entries collapsed into the canonical one
+ expect(out.hooks.Stop).toHaveLength(1)
+ expect(JSON.stringify(out)).not.toContain('19918')
+ })
+
+ it('leaves a malformed settings file untouched', async () => {
+ writeFileSync(file, '{ not json')
+ const { installCommandCodeHooks } = await loadHooks()
+ installCommandCodeHooks(18473)
+ expect(readFileSync(file, 'utf8')).toBe('{ not json')
+ })
+})
+
+/**
+ * Devin reads Claude's hook schema verbatim, but its hooks nest inside the user's GENERAL config
+ * (`~/.config/devin/config.json`) next to `devin.org_id`, `theme_mode`, … — so the installer must merge,
+ * never rewrite the file.
+ */
+describe('Devin hook installation', () => {
+ let dir = ''
+
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'adapter-devin-hooks-'))
+ devinConfigPath = join(dir, 'config.json')
+ })
+
+ afterEach(() => {
+ rmSync(dir, { recursive: true, force: true })
+ delete process.env.DEVIN_CONFIG_PATH
+ })
+
+ it('merges into the user config, keeps foreign hooks, and is idempotent', async () => {
+ writeFileSync(devinConfigPath, JSON.stringify({
+ version: 1,
+ devin: { org_id: 'org-9fc31c99' },
+ theme_mode: 'dark',
+ hooks: { SessionStart: [{ hooks: [{ type: 'command', command: '/usr/local/bin/my-own.sh' }] }] },
+ }))
+
+ const { installDevinHooks } = await loadHooks()
+ installDevinHooks(18473)
+
+ const out = JSON.parse(readFileSync(devinConfigPath, 'utf8')) as {
+ version: number
+ devin: { org_id: string }
+ theme_mode: string
+ hooks: Record<string, Array<{ hooks: Array<{ command: string }> }>>
+ }
+ expect(out.version).toBe(1) // unrelated settings survive
+ expect(out.devin.org_id).toBe('org-9fc31c99')
+ expect(out.theme_mode).toBe('dark')
+ expect(Object.keys(out.hooks).sort()).toEqual(['SessionEnd', 'SessionStart', 'Stop', 'UserPromptSubmit'])
+ expect(out.hooks.SessionStart[0].hooks[0].command).toBe('/usr/local/bin/my-own.sh') // foreign kept
+ expect(out.hooks.SessionStart[1].hooks[0].command).toContain('--engine devin')
+ expect(out.hooks.Stop[0].hooks[0].command).toContain('notify.mjs')
+
+ const first = readFileSync(devinConfigPath, 'utf8')
+ installDevinHooks(18473)
+ expect(readFileSync(devinConfigPath, 'utf8')).toBe(first)
+ })
+
+ it('collapses duplicate machine blocks left by an older path/port', async () => {
+ const stale = (port: number) => ({ hooks: [{ type: 'command', command: `node '/old/notify.mjs' --port ${port} --engine devin` }] })
+ writeFileSync(devinConfigPath, JSON.stringify({ hooks: { SessionStart: [stale(19918), stale(19919)], Stop: [stale(19918)] } }))
+
+ const { installDevinHooks } = await loadHooks()
+ installDevinHooks(18473)
+
+ const out = JSON.parse(readFileSync(devinConfigPath, 'utf8')) as { hooks: Record<string, unknown[]> }
+ expect(out.hooks.SessionStart).toHaveLength(1)
+ expect(out.hooks.Stop).toHaveLength(1)
+ expect(JSON.stringify(out)).not.toContain('19918')
+ })
+
+ it('creates the config when the user has none, and leaves a malformed one untouched', async () => {
+ const { installDevinHooks } = await loadHooks()
+ installDevinHooks(18473)
+ expect(JSON.parse(readFileSync(devinConfigPath, 'utf8')).hooks.SessionStart).toHaveLength(1)
+
+ writeFileSync(devinConfigPath, '{ not json')
+ const again = await loadHooks()
+ again.installDevinHooks(18473)
+ expect(readFileSync(devinConfigPath, 'utf8')).toBe('{ not json')
+ })
+})
+
+/**
+ * Hermes is the only engine whose hooks live in the user's MAIN config (YAML, not a dedicated JSON
+ * file), so the installer owns a delimited block instead of rebuilding a JSON array. A duplicate
+ * top-level `hooks:` key is silently resolved by YAML to the LAST one, which once pinned live sessions
+ * to a stale block — these tests lock the collapse behaviour in.
+ */
+describe('Hermes hook installation', () => {
+ const USER_CONFIG = 'model:\n default: minimax/minimax-m3\n provider: custom\n'
+ let file = ''
+
+ beforeEach(() => {
+ hermesHome = mkdtempSync(join(tmpdir(), 'adapter-hermes-hooks-'))
+ file = join(hermesHome, 'config.yaml')
+ writeFileSync(file, USER_CONFIG)
+ })
+
+ afterEach(() => {
+ rmSync(hermesHome, { recursive: true, force: true })
+ delete process.env.HERMES_HOME
+ })
+
+ const blockCount = (text: string): number => (text.match(/^hooks:/gm) ?? []).length
+ const ports = (text: string): string[] => [...new Set([...text.matchAll(/--port (\d+)/g)].map((m) => m[1]))]
+
+ it('appends one managed block, preserves the user config, and allowlists the command', async () => {
+ const { installHermesHooks } = await loadHooks()
+ installHermesHooks(18473)
+
+ const out = readFileSync(file, 'utf8')
+ expect(blockCount(out)).toBe(1)
+ expect(out).toContain('model:\n default: minimax/minimax-m3') // user config untouched
+ expect(out).toContain('on_session_start:')
+ expect(out).toContain('pre_llm_call:') // the beacon: on_session_start does not fire on resume
+
+ // Hermes silently skips a hook whose exact (event, command) pair is not allowlisted.
+ const allow = JSON.parse(readFileSync(join(hermesHome, 'shell-hooks-allowlist.json'), 'utf8')) as {
+ approvals: Array<{ event: string; command: string }>
+ }
+ const cmd = /- command: "(.*?)"/.exec(out)![1]
+ expect(allow.approvals.map((a) => a.event).sort()).toEqual(['on_session_start', 'pre_llm_call'])
+ for (const a of allow.approvals) expect(a.command).toBe(cmd)
+ })
+
+ it('collapses to a SINGLE block when the port changes (no duplicate hooks: key)', async () => {
+ const { installHermesHooks } = await loadHooks()
+ installHermesHooks(18473)
+ installHermesHooks(19999)
+
+ const out = readFileSync(file, 'utf8')
+ expect(blockCount(out)).toBe(1)
+ expect(ports(out)).toEqual(['19999']) // the stale port is gone, not merely appended past
+ })
+
+ it('absorbs an orphaned block left by an earlier buggy install', async () => {
+ // Shape produced by the old marker-only rewrite: a bare `hooks:` mapping with our command.
+ const orphan = "\nhooks:\n pre_llm_call:\n - command: \"node '/old/notify.mjs' --port 19918 --engine hermes\"\n timeout: 10\n"
+ writeFileSync(file, `${USER_CONFIG}${orphan}`)
+
+ const { installHermesHooks } = await loadHooks()
+ installHermesHooks(18473)
+
+ const out = readFileSync(file, 'utf8')
+ expect(blockCount(out)).toBe(1)
+ expect(out).not.toContain('19918')
+ expect(out).toContain('model:\n default: minimax/minimax-m3')
+ })
+
+ it('is idempotent', async () => {
+ const { installHermesHooks } = await loadHooks()
+ installHermesHooks(18473)
+ const first = readFileSync(file, 'utf8')
+ installHermesHooks(18473)
+ expect(readFileSync(file, 'utf8')).toBe(first)
+ })
+
+ it('leaves a user-owned hooks: block untouched', async () => {
+ const mine = `${USER_CONFIG}\nhooks:\n pre_tool_call:\n - command: "/usr/local/bin/my-guard.sh"\n timeout: 5\n`
+ writeFileSync(file, mine)
+
+ const { installHermesHooks } = await loadHooks()
+ installHermesHooks(18473)
+
+ expect(readFileSync(file, 'utf8')).toBe(mine)
+ expect(existsSync(join(hermesHome, 'shell-hooks-allowlist.json'))).toBe(false)
+ })
+})
diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.ts
new file mode 100644
index 000000000..771f7cc44
--- /dev/null
+++ b/cli/src/lib/hooks.ts
@@ -0,0 +1,620 @@
+/**
+ * Idempotently install the machine-adapter SessionStart / SessionEnd hooks into
+ * ~/.claude/settings.json so claude notifies us when tmux sessions start/end.
+ *
+ * Changes to settings.json take effect on the NEXT claude session start.
+ */
+
+import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync } from 'fs'
+import { join, dirname } from 'path'
+import { homedir } from 'os'
+import { fileURLToPath } from 'url'
+import { env } from '../config/env.js'
+import type { AgentEngine } from '../engines/types.js'
+
+const SETTINGS_PATH = join(homedir(), '.claude', 'settings.json')
+const CODEX_HOOKS_PATH = join(process.env.CODEX_HOME || join(homedir(), '.codex'), 'hooks.json')
+const CURSOR_HOOKS_PATH = join(process.env.CURSOR_HOME || join(homedir(), '.cursor'), 'hooks.json')
+
+// notify.mjs location depends on the layout (import.meta.url is the REAL executing file at runtime):
+// - packaged/bundled: cli.js at ~/.harness/cli/cli.js → notify.mjs is a SIBLING (dist/ bundle too).
+// - dev/per-file: hooks.js at <appRoot>/{src,dist}/lib/ → notify.mjs at ../../hook/notify.mjs.
+// Prefer the sibling, fall back to the dev path.
+const cliDir = dirname(fileURLToPath(import.meta.url))
+const HOOK_SCRIPT =
+ [join(cliDir, 'notify.mjs'), join(cliDir, '..', '..', 'hook', 'notify.mjs')].find(existsSync) ??
+ join(cliDir, '..', '..', 'hook', 'notify.mjs')
+
+// SessionStart/End drive register/remove. UserPromptSubmit is the CATCH hook: it re-registers on
+// every prompt so a session whose SessionStart we missed (adapter started late, or hook installed
+// after the session began) still appears on its first prompt. notify.mjs treats it like SessionStart.
+// Stop/StopFailure are the authoritative turn-close signals (Stop = normal finish incl. max_tokens/
+// refusal; StopFailure = turn ended on an API error, where Stop does NOT fire) — they close a turn even
+// when the JSONL-derived turn_ended is missed. Neither supports a matcher (silently ignored).
+const EVENTS = ['SessionStart', 'SessionEnd', 'UserPromptSubmit', 'Stop', 'StopFailure'] as const
+
+interface CommandHook {
+ type: string
+ command: string
+ timeout?: number
+}
+interface HookBlock {
+ matcher?: string
+ hooks: CommandHook[]
+}
+type Settings = { hooks?: Record<string, HookBlock[]> } & Record<string, unknown>
+
+function shellQuote(value: string): string {
+ return `'${value.replace(/'/g, `'\\''`)}'`
+}
+
+function command(port: number, engine: 'claude' | 'codex' | 'cursor' | 'hermes' | 'commandcode' | 'devin'): string {
+ return [
+ 'node',
+ shellQuote(HOOK_SCRIPT),
+ '--port', String(port),
+ '--data-dir', shellQuote(env.ADAPTER_DATA_DIR),
+ '--claude-projects-dir', shellQuote(env.CLAUDE_PROJECTS_DIR),
+ '--codex-home', shellQuote(env.CODEX_HOME),
+ '--cursor-home', shellQuote(env.CURSOR_HOME),
+ '--commandcode-home', shellQuote(env.COMMANDCODE_HOME),
+ '--devin-home', shellQuote(env.DEVIN_HOME),
+ ...(engine !== 'claude' ? ['--engine', engine] : []),
+ ].join(' ')
+}
+
+/** True if a block already points at our notify.mjs script (any path — robust across layout/version). */
+function isOurs(block: HookBlock): boolean {
+ return Array.isArray(block?.hooks) && block.hooks.some((h) => h?.command?.includes('notify.mjs'))
+}
+
+export function installSessionHooks(port: number): void {
+ let settings: Settings = {}
+ try {
+ settings = JSON.parse(readFileSync(SETTINGS_PATH, 'utf-8')) as Settings
+ } catch {
+ // missing / unreadable → start from empty settings
+ }
+
+ if (!settings.hooks || typeof settings.hooks !== 'object') settings.hooks = {}
+ const cmd = command(port, 'claude')
+ let changed = false
+ let updated = false // true when an EXISTING block's command changed (path/port drift)
+
+ for (const event of EVENTS) {
+ const blocks = Array.isArray(settings.hooks[event]) ? settings.hooks[event] : []
+ // Collapse any duplicate "ours" blocks (e.g. from an earlier path) down to a single one, and
+ // keep every non-ours block untouched.
+ const foreign = blocks.filter((b) => !isOurs(b))
+ const oursBlocks = blocks.filter(isOurs)
+ if (oursBlocks.length > 1) changed = true // dropping duplicates is a change
+
+ // The one canonical block for this event with the CURRENT command (path + port). If a prior
+ // block existed with a different command (moved checkout / dev↔dist / changed port), this
+ // overwrites it in place.
+ const existingCmd = oursBlocks[0]?.hooks?.find((h) => isOurs({ hooks: [h] }))?.command
+ if (oursBlocks.length === 0) changed = true
+ else if (existingCmd !== cmd) { changed = true; updated = true }
+
+ settings.hooks[event] = [...foreign, { hooks: [{ type: 'command', command: cmd, timeout: 5 }] }]
+ }
+
+ if (!changed) {
+ console.log('[hooks] Claude session + turn (Stop/StopFailure) hooks already installed')
+ return
+ }
+
+ try {
+ mkdirSync(dirname(SETTINGS_PATH), { recursive: true })
+ writeFileSync(SETTINGS_PATH, JSON.stringify(settings, null, 2) + '\n')
+ console.log(
+ updated
+ ? `[hooks] updated (path/port changed) → ${HOOK_SCRIPT} --port ${port}`
+ : `[hooks] installed Claude session + turn (Stop/StopFailure) hooks → ${SETTINGS_PATH}`,
+ )
+ console.log('[hooks] (takes effect on the next claude session start)')
+ } catch (err) {
+ console.error('[hooks] failed to write settings.json:', err)
+ }
+}
+
+function writeJsonAtomic(file: string, value: unknown): void {
+ mkdirSync(dirname(file), { recursive: true })
+ const tmp = `${file}.${process.pid}.tmp`
+ writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n')
+ renameSync(tmp, file)
+}
+
+/** Merge Machine's user-level Codex hooks without replacing unrelated hooks. A malformed existing file
+ * is left untouched: silently replacing it could disable user security/automation hooks. */
+export function installCodexHooks(port: number): void {
+ let settings: Settings = {}
+ if (existsSync(CODEX_HOOKS_PATH)) {
+ try {
+ settings = JSON.parse(readFileSync(CODEX_HOOKS_PATH, 'utf-8')) as Settings
+ } catch (err) {
+ console.error(`[hooks] Codex hooks file is invalid JSON; leaving it unchanged: ${CODEX_HOOKS_PATH}`)
+ console.error('[hooks] fix the file, then restart harness join')
+ return
+ }
+ }
+ if (!settings.hooks || typeof settings.hooks !== 'object') settings.hooks = {}
+
+ const cmd = command(port, 'codex')
+ const required: Array<{ event: 'SessionStart' | 'UserPromptSubmit'; matcher?: string }> = [
+ { event: 'SessionStart', matcher: 'startup|resume|clear|compact' },
+ { event: 'UserPromptSubmit' },
+ ]
+ let changed = false
+ for (const { event, matcher } of required) {
+ const blocks = Array.isArray(settings.hooks[event]) ? settings.hooks[event] : []
+ const foreign = blocks.filter((b) => !isOurs(b))
+ const ours = blocks.filter(isOurs)
+ const canonical: HookBlock = {
+ ...(matcher ? { matcher } : {}),
+ hooks: [{ type: 'command', command: cmd, timeout: 5 }],
+ }
+ const current = ours[0]
+ if (ours.length !== 1 || current?.matcher !== matcher || current?.hooks?.[0]?.command !== cmd) changed = true
+ settings.hooks[event] = [...foreign, canonical]
+ }
+
+ if (!changed) {
+ console.log('[hooks] Codex SessionStart/UserPromptSubmit hooks already installed')
+ return
+ }
+ try {
+ writeJsonAtomic(CODEX_HOOKS_PATH, settings)
+ console.log(`[hooks] installed Codex SessionStart/UserPromptSubmit hooks → ${CODEX_HOOKS_PATH}`)
+ console.log('[hooks] Codex requires reviewing these user hooks with /hooks before normal use')
+ } catch (err) {
+ console.error('[hooks] failed to write Codex hooks.json:', err)
+ }
+}
+
+interface CursorHook {
+ command: string
+ failClosed?: boolean
+}
+
+type CursorSettings = {
+ version?: number
+ hooks?: Record<string, CursorHook[]>
+} & Record<string, unknown>
+
+/** Merge Cursor's simpler user-hook schema. Cursor local CLI uses lower-camel event names and invokes
+ * command entries directly, unlike Claude/Codex's nested matcher/hooks blocks. */
+export function installCursorHooks(port: number): void {
+ let settings: CursorSettings = {}
+ if (existsSync(CURSOR_HOOKS_PATH)) {
+ try {
+ settings = JSON.parse(readFileSync(CURSOR_HOOKS_PATH, 'utf-8')) as CursorSettings
+ } catch {
+ console.error(`[hooks] Cursor hooks file is invalid JSON; leaving it unchanged: ${CURSOR_HOOKS_PATH}`)
+ return
+ }
+ }
+ if (!settings.hooks || typeof settings.hooks !== 'object') settings.hooks = {}
+ if (typeof settings.version !== 'number') settings.version = 1
+
+ const cmd = command(port, 'cursor')
+ const events = ['sessionStart', 'beforeSubmitPrompt', 'preToolUse', 'stop', 'sessionEnd'] as const
+ let changed = false
+ for (const event of events) {
+ const entries = Array.isArray(settings.hooks[event]) ? settings.hooks[event] : []
+ const foreign = entries.filter((entry) => !entry?.command?.includes('notify.mjs'))
+ const ours = entries.filter((entry) => entry?.command?.includes('notify.mjs'))
+ const canonical: CursorHook = { command: cmd, failClosed: false }
+ if (ours.length !== 1 || ours[0]?.command !== cmd || ours[0]?.failClosed !== false) changed = true
+ settings.hooks[event] = [...foreign, canonical]
+ }
+ if (!changed) {
+ console.log('[hooks] Cursor lifecycle/task hooks already installed')
+ return
+ }
+ try {
+ writeJsonAtomic(CURSOR_HOOKS_PATH, settings)
+ console.log(`[hooks] installed Cursor lifecycle/task hooks → ${CURSOR_HOOKS_PATH}`)
+ } catch (err) {
+ console.error('[hooks] failed to write Cursor hooks.json:', err)
+ }
+}
+
+const OPENCODE_PLUGIN_PATH = join(env.OPENCODE_PLUGIN_DIR, 'launcher-register.js')
+
+/** OpenCode has no shell hooks — discovery is a global plugin that POSTs each session to the daemon.
+ * The plugin runs INSIDE every interactive `opencode` process (so it sees `$TMUX_PANE` + the cwd) and
+ * fires on session.created/updated. The recap worker runs `opencode run --pure`, which skips external
+ * plugins, so it never self-registers. */
+function opencodePluginSource(port: number): string {
+ return `// launcher-register — auto-installed by the machine adapter. Registers this OpenCode session with the
+// local machine daemon (127.0.0.1:${port}) so it can be mirrored to web/device. No-op if machine isn't running.
+export const MachineRegister = async ({ directory, worktree, project }) => {
+ const seen = new Set()
+ const post = async (sessionID) => {
+ const pane = process.env.TMUX_PANE
+ // The launcher (\`harness opencode\`) mints a UUID per launch and exports it as MACHINE_ID; the daemon
+ // binds a session's lifetime to that launcher and REFUSES a registration without one. This plugin runs
+ // inside the engine, so it inherits the variable — and an engine started outside the launcher has none,
+ // which is exactly when it should not register. Same rule notify.mjs applies for every other engine.
+ const launcherId = process.env.MACHINE_ID
+ if (!pane || !launcherId || !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" },
+ body: JSON.stringify({
+ engine: "opencode",
+ launcherId,
+ sessionId: sessionID,
+ cwd: directory || worktree || (project && project.worktree) || null,
+ tmuxPane: pane,
+ }),
+ })
+ } catch {}
+ }
+ return {
+ event: async ({ event }) => {
+ if (!event) return
+ if (event.type === "session.created" || event.type === "session.updated") {
+ const p = event.properties || {}
+ const info = p.info || {}
+ if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent
+ await post(info.id || p.sessionID || p.sessionId)
+ }
+ },
+ }
+}
+`
+}
+
+const COMMANDCODE_SETTINGS_PATH = join(env.COMMANDCODE_HOME, 'settings.json')
+// Command Code exposes only SessionStart / PreToolUse / PostToolUse / Stop — there is NO
+// UserPromptSubmit (so no catch-hook re-register) and no SessionEnd (the tmux reaper covers that).
+// Stop is the authoritative turn close, same as claude's.
+//
+// PreToolUse is here as the TURN-OPEN signal, and it is the only one this engine has. Command Code
+// writes its transcript in one flush when the turn finishes — the user line and the assistant line carry
+// the same millisecond — so tailing the JSONL cannot open a turn either. With only SessionStart/Stop the
+// adapter first heard about a turn when it was already over and emitted turn_started+turn_ended in the
+// same millisecond, so the device never showed "working": the tile went straight from idle to the recap.
+const COMMANDCODE_EVENTS = ['SessionStart', 'PreToolUse', 'Stop'] as const
+
+/**
+ * Command Code's hook file is `~/.commandcode/settings.json` with the SAME nested `matcher`/`hooks`
+ * schema as `~/.claude/settings.json`, so this mirrors installSessionHooks — including its dedup
+ * discipline: every "ours" block (any command mentioning notify.mjs, whatever its old path/port) is
+ * collapsed into exactly one canonical entry, and foreign blocks are preserved untouched.
+ */
+export function installCommandCodeHooks(port: number): void {
+ let settings: Settings = {}
+ if (existsSync(COMMANDCODE_SETTINGS_PATH)) {
+ try {
+ settings = JSON.parse(readFileSync(COMMANDCODE_SETTINGS_PATH, 'utf-8')) as Settings
+ } catch {
+ console.error(`[hooks] Command Code settings file is invalid JSON; leaving it unchanged: ${COMMANDCODE_SETTINGS_PATH}`)
+ return
+ }
+ }
+ if (!settings.hooks || typeof settings.hooks !== 'object') settings.hooks = {}
+
+ const cmd = command(port, 'commandcode')
+ let changed = false
+ for (const event of COMMANDCODE_EVENTS) {
+ const blocks = Array.isArray(settings.hooks[event]) ? settings.hooks[event] : []
+ const foreign = blocks.filter((b) => !isOurs(b))
+ const ours = blocks.filter(isOurs)
+ if (ours.length !== 1 || ours[0]?.hooks?.[0]?.command !== cmd) changed = true
+ settings.hooks[event] = [...foreign, { hooks: [{ type: 'command', command: cmd, timeout: 5 }] }]
+ }
+
+ if (!changed) {
+ console.log('[hooks] Command Code session hooks already installed')
+ return
+ }
+ try {
+ writeJsonAtomic(COMMANDCODE_SETTINGS_PATH, settings)
+ console.log(`[hooks] installed Command Code SessionStart/Stop hooks → ${COMMANDCODE_SETTINGS_PATH}`)
+ console.log('[hooks] (takes effect on the next commandcode session start)')
+ } catch (err) {
+ console.error('[hooks] failed to write Command Code settings.json:', err)
+ }
+}
+
+// Devin reads Claude's hook schema verbatim (its binary parses `ClaudeHookConfig`/`ClaudeHookMatcherConfig`),
+// so the only differences from installSessionHooks are the file and that hooks nest under a "hooks" key of
+// the user's general config — which also holds `devin.org_id`, `theme_mode`, etc, so this MERGES and never
+// rewrites the file wholesale. Verified live: SessionStart/UserPromptSubmit/Stop all fire with
+// `$TMUX_PANE` intact; the payload carries {hook_event_name, session_id, prompt_id, prompt, source} but
+// NO transcript_path and NO cwd (notify.mjs derives cwd from its own process).
+const DEVIN_EVENTS = ['SessionStart', 'UserPromptSubmit', 'Stop', 'SessionEnd'] as const
+
+export function installDevinHooks(port: number): void {
+ let config: Settings & Record<string, unknown> = {}
+ if (existsSync(env.DEVIN_CONFIG_PATH)) {
+ try {
+ config = JSON.parse(readFileSync(env.DEVIN_CONFIG_PATH, 'utf-8')) as Settings & Record<string, unknown>
+ } catch {
+ console.error(`[hooks] Devin config file is invalid JSON; leaving it unchanged: ${env.DEVIN_CONFIG_PATH}`)
+ return
+ }
+ }
+ if (!config.hooks || typeof config.hooks !== 'object') config.hooks = {}
+
+ const cmd = command(port, 'devin')
+ let changed = false
+ for (const event of DEVIN_EVENTS) {
+ const blocks = Array.isArray(config.hooks[event]) ? config.hooks[event] : []
+ const foreign = blocks.filter((b) => !isOurs(b))
+ const ours = blocks.filter(isOurs)
+ if (ours.length !== 1 || ours[0]?.hooks?.[0]?.command !== cmd) changed = true
+ config.hooks[event] = [...foreign, { hooks: [{ type: 'command', command: cmd, timeout: 5 }] }]
+ }
+
+ if (!changed) {
+ console.log('[hooks] Devin session hooks already installed')
+ return
+ }
+ try {
+ writeJsonAtomic(env.DEVIN_CONFIG_PATH, config)
+ console.log(`[hooks] installed Devin SessionStart/UserPromptSubmit/Stop/SessionEnd hooks → ${env.DEVIN_CONFIG_PATH}`)
+ console.log('[hooks] (takes effect on the next devin session start)')
+ } catch (err) {
+ console.error('[hooks] failed to write Devin config.json:', err)
+ }
+}
+
+const HERMES_CONFIG_PATH = join(env.HERMES_HOME, 'config.yaml')
+const HERMES_ALLOWLIST_PATH = join(env.HERMES_HOME, 'shell-hooks-allowlist.json')
+// The managed block is delimited by BEGIN/END so it can be replaced unambiguously. (An earlier version
+// used a single marker line and a lookahead regex, which only replaced the comment and orphaned the old
+// `hooks:` mapping — YAML then took the LAST duplicate key, so a stale block silently won.)
+const HERMES_BLOCK_BEGIN = '# machine-adapter: session discovery (managed block — safe to delete)'
+const HERMES_BLOCK_END = '# machine-adapter: end'
+// `on_session_start` fires ONLY for brand-new sessions, so `pre_llm_call` (once per turn, in every
+// session incl. `hermes -c`/`--resume`) is the real beacon. Registration is idempotent.
+const HERMES_HOOK_EVENTS = ['on_session_start', 'pre_llm_call'] as const
+
+/** Hermes gates every (event, command) pair behind ~/.hermes/shell-hooks-allowlist.json; an unapproved
+ * hook is SILENTLY skipped in non-TTY runs. Record ours so it fires without an interactive prompt. */
+function allowlistHermesHook(cmd: string): void {
+ let data: { approvals?: Array<{ event?: string; command?: string }> } = { approvals: [] }
+ try {
+ const parsed = JSON.parse(readFileSync(HERMES_ALLOWLIST_PATH, 'utf-8')) as typeof data
+ if (parsed && Array.isArray(parsed.approvals)) data = parsed
+ } catch { /* absent or unreadable → start from an empty skeleton */ }
+ const approvals = data.approvals ?? []
+ let changed = false
+ for (const event of HERMES_HOOK_EVENTS) {
+ // Hermes matches on EXACT (event, command) string equality.
+ if (approvals.some((a) => a?.event === event && a?.command === cmd)) continue
+ approvals.push({ event, command: cmd })
+ changed = true
+ }
+ if (!changed) return
+ writeJsonAtomic(HERMES_ALLOWLIST_PATH, { ...data, approvals })
+}
+
+function hermesHooksBlock(cmd: string): string {
+ const entries = HERMES_HOOK_EVENTS
+ .map((event) => ` ${event}:\n - command: ${JSON.stringify(cmd)}\n timeout: 10`)
+ .join('\n')
+ return `\n${HERMES_BLOCK_BEGIN}\nhooks:\n${entries}\n${HERMES_BLOCK_END}\n`
+}
+
+/** True for a top-level `hooks:` mapping that is ours (every command runs our notify.mjs for hermes). */
+function isMachineHooksBody(body: string[]): boolean {
+ const commands = body.filter((line) => /^\s*- command:/.test(line))
+ return commands.length > 0 && commands.every((line) => line.includes('notify.mjs') && line.includes('--engine hermes'))
+}
+
+/**
+ * Strip every block this installer owns: the delimited BEGIN…END form AND any bare `hooks:` mapping
+ * left behind by the earlier buggy rewrite (identified by its notify.mjs commands). Returns the cleaned
+ * document plus whether a FOREIGN `hooks:` key survives — the caller must not touch the file then.
+ */
+function stripMachineHermesBlocks(config: string): { cleaned: string; foreignHooks: boolean; removed: number } {
+ const lines = config.split('\n')
+ const out: string[] = []
+ let removed = 0
+ let foreignHooks = false
+
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i]
+ if (line.trim() === HERMES_BLOCK_BEGIN) {
+ // Skip through the END marker (or, for a truncated block, to the end of the mapping).
+ let j = i + 1
+ while (j < lines.length && lines[j].trim() !== HERMES_BLOCK_END) j++
+ i = j < lines.length ? j : lines.length - 1
+ removed++
+ continue
+ }
+ if (/^hooks:\s*$/.test(line)) {
+ let j = i + 1
+ while (j < lines.length && (lines[j].startsWith(' ') || lines[j].startsWith('\t') || lines[j].trim() === '')) j++
+ const body = lines.slice(i + 1, j)
+ if (isMachineHooksBody(body)) { removed++; i = j - 1; continue }
+ foreignHooks = true
+ out.push(line)
+ continue
+ }
+ out.push(line)
+ }
+ return { cleaned: out.join('\n').replace(/\n{3,}$/, '\n'), foreignHooks, removed }
+}
+
+/**
+ * Install the Hermes shell hooks. Unlike the other engines Hermes has no dedicated hooks file — they
+ * live in the user's main `~/.hermes/config.yaml`. We therefore own exactly one delimited block: every
+ * previous machine block is stripped first and a single fresh one appended, so a port/path change can
+ * never leave a duplicate `hooks:` key behind (YAML resolves duplicates to the LAST one, which silently
+ * pinned sessions to a stale block). A `hooks:` key that is NOT ours means the user manages their own —
+ * leave the file untouched and print what to add.
+ */
+export function installHermesHooks(port: number): void {
+ const cmd = command(port, 'hermes')
+ let config = ''
+ try {
+ config = readFileSync(HERMES_CONFIG_PATH, 'utf-8')
+ } catch {
+ console.log(`[hooks] no Hermes config at ${HERMES_CONFIG_PATH} — skipping (run hermes once first)`)
+ return
+ }
+
+ const { cleaned, foreignHooks, removed } = stripMachineHermesBlocks(config)
+ if (foreignHooks) {
+ console.error(`[hooks] ${HERMES_CONFIG_PATH} has its own \`hooks:\` block — leaving it untouched.`)
+ console.error('[hooks] add these entries under it manually to mirror Hermes sessions:')
+ for (const event of HERMES_HOOK_EVENTS) console.error(`[hooks] ${event}: [{ command: ${JSON.stringify(cmd)}, timeout: 10 }]`)
+ return
+ }
+
+ const next = `${cleaned.replace(/\s*$/, '')}\n${hermesHooksBlock(cmd)}`
+ if (next === config) {
+ allowlistHermesHook(cmd) // keep the allowlist in sync even when the block is current
+ console.log('[hooks] Hermes session hooks already installed')
+ return
+ }
+
+ try {
+ writeFileSync(HERMES_CONFIG_PATH, next)
+ allowlistHermesHook(cmd)
+ console.log(
+ removed > 1
+ ? `[hooks] installed Hermes session hooks (collapsed ${removed} stale blocks) → ${HERMES_CONFIG_PATH}`
+ : `[hooks] installed Hermes session hooks → ${HERMES_CONFIG_PATH}`,
+ )
+ console.log('[hooks] (takes effect on the next hermes session start)')
+ } catch (err) {
+ console.error('[hooks] failed to write Hermes config.yaml:', err)
+ }
+}
+
+const PI_EXTENSION_PATH = join(env.PI_HOME, 'agent', 'extensions', 'launcher-register.ts')
+
+/** Pi has no shell hooks either — discovery is a global TypeScript extension. It runs INSIDE every
+ * interactive `pi` process (so it sees `$TMUX_PANE` and the session's own file path) and registers the
+ * session with the local daemon. Pi buffers the transcript until the first assistant message, so the
+ * session file may not exist yet at `session_start`; the extension re-registers on the first turn, once
+ * `getSessionFile()` points at a real file. The recap worker runs with `--no-extensions`, so it never
+ * registers itself. Global extensions load before the project-trust prompt, so this always fires. */
+function piExtensionSource(port: number): string {
+ return `// launcher-register — auto-installed by the machine adapter. Registers this Pi session with 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 type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
+
+export default function (pi: ExtensionAPI) {
+ let announced = false; // posted at least once (the transcript may not exist yet)
+ let registered = false; // posted with a real, on-disk transcript — nothing left to do
+
+ const register = async (ctx: any) => {
+ const pane = process.env.TMUX_PANE;
+ if (!pane) return; // tmux-only, like every other engine
+ // The launcher (\`harness pi\`) exports MACHINE_ID per launch, and the daemon refuses a registration
+ // without it — the id is what binds the session's lifetime to a live launcher. This extension runs
+ // inside pi, so it inherits the variable; started outside the launcher there is none, and registering
+ // is exactly the wrong thing to do. Same rule notify.mjs applies for every other engine.
+ const launcherId = process.env.MACHINE_ID;
+ if (!launcherId) 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.
+ const file = ctx?.sessionManager?.getSessionFile?.() ?? null;
+ const ready = !!file && existsSync(file);
+ if (registered || (announced && !ready)) return;
+ const sessionId = ctx?.sessionManager?.getSessionId?.();
+ if (!sessionId) return;
+ try {
+ const res = await fetch("http://127.0.0.1:${port}/api/hook/session-start", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ engine: "pi",
+ launcherId,
+ sessionId,
+ transcriptPath: ready ? file : undefined,
+ cwd: ctx?.cwd ?? undefined,
+ tmuxPane: pane,
+ }),
+ });
+ if (!res.ok) return; // daemon refused (e.g. transcript not readable yet) — retry on the next turn
+ announced = true;
+ if (ready) registered = true;
+ } catch {}
+ };
+
+ // session_start fires before the transcript exists; the turn hooks catch it once it does.
+ pi.on("session_start", async (_event, ctx) => { await register(ctx); });
+ pi.on("turn_start", async (_event, ctx) => { await register(ctx); });
+ pi.on("turn_end", async (_event, ctx) => { await register(ctx); });
+}
+`
+}
+
+/** Idempotently drop the Pi discovery extension into <PI_HOME>/agent/extensions/. */
+export function installPiExtension(port: number): void {
+ const source = piExtensionSource(port)
+ try {
+ if (existsSync(PI_EXTENSION_PATH) && readFileSync(PI_EXTENSION_PATH, 'utf-8') === source) {
+ console.log('[hooks] Pi discovery extension already installed')
+ return
+ }
+ } catch { /* unreadable — rewrite it */ }
+ try {
+ mkdirSync(dirname(PI_EXTENSION_PATH), { recursive: true })
+ const tmp = `${PI_EXTENSION_PATH}.${process.pid}.tmp`
+ writeFileSync(tmp, source)
+ renameSync(tmp, PI_EXTENSION_PATH)
+ console.log(`[hooks] installed Pi discovery extension → ${PI_EXTENSION_PATH}`)
+ console.log('[hooks] (takes effect on the next pi session start)')
+ } catch (err) {
+ console.error('[hooks] failed to write Pi extension:', err)
+ }
+}
+
+/** Idempotently drop the OpenCode discovery plugin into ~/.config/opencode/plugin/. */
+export function installOpencodePlugin(port: number): void {
+ const source = opencodePluginSource(port)
+ try {
+ if (existsSync(OPENCODE_PLUGIN_PATH) && readFileSync(OPENCODE_PLUGIN_PATH, 'utf-8') === source) {
+ console.log('[hooks] OpenCode discovery plugin already installed')
+ return
+ }
+ } catch { /* unreadable — rewrite it */ }
+ try {
+ mkdirSync(dirname(OPENCODE_PLUGIN_PATH), { recursive: true })
+ const tmp = `${OPENCODE_PLUGIN_PATH}.${process.pid}.tmp`
+ writeFileSync(tmp, source)
+ renameSync(tmp, OPENCODE_PLUGIN_PATH)
+ console.log(`[hooks] installed OpenCode discovery plugin → ${OPENCODE_PLUGIN_PATH}`)
+ console.log('[hooks] (takes effect on the next opencode session start)')
+ } catch (err) {
+ console.error('[hooks] failed to write OpenCode plugin:', err)
+ }
+}
+
+/**
+ * Install/refresh the hook (or plugin/extension) for ONE engine.
+ *
+ * Used by the `harness <engine>` launcher, which calls this immediately BEFORE spawning the CLI. Every
+ * installer above ends with "(takes effect on the next session start)" — running it here means the
+ * session we are about to start IS that next one, closing the gap where a freshly-installed machine
+ * missed the very first session because its hooks landed too late.
+ *
+ * Installers are idempotent (they collapse any block whose command contains `notify.mjs` into one
+ * canonical entry and leave foreign blocks alone), so calling this on every launch is cheap and safe.
+ */
+export function installHooksFor(engine: AgentEngine, port: number): void {
+ switch (engine) {
+ case 'claude': installSessionHooks(port); break
+ case 'codex': installCodexHooks(port); break
+ case 'cursor': installCursorHooks(port); break
+ case 'opencode': installOpencodePlugin(port); break
+ case 'pi': installPiExtension(port); break
+ case 'hermes': installHermesHooks(port); break
+ case 'commandcode': installCommandCodeHooks(port); break
+ case 'devin': installDevinHooks(port); break
+ }
+}
diff --git a/cli/src/lib/launch.spec.ts b/cli/src/lib/launch.spec.ts
new file mode 100644
index 000000000..93d7e1bd4
--- /dev/null
+++ b/cli/src/lib/launch.spec.ts
@@ -0,0 +1,563 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { VERSION } from '../version.js'
+
+/**
+ * `harness <engine>` wrapper contract:
+ * - refuses outside tmux, and refuses when the daemon is not joined/running — WITHOUT spawning the CLI
+ * and without starting the daemon behind the user's back;
+ * - forwards argv verbatim (the CLI's own flags must survive), appending the permission bypass the
+ * pane's remote driver cannot click through — unless the user named a policy themselves;
+ * - is transparent: inherits the tty, propagates the child's exit status.
+ */
+
+const spawnMock = vi.fn()
+const execFileMock = vi.fn()
+
+vi.mock('child_process', () => ({
+ spawn: (...args: unknown[]) => spawnMock(...args),
+ execFile: (...args: unknown[]) => execFileMock(...args),
+}))
+
+const daemonRunning = vi.fn(() => true)
+const tokenSaved = vi.fn(() => true)
+vi.mock('./daemonState.js', () => ({
+ daemonPort: () => 18473,
+ isDaemonRunning: () => daemonRunning(),
+ hasSavedToken: () => tokenSaved(),
+}))
+
+vi.mock('./hooks.js', () => ({ installHooksFor: vi.fn() }))
+vi.mock('./engineBin.js', async (orig) => ({
+ ...(await orig<Record<string, unknown>>()),
+ engineBin: () => '/usr/bin/fake-claude',
+}))
+/** Drivable fake WebSocket — the tests decide when it opens/closes, so socket events (not timers) are
+ * what the assertions turn on. */
+class FakeWs {
+ static instances: FakeWs[] = []
+ /** The daemon's ack. null → it never answers, which exercises the launcher's bounded wait. */
+ static ack: Record<string, unknown> | null = { t: 'opened', v: 1, version: VERSION }
+ handlers = new Map<string, (...a: unknown[]) => void>()
+ sent: string[] = []
+ closed = false
+ constructor(public url: string) {
+ FakeWs.instances.push(this)
+ setTimeout(() => this.openIt(), 0) // a real socket opens on its own
+ }
+ on(event: string, fn: (...a: unknown[]) => void) { this.handlers.set(event, fn); return this }
+ send(data: string) { this.sent.push(data) }
+ close() { this.closed = true; this.emit('close') }
+ emit(event: string, ...args: unknown[]) { this.handlers.get(event)?.(...args) }
+ /** Complete the handshake the way `ws` would, then answer like the daemon does. */
+ openIt() {
+ this.emit('open')
+ if (FakeWs.ack) setTimeout(() => this.emit('message', JSON.stringify(FakeWs.ack)), 0)
+ }
+}
+vi.mock('ws', () => ({ WebSocket: FakeWs }))
+
+/** A fake child that never exits on its own — the test drives its lifecycle. */
+function fakeChild() {
+ const handlers = new Map<string, (...a: unknown[]) => void>()
+ return {
+ on(event: string, fn: (...a: unknown[]) => void) { handlers.set(event, fn); return this },
+ kill: vi.fn(),
+ emit(event: string, ...args: unknown[]) { handlers.get(event)?.(...args) },
+ }
+}
+
+let exitCode: number | undefined
+let stderr: string[] = []
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ exitCode = undefined
+ stderr = []
+ daemonRunning.mockReturnValue(true)
+ tokenSaved.mockReturnValue(true)
+ process.env.TMUX = '/tmp/tmux-501/default,1,0'
+ process.env.TMUX_PANE = '%7'
+ vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
+ exitCode = code
+ throw new Error('__exit__') // unwind like the real exit would end the turn
+ }) as never)
+ vi.spyOn(console, 'error').mockImplementation((...a: unknown[]) => { stderr.push(a.join(' ')) })
+ // Health probe: daemon answers OK unless a test says otherwise.
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ({}) })))
+ FakeWs.instances = []
+ FakeWs.ack = { t: 'opened', v: 1, version: VERSION }
+ spawnMock.mockImplementation(() => fakeChild())
+ execFileMock.mockImplementation((_cmd: string, _args: string[], _opts: unknown, cb?: (...a: unknown[]) => void) => {
+ cb?.(null, '', '')
+ })
+})
+
+afterEach(() => {
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+ delete process.env.TMUX
+ delete process.env.TMUX_PANE
+})
+
+/**
+ * Kick off a launch and wait until it has *settled into* one of its two end states: refused (process.exit
+ * called) or running (child spawned). It is never awaited to completion — the real launcher deliberately
+ * returns a promise that never resolves, so the wrapper stays alive holding the pane until the child ends.
+ */
+async function launch(argv: string[] = [], settleMs = 1_000): Promise<void> {
+ const { launchEngine } = await import('./launch.js')
+ void launchEngine('claude', argv).catch((err: Error) => {
+ if (err.message !== '__exit__') throw err
+ })
+ // `settleMs` must exceed ACK_WAIT_MS for the cases where the daemon never acks — the launcher waits
+ // out that window before falling back and spawning.
+ await vi.waitFor(() => {
+ expect(exitCode !== undefined || spawnMock.mock.calls.length > 0).toBe(true)
+ }, { timeout: settleMs })
+}
+
+describe('harness <engine> launcher', () => {
+ it('refuses to run outside tmux and never spawns the CLI', async () => {
+ delete process.env.TMUX
+ delete process.env.TMUX_PANE
+ await launch()
+ expect(exitCode).toBe(1)
+ expect(spawnMock).not.toHaveBeenCalled()
+ expect(stderr.join('\n')).toContain('tmux')
+ })
+
+ it('refuses when the computer has never joined, pointing at `harness join <token>`', async () => {
+ daemonRunning.mockReturnValue(false)
+ tokenSaved.mockReturnValue(false)
+ await launch()
+ expect(exitCode).toBe(1)
+ expect(spawnMock).not.toHaveBeenCalled()
+ expect(stderr.join('\n')).toContain('harness join <token>')
+ })
+
+ it('refuses when the daemon is stopped — and does NOT start it implicitly', async () => {
+ daemonRunning.mockReturnValue(false)
+ tokenSaved.mockReturnValue(true)
+ await launch()
+ expect(exitCode).toBe(1)
+ expect(spawnMock).not.toHaveBeenCalled() // no daemon respawn, no CLI
+ const out = stderr.join('\n')
+ expect(out).toContain('harness join')
+ expect(out).not.toContain('<token>') // credential is saved; don't ask for it again
+ })
+
+ it('forwards every argument verbatim and inherits the terminal', async () => {
+ const argv = ['--resume', 'abc-123', '--model', 'opus', '--', 'a b c']
+ await launch(argv)
+ expect(spawnMock).toHaveBeenCalledTimes(1)
+ const [bin, args, opts] = spawnMock.mock.calls[0] as [string, string[], Record<string, unknown>]
+ expect(bin).toBe('/usr/bin/fake-claude')
+ // The user's arguments arrive untouched and IN ORDER; the permission flag is appended after them,
+ // never spliced in — `--` and everything past it must keep meaning what the user wrote.
+ expect(args.slice(0, argv.length)).toEqual(argv)
+ expect(opts.stdio).toBe('inherit')
+ })
+
+ it('adds the permission bypass nobody is there to click, unless the user chose one', async () => {
+ // The pane is driven from web/device, so an agent that stops to ask never gets an answer.
+ await launch()
+ const [, plain] = spawnMock.mock.calls[0] as [string, string[]]
+ expect(plain).toContain('--dangerously-skip-permissions')
+
+ spawnMock.mockClear()
+ await launch(['--permission-mode', 'plan'])
+ const [, chosen] = spawnMock.mock.calls[0] as [string, string[]]
+ expect(chosen).toEqual(['--permission-mode', 'plan'])
+ })
+
+ it('exports MACHINE_ID to the child and keeps the tmux env', async () => {
+ await launch()
+ const [, , opts] = spawnMock.mock.calls[0] as [string, string[], { env: NodeJS.ProcessEnv }]
+ expect(opts.env.MACHINE_ID).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i)
+ expect(opts.env.TMUX_PANE).toBe('%7') // opposite of the recap one-shots, which scrub it
+ })
+
+ it('announces the session over the launcher socket, with the id the child receives', async () => {
+ await launch()
+ const ws = FakeWs.instances[0]
+ expect(ws.url).toContain('/api/machine-ws')
+ ws.openIt()
+ const open = JSON.parse(ws.sent[0]) as Record<string, unknown>
+ expect(open.t).toBe('open')
+ expect(open.engine).toBe('claude')
+ expect(open.tmuxPane).toBe('%7')
+ const [, , opts] = spawnMock.mock.calls[0] as [string, string[], { env: NodeJS.ProcessEnv }]
+ expect(open.launcherId).toBe(opts.env.MACHINE_ID) // the daemon and the CLI agree on the id
+ })
+
+ it('closes the launcher socket on exit (that close is what drops the tile) and keeps the exit code', async () => {
+ const child = fakeChild()
+ spawnMock.mockImplementation(() => child)
+ await launch()
+ const ws = FakeWs.instances[0]
+ try { child.emit('exit', 3, null) } catch { /* mocked process.exit throws */ }
+ await vi.waitFor(() => expect(ws.closed).toBe(true))
+ await vi.waitFor(() => expect(exitCode).toBe(3))
+ })
+
+ it('prints NOTHING on a normal exit — even if the daemon died mid-session', async () => {
+ const child = fakeChild()
+ spawnMock.mockImplementation(() => child)
+ await launch()
+ FakeWs.instances[0].emit('close') // daemon stopped while the agent was running
+ stderr.length = 0
+
+ try { child.emit('exit', 0, null) } catch { /* mocked process.exit throws */ }
+ await vi.waitFor(() => expect(exitCode).toBe(0))
+ // Native `claude` says nothing when it exits; a wrapper that nags on the way out is not transparent
+ // (it also pollutes stdout/stderr for anything scripting the command).
+ expect(stderr.join('')).toBe('')
+ })
+
+ it('warns the moment the socket drops — no polling delay — and never writes into the pane', async () => {
+ await launch()
+ const ws = FakeWs.instances[0]
+
+ const notices = (): unknown[][] => execFileMock.mock.calls.filter((c: unknown[]) =>
+ Array.isArray(c[1]) && (c[1] as string[])[0] === 'display-message')
+ expect(notices()).toHaveLength(0)
+
+ ws.emit('close') // e.g. `harness stop` in another pane
+ // Synchronous with the socket event: the old build waited up to 3s for a health poll.
+ expect(notices()).toHaveLength(1)
+ const args = notices()[0][1] as string[]
+ expect(args).toContain('-d') // explicit duration; tmux's 750ms default flashed past unseen
+ expect(args.join(' ')).toContain('harness join')
+ // Transparency: the warning goes to the tmux status bar, never into the pane the TUI is drawing in.
+ expect(stderr.join('\n')).not.toContain('harness join')
+ })
+
+ it('keeps re-posting the disconnect notice while the daemon stays down', async () => {
+ vi.useFakeTimers()
+ await launch()
+ const notices = (): number => execFileMock.mock.calls.filter((c: unknown[]) =>
+ Array.isArray(c[1]) && (c[1] as string[])[0] === 'display-message').length
+
+ FakeWs.instances[0].emit('close')
+ expect(notices()).toBe(1) // instant, on the socket event
+
+ // A tmux status message is cleared by `display-time` OR by the user's next keystroke — announcing
+ // once means it WILL be missed. Every failed reconnect must put it back.
+ for (let i = 1; i < 4; i++) {
+ await vi.advanceTimersByTimeAsync(5_100)
+ FakeWs.instances[FakeWs.instances.length - 1].emit('close') // still no daemon
+ }
+ expect(notices()).toBeGreaterThan(2)
+ vi.useRealTimers()
+ })
+
+ it('reconnects after a drop and re-announces the session', async () => {
+ vi.useFakeTimers()
+ await launch()
+ FakeWs.instances[0].emit('close')
+ await vi.advanceTimersByTimeAsync(2_100) // one flat retry interval
+ expect(FakeWs.instances.length).toBe(2)
+ const reopen = JSON.parse(FakeWs.instances[1].sent[0]) as Record<string, unknown>
+ expect(reopen.t).toBe('open')
+ // Same id → the daemon re-claims the SAME session instead of creating a second one.
+ expect(reopen.launcherId).toBe(JSON.parse(FakeWs.instances[0].sent[0]).launcherId)
+ vi.useRealTimers()
+ })
+
+ it('retries on a FLAT interval, so the daemon\'s 15s grace always covers several attempts', async () => {
+ // The daemon declares a launcher dead after MACHINE_RECONNECT_GRACE_MS of silence. With the old
+ // 0.5→1→2→4→5s backoff, how many attempts fell inside that window depended on how long the daemon had
+ // already been away — the verdict got less safe the longer the outage. A flat interval fixes it.
+ vi.useFakeTimers()
+ try {
+ await launch()
+ FakeWs.instances[0].emit('close')
+ const attemptsAt: number[] = []
+ for (let elapsed = 0; elapsed < 15_000; elapsed += 500) {
+ await vi.advanceTimersByTimeAsync(500)
+ const last = FakeWs.instances[FakeWs.instances.length - 1]
+ if (attemptsAt.length < FakeWs.instances.length - 1) attemptsAt.push(elapsed + 500)
+ last.emit('close') // the daemon is still down
+ }
+ // ≥6 tries inside the grace window, and never a widening gap between them.
+ expect(attemptsAt.length).toBeGreaterThanOrEqual(6)
+ const gaps = attemptsAt.slice(1).map((at, i) => at - attemptsAt[i])
+ expect(Math.max(...gaps)).toBeLessThanOrEqual(2_500)
+ } finally { vi.useRealTimers() }
+ })
+
+ it('keeps the same machine id for the whole process, however often it reconnects', async () => {
+ // The id is what binds a session to a launcher. Minting a fresh one on reconnect would orphan the
+ // agent the daemon is holding for it — the reconnect would look like a brand-new launcher.
+ vi.useFakeTimers()
+ try {
+ await launch()
+ const first = JSON.parse(FakeWs.instances[0].sent[0]).launcherId as string
+ for (let i = 0; i < 3; i++) {
+ FakeWs.instances[FakeWs.instances.length - 1].emit('close')
+ await vi.advanceTimersByTimeAsync(2_100)
+ }
+ expect(FakeWs.instances.length).toBe(4)
+ for (const ws of FakeWs.instances) expect(JSON.parse(ws.sent[0]).launcherId).toBe(first)
+ } finally { vi.useRealTimers() }
+ })
+
+ it('spawns the binary the DAEMON resolved, not this build\'s own guess', async () => {
+ // Binary policy changes between builds (`commandcode` → `cmd` already happened). A launcher left over
+ // from an older build must not strand the user on the old name.
+ FakeWs.ack = { t: 'opened', v: 1, version: VERSION, bin: '/opt/new/location/claude', hooksReady: true }
+ await launch()
+ const [bin] = spawnMock.mock.calls[0] as [string]
+ expect(bin).toBe('/opt/new/location/claude')
+ })
+
+ it('skips its own hook install when the daemon says it already did it', async () => {
+ const { installHooksFor } = await import('./hooks.js')
+ FakeWs.ack = { t: 'opened', v: 1, version: VERSION, bin: '/usr/bin/fake-claude', hooksReady: true }
+ await launch()
+ expect(installHooksFor).not.toHaveBeenCalled() // the daemon's (newer) definitions win
+ })
+
+ it('still spawns when the daemon never acks — a wedged daemon must not block the agent', async () => {
+ FakeWs.ack = null // connected, but silent
+ const { installHooksFor } = await import('./hooks.js')
+ await launch([], 5_000)
+ const [bin] = spawnMock.mock.calls[0] as [string]
+ expect(bin).toBe('/usr/bin/fake-claude') // fell back to this build's resolution
+ expect(installHooksFor).toHaveBeenCalled() // …and to installing hooks itself
+ }, 10_000)
+
+ it('warns repeatedly when the daemon refuses our protocol version', async () => {
+ FakeWs.ack = { t: 'error', reason: 'unsupported_protocol', supported: [2] }
+ await launch([], 5_000)
+ const notices = (): unknown[][] => execFileMock.mock.calls.filter((c: unknown[]) =>
+ Array.isArray(c[1]) && (c[1] as string[])[0] === 'display-message')
+ // The agent runs on (killing it would be worse) but it is unreachable from the web, so unlike the
+ // one-shot "a newer build exists" notice this one has to keep saying so.
+ await vi.waitFor(() => expect(notices().length).toBeGreaterThan(0))
+ expect((notices()[0][1] as string[]).join(' ')).toContain('exit and re-run')
+ }, 10_000)
+
+ it('reports a missing engine binary like a shell does (127), without a stack trace', async () => {
+ const child = fakeChild()
+ spawnMock.mockImplementation(() => child)
+ await launch()
+ try { child.emit('error', Object.assign(new Error('spawn ENOENT'), { code: 'ENOENT' })) } catch { /* exit */ }
+ await vi.waitFor(() => expect(exitCode).toBe(127))
+ expect(stderr.join('\n')).toContain('command not found')
+ })
+})
+
+/**
+ * The daemon can push a notice onto the pane's status line at any time. Everything in the frame is
+ * ADVISORY — it crosses a version boundary (an hours-old launcher, a daemon from today) — so these tests
+ * pin the two things that must never depend on the sender behaving: the text reaches tmux's FORMAT parser,
+ * and a malformed frame must be a no-op rather than a broken status line.
+ */
+describe('daemon → launcher notices', () => {
+ const notices = (): string[][] => execFileMock.mock.calls
+ .filter((c: unknown[]) => Array.isArray(c[1]) && (c[1] as string[])[0] === 'display-message')
+ .map((c: unknown[]) => c[1] as string[])
+ const lastNotice = (): string[] => notices()[notices().length - 1]
+
+ async function push(frame: Record<string, unknown>): Promise<void> {
+ await launch()
+ execFileMock.mockClear()
+ FakeWs.instances[0].emit('message', JSON.stringify(frame))
+ }
+
+ it('always names a background, so the text can never land on its own colour', async () => {
+ await push({ t: 'notice', text: 'all good', level: 'info' })
+ expect(lastNotice().join(' ')).toContain('#[bg=black,fg=cyan,bold] all good')
+
+ FakeWs.instances[0].emit('message', JSON.stringify({ t: 'notice', text: 'heads up', level: 'warn' }))
+ // The bug this pins: tmux's `message-style` default is `bg=yellow`, so a foreground-only `fg=yellow`
+ // rendered a solid gold bar with invisible text on a real pane.
+ expect(lastNotice().join(' ')).toContain('#[bg=yellow,fg=black,bold] heads up')
+ for (const args of notices()) expect(args.join(' ')).toMatch(/#\[bg=[a-z]+,fg=/)
+ })
+
+ it('never passes -N — it would swallow the user\'s keystrokes, not just hold the message', async () => {
+ // Measured on a real pane: keys typed during a 6s `-N` notice never reached the child, before OR after
+ // it expired. A frozen terminal is a far worse bug than a notice someone missed.
+ await push({ t: 'notice', text: 'heads up', level: 'warn' })
+ FakeWs.instances[0].emit('message', JSON.stringify({ t: 'notice', text: 'broken', level: 'error' }))
+ for (const args of notices()) expect(args).not.toContain('-N')
+ })
+
+ it('re-posts a warning, since one keystroke erases it', async () => {
+ vi.useFakeTimers()
+ try {
+ await push({ t: 'notice', text: 'heads up', level: 'warn' })
+ expect(notices()).toHaveLength(1)
+ await vi.advanceTimersByTimeAsync(6_000)
+ expect(notices().length).toBeGreaterThan(1)
+ expect(notices().every((a) => a.join(' ').includes('heads up'))).toBe(true)
+ } finally { vi.useRealTimers() }
+ })
+
+ it('does NOT re-post ordinary chatter', async () => {
+ vi.useFakeTimers()
+ try {
+ await push({ t: 'notice', text: 'all good', level: 'info' })
+ await vi.advanceTimersByTimeAsync(10_000)
+ expect(notices()).toHaveLength(1)
+ } finally { vi.useRealTimers() }
+ })
+
+ it('neutralises tmux format syntax in the daemon\'s text', async () => {
+ // display-message expands FORMATS (we cannot pass -l — that would print our own colour codes), so
+ // `#{…}` interpolates, `#[…]` restyles and `#(…)` RUNS A SHELL COMMAND. Doubling every `#` is the fix.
+ await push({ t: 'notice', text: '#{pane_id} #[fg=red]x #(id)' })
+ const message = lastNotice()[lastNotice().length - 1]
+ expect(message).toContain('##{pane_id}')
+ expect(message).toContain('##[fg=red]x')
+ expect(message).toContain('##(id)')
+ // The only unescaped directives left are the ones this launcher wrote itself.
+ expect(message.replace(/^#\[[^\]]+\]/, '').replace(/#\[default\]$/, '')).not.toMatch(/(^|[^#])#([^#]|$)/)
+ })
+
+ it('ignores a colour that is not a colour', async () => {
+ // Escaping alone would not save this one: the payload closes the style bracket and opens its own,
+ // without needing a single `#`.
+ await push({ t: 'notice', text: 'hi', level: 'warn', color: 'red]#[fg=black' })
+ expect(lastNotice().join(' ')).toContain('#[bg=yellow,fg=black,bold] hi')
+ // The injected `]#[` never becomes a second style directive.
+ expect(lastNotice().join(' ')).not.toContain('red]')
+
+ // A colour that IS a colour is honoured — on the launcher's own background, never a supplied one.
+ FakeWs.instances[0].emit('message', JSON.stringify({ t: 'notice', text: 'hi', color: 'colour214' }))
+ expect(lastNotice().join(' ')).toContain('#[bg=black,fg=colour214,bold] hi')
+ })
+
+ it('clamps the duration instead of trusting it', async () => {
+ await push({ t: 'notice', text: 'a', durationMs: 999_999_999 })
+ expect(lastNotice()[lastNotice().indexOf('-d') + 1]).toBe('15000')
+
+ FakeWs.instances[0].emit('message', JSON.stringify({ t: 'notice', text: 'b', durationMs: -5 }))
+ expect(lastNotice()[lastNotice().indexOf('-d') + 1]).toBe('1000')
+
+ FakeWs.instances[0].emit('message', JSON.stringify({ t: 'notice', text: 'c', durationMs: 'soon' }))
+ expect(lastNotice()[lastNotice().indexOf('-d') + 1]).toBe('6000') // the launcher's own default
+ })
+
+ it('shrugs off a malformed notice rather than showing garbage', async () => {
+ await push({ t: 'notice' }) // no text at all
+ expect(notices()).toHaveLength(0)
+
+ FakeWs.instances[0].emit('message', JSON.stringify({ t: 'notice', text: ' ' }))
+ expect(notices()).toHaveLength(0) // nothing left after trimming
+
+ FakeWs.instances[0].emit('message', JSON.stringify({ t: 'notice', text: 'ok', level: 'catastrophe' }))
+ expect(lastNotice().join(' ')).toContain('#[bg=black,fg=cyan,bold] ok') // unknown level ⇒ info
+ expect(lastNotice()).not.toContain('-N')
+ })
+
+ it('ignores a frame type it has never heard of', async () => {
+ // The compatibility mechanism for every FUTURE daemon→launcher frame: a launcher released today must
+ // sit quietly through whatever a daemon from next year sends it.
+ await push({ t: 'some-future-frame', text: 'x', payload: { a: 1 } })
+ expect(notices()).toHaveLength(0)
+ expect(stderr.join('')).toBe('')
+ })
+
+ it('explains a disconnect that the daemon itself just announced', async () => {
+ await push({ t: 'notice', text: 'machine is updating — restarting now', level: 'warn' })
+ FakeWs.instances[0].emit('close')
+
+ // Telling someone to run `harness join` while the daemon is already coming back is wrong advice at
+ // the worst possible moment.
+ expect(lastNotice().join(' ')).toContain('restarting')
+ expect(lastNotice().join(' ')).not.toContain('harness join')
+ })
+
+ it('still gives the plain disconnect advice when nothing warned us', async () => {
+ await launch()
+ execFileMock.mockClear()
+ FakeWs.instances[0].emit('close')
+ expect(lastNotice().join(' ')).toContain('harness join')
+ })
+})
+/**
+ * Deleting an agent must end the launcher and the engine — and leave the tmux pane alone. These pin the
+ * launcher's half: it stops its child itself, routes teardown through the ONE existing exit path, and
+ * never treats the resulting socket close as "the daemon vanished".
+ */
+describe('daemon → launcher exit request', () => {
+ const notices = (): string[][] => execFileMock.mock.calls
+ .filter((c: unknown[]) => Array.isArray(c[1]) && (c[1] as string[])[0] === 'display-message')
+ .map((c: unknown[]) => c[1] as string[])
+
+ it('SIGTERMs the engine and says why on the status bar', async () => {
+ const child = fakeChild()
+ spawnMock.mockImplementation(() => child)
+ await launch()
+ execFileMock.mockClear()
+
+ FakeWs.instances[0].emit('message', JSON.stringify({ t: 'exit', reason: 'deleted' }))
+
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM')
+ expect(notices()[0]?.join(' ')).toContain('deleted')
+ // Not tmux's problem: the pane and its shell survive this.
+ expect(execFileMock.mock.calls.some((c: unknown[]) => (c[1] as string[])?.[0] === 'kill-pane')).toBe(false)
+ })
+
+ it('escalates to SIGKILL if the engine will not go', async () => {
+ vi.useFakeTimers()
+ try {
+ const child = fakeChild()
+ spawnMock.mockImplementation(() => child)
+ await launch()
+ FakeWs.instances[0].emit('message', JSON.stringify({ t: 'exit' }))
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM')
+
+ await vi.advanceTimersByTimeAsync(3_100)
+ // A CLI that traps SIGTERM for a confirmation prompt would otherwise survive its own deletion.
+ expect(child.kill).toHaveBeenCalledWith('SIGKILL')
+ } finally { vi.useRealTimers() }
+ })
+
+ it('lets the existing child-exit path do the teardown, not a second one', async () => {
+ const child = fakeChild()
+ spawnMock.mockImplementation(() => child)
+ await launch()
+ const ws = FakeWs.instances[0]
+
+ ws.emit('message', JSON.stringify({ t: 'exit' }))
+ expect(ws.closed).toBe(false) // the socket stays up until the engine is actually gone
+
+ try { child.emit('exit', 0, null) } catch { /* mocked process.exit throws */ }
+ await vi.waitFor(() => expect(exitCode).toBe(0))
+ expect(ws.closed).toBe(true)
+ })
+
+ it('stops reconnecting — a close after this is expected, not a lost daemon', async () => {
+ vi.useFakeTimers()
+ try {
+ const child = fakeChild()
+ spawnMock.mockImplementation(() => child)
+ await launch()
+ FakeWs.instances[0].emit('message', JSON.stringify({ t: 'exit' }))
+ execFileMock.mockClear()
+
+ FakeWs.instances[0].emit('close')
+ await vi.advanceTimersByTimeAsync(6_000)
+
+ expect(FakeWs.instances).toHaveLength(1) // no reconnect attempt
+ const said = notices().map((a) => a.join(' ')).join('\n')
+ expect(said).not.toContain('harness join') // and no misleading advice
+ } finally { vi.useRealTimers() }
+ })
+
+ it('handles an exit that arrives before the engine was even spawned', async () => {
+ // The daemon can answer `open` and then delete the agent while the launcher is still waiting on its
+ // ack — there is no child to stop yet, and the request must not be dropped on the floor.
+ const child = fakeChild()
+ spawnMock.mockImplementation(() => {
+ setTimeout(() => FakeWs.instances[0].emit('message', JSON.stringify({ t: 'exit' })), 0)
+ return child
+ })
+ await launch()
+ await vi.waitFor(() => expect(child.kill).toHaveBeenCalledWith('SIGTERM'))
+ })
+})
diff --git a/cli/src/lib/launch.ts b/cli/src/lib/launch.ts
new file mode 100644
index 000000000..4c6b917a6
--- /dev/null
+++ b/cli/src/lib/launch.ts
@@ -0,0 +1,499 @@
+/**
+ * `harness <engine> [args…]` — run an agent CLI inside the CURRENT tmux pane, wrapped so the adapter
+ * owns its lifecycle.
+ *
+ * Design (see the machine-ID architecture):
+ * - **No PTY library.** The command already runs in a tmux pane, so the pane IS the pty: `stdio:
+ * 'inherit'` hands the child the real tty. `capture-pane` output is byte-identical to running the
+ * CLI natively (verified), so submit-verification / question-scraping / the `/model` picker all keep
+ * working unchanged. That also means this file must print NOTHING to the pane while the child runs —
+ * any stray line would land inside the child's TUI. Mid-session notices go to the tmux status bar via
+ * `display-message` instead.
+ * - **Machine ID owns the session.** Each launch mints a UUID, exports it as `MACHINE_ID` for the child,
+ * and opens it with the daemon. The engine's own hook reports that id back at registration, so a
+ * session exists in the adapter only while its launching wrapper is alive.
+ * - **Two hard gates**: must be inside tmux, and the daemon must already be joined + running. Neither is
+ * auto-provisioned — we refuse with an instruction instead of doing something behind the user's back.
+ */
+
+import { execFile, spawn } from 'child_process'
+import { randomUUID } from 'crypto'
+import { WebSocket } from 'ws'
+import { env } from '../config/env.js'
+import { VERSION } from '../version.js'
+import type { AgentEngine } from '../engines/types.js'
+import { daemonPort, hasSavedToken, isDaemonRunning } from './daemonState.js'
+import { engineBin } from './engineBin.js'
+import { permissionArgsFor } from './enginePermissions.js'
+import { MACHINE_WS_PATH } from './launcherSessions.js'
+import {
+ LAUNCHER_PROTOCOL_V, isSupportedProtocol,
+ type LauncherDownFrame, type LauncherNoticeFrame, type LauncherNoticeLevel, type LauncherOpenedFrame,
+} from './launcherProtocol.js'
+import { installHooksFor } from './hooks.js'
+
+const PANE_RE = /^%\d+$/
+/** How long each status-bar warning stays up. Must EXCEED the reconnect interval (RETRY_MS) so
+ * consecutive notices OVERLAP and the line never blinks out between them. tmux's own `display-time`
+ * default is 750ms, which flashed past unseen. Deliberately finite rather than `-d 0` ("stay until a key
+ * is pressed"), because that variant consumes the next keystroke — and the user is typing into the agent. */
+const NOTICE_MS = 6_000
+/** How long to wait for the daemon's `opened` ack before falling back to this build's own answers. */
+const ACK_WAIT_MS = 2_000
+
+function fail(lines: string[]): never {
+ for (const line of lines) console.error(line)
+ process.exit(1)
+}
+
+/** The running daemon's health, build and supported protocols — or null when it is not answering. */
+async function daemonInfo(timeoutMs = 2_000): Promise<{ version?: string; protocols?: number[] } | null> {
+ const ctrl = new AbortController()
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs)
+ try {
+ const res = await fetch(`http://127.0.0.1:${daemonPort()}/api/health`, { signal: ctrl.signal })
+ if (!res.ok) return null
+ return (await res.json().catch(() => ({}))) as { version?: string; protocols?: number[] }
+ } catch { return null } finally { clearTimeout(timer) }
+}
+
+/**
+ * Style per level — foreground AND background, always both.
+ *
+ * tmux paints the status message with `message-style`, which defaults to `bg=yellow,fg=black`. Setting
+ * only a foreground therefore gambles on the user's theme, and loses: `fg=yellow` on that default
+ * rendered yellow-on-yellow — a solid gold bar with the text invisible inside it (seen on a real pane,
+ * 2026-08-03). Naming the background too makes contrast ours to guarantee rather than theirs to supply.
+ *
+ * `warn` deliberately matches the tmux default, so the common case looks native rather than decorated.
+ */
+const LEVEL_STYLE: Record<LauncherNoticeLevel, string> = {
+ info: 'bg=black,fg=cyan,bold',
+ warn: 'bg=yellow,fg=black,bold',
+ error: 'bg=red,fg=white,bold',
+}
+/** A tmux colour name (`red`, `brightblack`, `colour214`) or `#rrggbb`. Anything else is not a colour. */
+const SAFE_COLOUR = /^(?:[a-zA-Z][a-zA-Z0-9]{0,15}|#[0-9a-fA-F]{6})$/
+const NOTICE_MIN_MS = 1_000
+const NOTICE_MAX_MS = 15_000
+const NOTICE_MAX_CHARS = 300
+/** Gap between the repeats a warning gets, so one keystroke cannot erase it for good. */
+const NOTICE_REPEAT_MS = 2_500
+/** How often the launcher re-dials a daemon that is not answering. Flat, and coupled to
+ * MACHINE_RECONNECT_GRACE_MS (cli.ts, 15s): the grace covers several of these, so "it never came back"
+ * is a verdict about the launcher, not about how long a backoff happened to have grown. */
+const RETRY_MS = 2_000
+/** SIGTERM → SIGKILL for the engine when the agent is deleted. Coupled to `FALLBACK_CHECK_MS`
+ * (deleteAgentFallback.ts), which must stay LONGER so a launcher that got the request always wins. */
+const LAUNCHER_EXIT_GRACE_MS = 3_000
+
+/**
+ * Make daemon-supplied text safe to hand to `tmux display-message`.
+ *
+ * That command runs its argument through tmux's FORMATS parser (we cannot pass `-l`, which would print
+ * our own colour directives literally). So `#` is live syntax there — `#{…}` interpolates variables,
+ * `#[…]` switches style mid-string, and `#(…)` runs a shell command. Doubling every `#` is what turns the
+ * message back into text. Control characters go too: the status line is one row, and a stray ESC would
+ * repaint it.
+ */
+function escapeNoticeText(text: string): string {
+ return text
+ .replace(/[\u0000-\u001f\u007f]+/g, ' ')
+ .replace(/#/g, '##')
+ .slice(0, NOTICE_MAX_CHARS)
+ .trim()
+}
+
+/**
+ * Status-bar notice on the pane running the agent. Deliberately NOT stdout: writing into the pane would
+ * corrupt the child's TUI and the pane captures the adapter scrapes. Best-effort.
+ *
+ * A status message is erased by the user's next keystroke, so a warning shown once is a warning missed.
+ * The fix is to REPEAT it, not to make it sticky: tmux's `-N` ("ignore key presses") does not merely keep
+ * the message up, it swallows the keystrokes entirely — measured on a real pane, keys typed during a 6s
+ * `-N` notice never reached the child, before or after it expired. That is a frozen terminal and lost
+ * input, which is far worse than a missed notice. So warnings re-post a couple of times instead, and the
+ * user keeps typing throughout.
+ */
+function paneNotice(pane: string, message: string, opts: {
+ level?: LauncherNoticeLevel
+ color?: string
+ durationMs?: number
+} = {}): void {
+ const level: LauncherNoticeLevel = opts.level && opts.level in LEVEL_STYLE ? opts.level : 'info'
+ // An override picks the text colour only; the background stays ours, so no colour the daemon sends can
+ // land on top of itself.
+ const style = opts.color && SAFE_COLOUR.test(opts.color)
+ ? `bg=black,fg=${opts.color},bold`
+ : LEVEL_STYLE[level]
+ const ms = Number.isFinite(opts.durationMs)
+ ? Math.min(NOTICE_MAX_MS, Math.max(NOTICE_MIN_MS, Math.round(opts.durationMs as number)))
+ : NOTICE_MS
+ const text = escapeNoticeText(message)
+ if (!text) return
+ const args = ['display-message', '-d', String(ms), '-t', pane, `#[${style}] ${text} #[default]`]
+ const post = (): void => { execFile('tmux', args, { timeout: 2_000 }, () => { /* best effort */ }) }
+ post()
+ if (level === 'info') return
+ // Two more chances to be read, since the first one dies with the next keystroke. Unref'd: a notice must
+ // never be the reason this process outlives the agent it wraps.
+ for (const delay of [NOTICE_REPEAT_MS, NOTICE_REPEAT_MS * 2]) {
+ const timer = setTimeout(post, delay)
+ timer.unref?.()
+ }
+}
+
+/**
+ * The launcher's lifeline to the daemon.
+ *
+ * One WebSocket, open for the whole run. It carries no terminal data — only `{t:'open'}` — because its
+ * VALUE IS ITS EXISTENCE: while it is up the daemon knows this launcher lives (no `ps` scanning), and the
+ * moment it drops we know the daemon is gone (no health polling). Both directions are now event-driven
+ * instead of the two 3-5s poll loops this replaced.
+ *
+ * A drop is never fatal: the agent keeps running and we reconnect with backoff, so a daemon self-update
+ * (which restarts it) reclaims the session within ~1s instead of orphaning it.
+ */
+class LauncherLink {
+ private ws: WebSocket | null = null
+ private retry: NodeJS.Timeout | null = null
+ private disposed = false
+ private everConnected = false
+ /** Is the daemon reachable right now? */
+ up = false
+ /** True once the daemon has told us it cannot speak our protocol version. */
+ incompatible = false
+ private resolveAck: ((frame: LauncherOpenedFrame) => void) | null = null
+ /** Called on every up→down / down→up transition (not on the first connect). */
+ onState: (up: boolean) => void = () => { /* set by the caller */ }
+ /** Called on each failed reconnect while still down — the caller re-posts its notice. A tmux status
+ * message is transient (it clears after `display-time` OR on the next key press, and the user is
+ * typing into the agent), so a single announcement WILL be missed. */
+ onStillDown: () => void = () => { /* set by the caller */ }
+ /** Called when the daemon refuses our protocol version — the agent runs on, but is unreachable from the
+ * web until the user restarts it, so this one is announced repeatedly. */
+ onIncompatible: () => void = () => { /* set by the caller */ }
+ /** Called when the daemon reports a different BUILD. Informational: protocol compatibility is what
+ * decides whether things work; this only tells the user a newer machine is live. */
+ onStaleBuild: (daemonVersion: string) => void = () => { /* set by the caller */ }
+ /** Called for a notice the daemon pushed on its own initiative. */
+ onNotice: (frame: LauncherNoticeFrame) => void = () => { /* set by the caller */ }
+ /** Called when the daemon asks this agent to end (the user deleted it). */
+ onExitRequested: (reason: string | undefined) => void = () => { /* set by the caller */ }
+ /** Set if the request arrived before the caller had a child to stop — it re-runs the callback itself. */
+ exitRequested: string | undefined | false = false
+ /**
+ * When the daemon last warned us, so a drop right after can be explained instead of misreported.
+ *
+ * A daemon that says "I am restarting" and then closes the socket is not the same event as a daemon
+ * that vanished — but they look identical from here, and the ordinary message tells the user to run
+ * `harness join`, which would be wrong advice while the daemon is already coming back on its own.
+ */
+ private warnedAt = 0
+ /** True while a warning from the daemon is recent enough to explain the current disconnect. */
+ recentlyWarned(withinMs = 30_000): boolean {
+ return this.warnedAt > 0 && Date.now() - this.warnedAt < withinMs
+ }
+
+ constructor(
+ private readonly launcherId: string,
+ private readonly engine: AgentEngine,
+ private readonly pane: string,
+ private readonly cwd: string,
+ ) {}
+
+ connect(): void {
+ if (this.disposed || this.ws) return
+ let ws: WebSocket
+ try {
+ ws = new WebSocket(`ws://127.0.0.1:${daemonPort()}${MACHINE_WS_PATH}`)
+ } catch { this.scheduleRetry(); return }
+ this.ws = ws
+
+ ws.on('open', () => {
+ const wasDown = this.everConnected && !this.up
+ this.up = true
+ this.everConnected = true
+ try {
+ ws.send(JSON.stringify({
+ t: 'open', v: LAUNCHER_PROTOCOL_V, launcherId: this.launcherId, engine: this.engine,
+ tmuxPane: this.pane, cwd: this.cwd, version: VERSION,
+ }))
+ } catch { /* the close handler will retry */ }
+ if (wasDown) this.onState(true)
+ })
+ // The ack is not decoration: it carries the engine binary and whether the daemon installed the
+ // hooks, i.e. the two decisions moved OUT of this (possibly outdated) launcher.
+ ws.on('message', (raw: unknown) => {
+ let frame: LauncherDownFrame
+ try { frame = JSON.parse(String(raw)) as LauncherDownFrame } catch { return }
+ if (frame.t === 'error') {
+ // The daemon cannot speak our protocol. The agent keeps running — killing someone's session over
+ // this would be worse — but it is NOT remote-controllable, so say so until they restart it.
+ this.incompatible = frame.reason === 'unsupported_protocol'
+ if (this.incompatible) this.onIncompatible()
+ return
+ }
+ if (frame.t === 'exit') {
+ // The agent was deleted. Stop reconnecting FIRST: the socket is about to close for a known reason,
+ // and the disconnect notice would otherwise tell the user their agent lost the daemon.
+ this.stopReconnecting()
+ this.exitRequested = typeof frame.reason === 'string' ? frame.reason : undefined
+ this.onExitRequested(this.exitRequested)
+ return
+ }
+ if (frame.t === 'notice') {
+ // Nothing here trusts the frame: `text` may be missing on a malformed one, and everything else is
+ // clamped downstream in paneNotice. A bad notice must be a no-op, never a crash — and never a
+ // console line, which would land inside the child's TUI.
+ if (typeof frame.text === 'string' && frame.text) {
+ if (frame.level === 'warn' || frame.level === 'error') this.warnedAt = Date.now()
+ this.onNotice(frame)
+ }
+ return
+ }
+ if (frame.t !== 'opened') return
+ this.resolveAck?.(frame)
+ this.resolveAck = null
+ if (frame.version && frame.version !== VERSION) this.onStaleBuild(frame.version)
+ })
+ // 'error' is always followed by 'close', so recovery lives in one place.
+ ws.on('error', () => { /* handled by close */ })
+ ws.on('close', () => {
+ this.ws = null
+ if (this.disposed) return
+ if (this.up) { this.up = false; this.onState(false) }
+ this.scheduleRetry()
+ })
+ }
+
+ private scheduleRetry(): void {
+ if (this.disposed || this.retry) return
+ // A FLAT interval, not a backoff. The daemon decides a launcher is dead when it has not reconnected
+ // within MACHINE_RECONNECT_GRACE_MS (cli.ts) — and that verdict is only as good as the retry rhythm
+ // behind it. At a fixed 2s the 15s grace always covers several whole attempts; the old 0.5→1→2→4→5s
+ // backoff made the number of attempts inside that window depend on how long the daemon had already
+ // been away, so a long outage quietly made the verdict less safe. Keep trying forever: the user is
+ // still working in the agent, and the daemon may come back at any time (`harness join`, self-update).
+ const delay = RETRY_MS
+ this.retry = setTimeout(() => {
+ this.retry = null
+ // Re-announce BEFORE retrying: if the daemon is still gone the notice is back on screen within a
+ // few seconds of being dismissed, instead of the user seeing it once and losing it.
+ if (this.everConnected && !this.up) this.onStillDown()
+ this.connect()
+ }, delay)
+ this.retry.unref?.()
+ }
+
+ /**
+ * The daemon's answer to our `open`, or null if it does not arrive in time.
+ *
+ * Bounded on purpose: the ack decides the binary and the hooks, but waiting for a daemon that is wedged
+ * must NEVER stop the user's agent from starting — on timeout the launcher falls back to its own
+ * (possibly older) resolution and spawns anyway.
+ */
+ waitForAck(timeoutMs: number): Promise<LauncherOpenedFrame | null> {
+ return new Promise((resolve) => {
+ const timer = setTimeout(() => { this.resolveAck = null; resolve(null) }, timeoutMs)
+ timer.unref?.()
+ this.resolveAck = (frame) => { clearTimeout(timer); resolve(frame) }
+ })
+ }
+
+ /**
+ * Stop chasing the daemon, but leave the socket open.
+ *
+ * Not `dispose()`: this runs while the engine is still shutting down, and the socket must stay up until
+ * the child actually exits so teardown keeps flowing through the ONE existing path (`child.on('exit')`
+ * → `closeSession()`), instead of a second one racing it.
+ */
+ stopReconnecting(): void {
+ this.disposed = true
+ if (this.retry) { clearTimeout(this.retry); this.retry = null }
+ }
+
+ /** End the session: closing the socket is what tells the daemon to drop the tile immediately. */
+ dispose(): void {
+ this.disposed = true
+ if (this.retry) { clearTimeout(this.retry); this.retry = null }
+ const ws = this.ws
+ this.ws = null
+ try { ws?.close() } catch { /* already gone */ }
+ }
+}
+
+/**
+ * Launch `engine` with `argv` forwarded verbatim. Returns never — it always ends the process with the
+ * child's exit status so `harness claude …` is indistinguishable from `claude …` to the calling shell.
+ */
+export async function launchEngine(engine: AgentEngine, argv: string[]): Promise<never> {
+ // ── Gate 1: must already be inside tmux. The machine never creates a tmux session; the pane is what
+ // gives us both the pty and the addressable target the remote side types into.
+ const pane = process.env.TMUX_PANE ?? ''
+ if (!process.env.TMUX || !PANE_RE.test(pane)) {
+ fail([
+ `\n ✗ machine ${engine} must run inside tmux.`,
+ '',
+ ' Start one, then run it again:',
+ ' tmux new -s work',
+ ` machine ${engine}\n`,
+ ])
+ }
+
+ // ── Gate 2: the daemon must already be joined AND running. We never start it implicitly.
+ const info = isDaemonRunning() ? await daemonInfo() : null
+ if (!info) {
+ fail(hasSavedToken()
+ ? [
+ '\n ✗ The machine adapter is not running on this computer.',
+ '',
+ ' Start it (the saved credential is reused):',
+ ' harness join\n',
+ ]
+ : [
+ '\n ✗ This computer has not joined a machine yet.',
+ '',
+ ' Join it with the token from your machine page:',
+ ' harness join <token>\n',
+ ])
+ }
+
+ // ── Gate 3: the daemon must be able to SPEAK to us. Deliberately a protocol check, not a build check:
+ // launcher and daemon come from the same OTA bundle but a running launcher keeps its build for hours,
+ // so different builds are normal and fine — only an unsupported PROTOCOL actually breaks the session.
+ // (A daemon predating protocol advertisement is a v1 daemon.)
+ const protocols = info.protocols ?? [1]
+ if (!protocols.includes(LAUNCHER_PROTOCOL_V)) {
+ fail([
+ `\n ✗ The running machine is too old to talk to this CLI (it speaks protocol v${protocols.join('/')}, this needs v${LAUNCHER_PROTOCOL_V}).`,
+ '',
+ ' Restart it on the current build:',
+ ' harness stop && harness join\n',
+ ])
+ }
+
+ // ── Open the machine session over a WebSocket that stays up for the whole run. The SOCKET is the
+ // liveness signal in both directions: while it is open the daemon knows this launcher lives, and the
+ // moment it drops we know the daemon is gone — no polling on either side.
+ const launcherId = randomUUID()
+ const link = new LauncherLink(launcherId, engine, pane, process.cwd())
+
+ // Wire the notices BEFORE connecting. The daemon can refuse our protocol on the very first frame, and
+ // callbacks attached after the spawn would miss it — the user would then get no warning at all for the
+ // one case where the agent is live but permanently unreachable.
+ // Every notice goes to the tmux status bar, never into the pane the TUI is drawing in.
+ const incompatibleNotice = (): void =>
+ paneNotice(pane, `harness was updated and can no longer drive this agent · exit and re-run: harness ${engine}`, { level: 'error' })
+ // A drop right after the daemon warned us is the daemon restarting ITSELF (an update), and it comes back
+ // on its own — telling the user to run `harness join` there would be wrong advice at the worst moment.
+ const disconnectedNotice = (): void => link.recentlyWarned()
+ ? paneNotice(pane, 'harness is restarting — this agent reconnects on its own', { level: 'warn' })
+ : paneNotice(pane, 'harness disconnected — this agent is no longer remote-controllable · run: harness join', { level: 'warn' })
+ link.onState = (up: boolean): void => {
+ if (up) paneNotice(pane, 'harness reconnected')
+ else disconnectedNotice()
+ }
+ link.onStillDown = (): void => { link.incompatible ? incompatibleNotice() : disconnectedNotice() }
+ // Anything the daemon decides the person in this pane should see. The frame is advisory: paneNotice
+ // clamps the duration, filters the colour and escapes the text before any of it reaches tmux.
+ link.onNotice = (frame: LauncherNoticeFrame): void =>
+ paneNotice(pane, frame.text, { level: frame.level, color: frame.color, durationMs: frame.durationMs })
+ link.onIncompatible = incompatibleNotice
+ link.onStaleBuild = (daemonVersion: string): void => {
+ paneNotice(pane, `harness updated to v${daemonVersion} (this agent runs v${VERSION}) · exit and re-run: harness ${engine}`)
+ }
+
+ link.connect()
+
+ // ── Let the DAEMON decide the two things that change between builds: which binary an engine maps to,
+ // and what this engine's hooks look like. A launcher left over from an older build would otherwise
+ // spawn a stale binary name and install stale hook definitions. Bounded wait — a wedged daemon must
+ // never stop the agent from starting, so on timeout we fall back to this build's own answers.
+ const ack = await link.waitForAck(ACK_WAIT_MS)
+ const bin = ack?.bin || engineBin(engine)
+ if (!ack?.hooksReady && !env.DISABLE_HOOK_INSTALL) {
+ // Fallback only. The installers narrate to stdout, which here is the user's pane — a stray
+ // "[hooks] …" line would print above the CLI's TUI, so swallow their chatter.
+ const { log, error, warn } = console
+ console.log = console.error = console.warn = () => { /* silence: this is the user's terminal */ }
+ try { installHooksFor(engine, daemonPort()) } catch { /* never block the launch on hook install */ }
+ finally { Object.assign(console, { log, error, warn }) }
+ }
+
+ // ── Permissions. Nobody is watching this pane — it is driven from web/device — so an agent that stops
+ // to ask is an agent that never answers. Add the engine's bypass flags unless the user named their own
+ // policy (that is the only opt-out, by design). Flags are the whole mechanism: where a CLI keeps its
+ // directory trust in a config file and offers no flag (devin, codex), machine leaves that prompt alone
+ // and the user answers it once, here in the pane, rather than machine editing their config for them.
+ const launchArgv = [...argv, ...permissionArgsFor(engine, argv)]
+
+ // ── Spawn. `stdio: 'inherit'` → the child owns the real tty (colors, keys, resize, isTTY all native).
+ // TMUX / TMUX_PANE are deliberately kept (the opposite of the recap one-shots, which scrub them so they
+ // cannot self-register) — the engine's hook needs the pane, and now the machine id too.
+ const child = spawn(bin, launchArgv, {
+ stdio: 'inherit',
+ env: { ...process.env, MACHINE_ID: launcherId },
+ })
+
+ const closeSession = async (): Promise<void> => { link.dispose() }
+
+ /**
+ * The agent was deleted from the web or the device: end the engine, and let the existing child-exit
+ * handler end this wrapper. The tmux pane is untouched — the user gets their shell prompt back.
+ *
+ * SIGTERM, then SIGKILL if the engine will not go: "delete" has to mean deleted, and a CLI that traps
+ * SIGTERM for a confirmation prompt would otherwise leave an agent running that nothing on screen
+ * accounts for. The daemon has its own, later backstop for launchers too old to receive this at all.
+ */
+ let exiting = false
+ const endForDeletion = (reason: string | undefined): void => {
+ if (exiting) return
+ exiting = true
+ paneNotice(pane, `harness: this agent was deleted${reason ? ` (${reason})` : ''} — closing`, { level: 'warn' })
+ try { child.kill('SIGTERM') } catch { /* already gone; the exit handler runs either way */ }
+ const grace = setTimeout(() => {
+ try { child.kill('SIGKILL') } catch { /* already gone */ }
+ }, LAUNCHER_EXIT_GRACE_MS)
+ grace.unref?.()
+ }
+ link.onExitRequested = endForDeletion
+ // The frame can arrive while we were still waiting for the ack, i.e. before there was a child to stop.
+ if (link.exitRequested !== false) endForDeletion(link.exitRequested)
+
+ // Ctrl-C is delivered by the tty driver to the whole foreground process group, so the child already
+ // gets it — the wrapper must NOT die first, or the shell would take the prompt back while the agent is
+ // still drawing. Ignore it here and let the child decide, exactly like running the CLI directly.
+ process.on('SIGINT', () => { /* child handles it */ })
+ for (const sig of ['SIGTERM', 'SIGHUP'] as const) {
+ process.on(sig, () => { try { child.kill(sig) } catch { /* already gone */ } })
+ }
+
+
+ child.on('error', (err: NodeJS.ErrnoException) => {
+ // `.catch` after the exit: nothing here may surface as an unhandled rejection — the close is
+ // best-effort and the handler's last act is to end the process anyway.
+ void closeSession().finally(() => {
+ if (err.code === 'ENOENT') {
+ console.error(`machine: ${bin}: command not found`)
+ process.exit(127) // same code a shell uses for a missing command
+ }
+ console.error(`machine: failed to start ${bin}: ${err.message}`)
+ process.exit(1)
+ }).catch(() => { /* exit already requested */ })
+ })
+
+ child.on('exit', (code, signal) => {
+ // `.catch` after the exit: nothing here may surface as an unhandled rejection — the close is
+ // best-effort and the handler's last act is to end the process anyway.
+ void closeSession().finally(() => {
+ // Re-raise the signal on ourselves so the calling shell reports the death exactly as it would for
+ // the CLI run directly (e.g. 130 for SIGINT), instead of a synthesized exit code.
+ if (signal) { process.kill(process.pid, signal); return }
+ process.exit(code ?? 0)
+ }).catch(() => { /* exit already requested */ })
+ })
+
+ // Keep the event loop alive until one of the handlers above exits the process.
+ return new Promise<never>(() => { /* resolved by process.exit */ })
+}
diff --git a/cli/src/lib/launcherProtocol.ts b/cli/src/lib/launcherProtocol.ts
new file mode 100644
index 000000000..6d068c4c8
--- /dev/null
+++ b/cli/src/lib/launcherProtocol.ts
@@ -0,0 +1,118 @@
+/**
+ * The launcher ↔ daemon wire contract.
+ *
+ * ⚠ THIS FILE IS A COMPATIBILITY CONTRACT, NOT ORDINARY CODE.
+ *
+ * Why it has to be: OTA ships ONE bundle containing both the daemon and the launcher. The daemon
+ * restarts onto the new build, but a `harness <engine>` already running is a long-lived process holding
+ * the build it started with — and it CANNOT upgrade itself (its process owns the tty and is the agent's
+ * parent). So a v0.0.1 launcher talking to a v9.9.9 daemon is normal, expected, and may last for hours.
+ *
+ * Therefore:
+ * - `v: 1` is a promise to every launcher already in the wild. You may ADD optional fields to a
+ * version. You may NOT rename, remove, retype, or reinterpret an existing field.
+ * - To change any of that, define `v: 2` and have the daemon serve BOTH. Only add to
+ * SUPPORTED_PROTOCOLS; removing an entry breaks released launchers and needs a deprecation window.
+ * - `launcherProtocol.spec.ts` pins a HAND-WRITTEN v1 frame (not one built from these types) and
+ * asserts the daemon still accepts it. That test is the contract; if it goes red, a released
+ * launcher just broke.
+ *
+ * The build version (`version`) is carried separately and is only informational — two different builds
+ * interoperate as long as they share a protocol version.
+ */
+
+import type { AgentEngine } from '../engines/types.js'
+
+/** Protocol version this build's launcher speaks. */
+export const LAUNCHER_PROTOCOL_V = 1
+
+/** Protocol versions this build's daemon accepts. APPEND ONLY — see the file header. */
+export const SUPPORTED_PROTOCOLS: readonly number[] = [1]
+
+/** Launcher → daemon, first frame after the socket opens. */
+export interface LauncherOpenFrame {
+ t: 'open'
+ /** Absent on launchers released before versioning existed — treat as 1. */
+ v?: number
+ launcherId?: string
+ engine?: AgentEngine
+ tmuxPane?: string
+ cwd?: string
+ /** The launcher's BUILD, for the stale-build notice. Never used for compatibility decisions. */
+ version?: string
+}
+
+/** Daemon → launcher, acknowledging a usable `open`. */
+export interface LauncherOpenedFrame {
+ t: 'opened'
+ v: number
+ /** The daemon's build — the launcher compares it with its own to tell the user a newer one is live. */
+ version: string
+ /** Engine binary resolved BY THE DAEMON, so binary policy can change without stranding old launchers. */
+ bin?: string
+ /** True when the daemon (re)installed this engine's hooks, so the launcher must not do it itself. */
+ hooksReady?: boolean
+}
+
+/** Daemon → launcher, refusing the socket. The only case where a session is turned away. */
+export interface LauncherErrorFrame {
+ t: 'error'
+ reason: 'unsupported_protocol' | 'invalid_open'
+ supported?: readonly number[]
+}
+
+export type LauncherNoticeLevel = 'info' | 'warn' | 'error'
+
+/**
+ * Daemon → launcher, unprompted: put this on the pane's status line.
+ *
+ * The first frame the daemon sends on its own initiative rather than as an answer to `open`. It exists
+ * because the daemon knows things the person in the pane does not — it restarts itself for an update mid-turn,
+ * for one — and until now had no way to say so.
+ *
+ * **Every field is advisory and the LAUNCHER decides how to render it**, on purpose: this frame crosses a
+ * version boundary (a months-old launcher, a daemon from today), so a value the launcher does not like must
+ * degrade to a sane default, never to a broken status line. See `paneNotice` for the clamping and escaping —
+ * the text reaches tmux's format parser, so it cannot be trusted as-is even coming from the daemon.
+ */
+export interface LauncherNoticeFrame {
+ t: 'notice'
+ text: string
+ /** Absent or unknown ⇒ 'info'. Picks the colour and whether the notice survives a keypress. */
+ level?: LauncherNoticeLevel
+ /** Clamped by the launcher; absent ⇒ its default. */
+ durationMs?: number
+ /** Overrides the level's colour. Ignored unless it is a plain tmux colour name or `#rrggbb`. */
+ color?: string
+}
+
+/**
+ * Daemon → launcher: end this agent — stop the engine and exit.
+ *
+ * Sent when the agent is deleted from the web or the device. The launcher owns its own child, so asking
+ * it to shut down beats the daemon reaching in and signalling processes: deleting an agent must not cost
+ * the user their tmux pane, which is what killing the pane (the old behaviour) did.
+ *
+ * A launcher too old to know this frame ignores it, so the daemon still verifies the outcome and falls
+ * back to signalling the engine directly — see `deleteAgentFallback.ts`.
+ */
+export interface LauncherExitFrame {
+ t: 'exit'
+ /** Why, for the log and the status-line notice. */
+ reason?: string
+}
+
+export type LauncherDownFrame =
+ | LauncherOpenedFrame
+ | LauncherErrorFrame
+ | LauncherNoticeFrame
+ | LauncherExitFrame
+
+/** Protocol version of an incoming frame: absent ⇒ 1 (pre-versioning launcher). */
+export function frameProtocol(frame: { v?: unknown }): number {
+ return typeof frame.v === 'number' ? frame.v : 1
+}
+
+export function isSupportedProtocol(v: number): boolean {
+ return SUPPORTED_PROTOCOLS.includes(v)
+}
diff --git a/cli/src/lib/launcherSessions.ts b/cli/src/lib/launcherSessions.ts
new file mode 100644
index 000000000..237a3f6e6
--- /dev/null
+++ b/cli/src/lib/launcherSessions.ts
@@ -0,0 +1,145 @@
+/**
+ * The live-machine book — the adapter's source of truth for session lifetime.
+ *
+ * Every `harness <engine>` launch mints a UUID and holds ONE WebSocket to the daemon for as long as it
+ * runs. The socket IS the liveness signal:
+ *
+ * an agent exists in the adapter ⇔ its launcher's socket is open
+ *
+ * That is why nothing here is polled or persisted. It replaced two polling loops (the launcher probing
+ * `GET /api/health` every 3s, and the daemon scanning `ps` for the launcher's pid every 5s), so a
+ * disconnect in either direction is now noticed the moment the socket closes instead of up to 5s later.
+ *
+ * Not persisted on purpose: a daemon restart tears down every socket, and each surviving launcher
+ * reconnects and re-announces itself within ~1s. Sessions loaded from `registry.json` at boot are given
+ * a short reconnect grace (see cli.ts) before being dropped — that grace is what tells "the daemon just
+ * self-updated" apart from "the launcher is gone".
+ */
+
+import type { AgentEngine } from '../engines/types.js'
+import type { LauncherNoticeFrame } from './launcherProtocol.js'
+
+/** Loopback path the `harness <engine>` launcher upgrades on (same port as the hook server). */
+export const MACHINE_WS_PATH = '/api/machine-ws'
+
+/** Only what this module needs from a socket — keeps it trivially testable without `ws`. */
+export interface LauncherSocket {
+ close(): void
+ /** `ws.WebSocket.send`. The callback fires once the frame has left (or failed to leave) this process. */
+ send(data: string, cb?: (err?: Error) => void): void
+}
+
+export interface LauncherSession {
+ launcherId: string
+ engine: AgentEngine
+ tmuxPane: string
+ cwd: string | null
+ socket: LauncherSocket
+ openedAt: number
+}
+
+export interface LauncherOpenInput {
+ launcherId?: string
+ engine?: AgentEngine
+ tmuxPane?: string
+ cwd?: string
+}
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
+const PANE_RE = /^%\d+$/
+
+class LauncherSessionBook {
+ private live = new Map<string, LauncherSession>()
+
+ /**
+ * Bind a launcher's socket to its machine id. Returns null when the payload is not a usable session.
+ *
+ * A re-`open` for an id we already hold (the launcher reconnecting after a daemon restart) REPLACES
+ * the old entry and closes its stale socket, so a reconnect can never leave two sockets claiming the
+ * same session.
+ */
+ open(input: LauncherOpenInput, socket: LauncherSocket): LauncherSession | null {
+ const launcherId = input.launcherId ?? ''
+ const pane = input.tmuxPane ?? ''
+ if (!UUID_RE.test(launcherId) || !PANE_RE.test(pane) || !input.engine) return null
+ const previous = this.live.get(launcherId)
+ if (previous && previous.socket !== socket) {
+ try { previous.socket.close() } catch { /* already gone */ }
+ }
+ const entry: LauncherSession = {
+ launcherId,
+ engine: input.engine,
+ tmuxPane: pane,
+ cwd: input.cwd ?? null,
+ socket,
+ openedAt: previous?.openedAt ?? Date.now(),
+ }
+ this.live.set(launcherId, entry)
+ return entry
+ }
+
+ close(launcherId: string): boolean {
+ return this.live.delete(launcherId)
+ }
+
+ /**
+ * Drop the session owned by a socket that just closed, returning its machine id (or null when the
+ * socket had already been replaced by a reconnect — in that case the NEWER socket owns the id and
+ * must not be evicted by the older one's close event).
+ */
+ closeBySocket(socket: LauncherSocket): string | null {
+ for (const [id, s] of this.live) {
+ if (s.socket === socket) { this.live.delete(id); return id }
+ }
+ return null
+ }
+
+ has(launcherId: string | undefined): boolean {
+ return !!launcherId && this.live.has(launcherId)
+ }
+
+ get(launcherId: string): LauncherSession | undefined {
+ return this.live.get(launcherId)
+ }
+
+ /**
+ * The launcher currently holding a tmux pane, if any.
+ *
+ * Used to adopt a session nobody announced (a resumed agent): the engine's hook never fired, so the
+ * only proof that this pane is a machine agent — and the only source of the launcherId that binds a
+ * session to a lifetime — is the live launcher socket.
+ */
+ byPane(tmuxPane: string): LauncherSession | undefined {
+ for (const s of this.live.values()) if (s.tmuxPane === tmuxPane) return s
+ return undefined
+ }
+
+ list(): LauncherSession[] {
+ return [...this.live.values()]
+ }
+
+ /**
+ * Push one notice to every live launcher, and wait — briefly — for it to actually leave this process.
+ *
+ * The waiting is the point. The only caller so far is the update restart, which tears the daemon down
+ * moments later; a fire-and-forget `send` there is a message that may never make it onto the wire. The
+ * bound keeps that from turning into a stall: after `timeoutMs` we proceed regardless, because a stuck
+ * socket must never be able to hold up a restart.
+ *
+ * Never throws, never rejects. A broken socket is one launcher missing one notice — it is not a reason
+ * for whatever the caller was doing to fail.
+ */
+ async notifyAll(frame: LauncherNoticeFrame, timeoutMs = 300): Promise<void> {
+ const payload = JSON.stringify(frame)
+ const sends = [...this.live.values()].map((session) => new Promise<void>((resolve) => {
+ try { session.socket.send(payload, () => resolve()) } catch { resolve() }
+ }))
+ if (!sends.length) return
+ await Promise.race([
+ Promise.all(sends).then(() => undefined),
+ new Promise<void>((resolve) => { const t = setTimeout(resolve, timeoutMs); t.unref?.() }),
+ ])
+ }
+}
+
+export const launcherSessions = new LauncherSessionBook()
diff --git a/cli/src/lib/log.spec.ts b/cli/src/lib/log.spec.ts
new file mode 100644
index 000000000..ae493c912
--- /dev/null
+++ b/cli/src/lib/log.spec.ts
@@ -0,0 +1,143 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { closeSync, existsSync, mkdtempSync, openSync, readFileSync, rmSync, statSync, writeFileSync, writeSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import {
+ ts, sid, preview, installTimestampedConsole,
+ adoptLegacyLog, prepareLogFile, trimLogFile, LOG_MAX_BYTES,
+} from './log.js'
+
+describe('log helpers', () => {
+ afterEach(() => vi.restoreAllMocks())
+
+ it('formats ts() as YYYY-MM-DD HH:MM:SS.mmm', () => {
+ expect(ts(new Date(2026, 6, 24, 9, 5, 3, 7))).toBe('2026-07-24 09:05:03.007')
+ expect(ts()).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}$/)
+ })
+
+ it('shortens session ids', () => {
+ expect(sid('69aaaa14-89e9-7e21-871a-ee6ea943fc95')).toBe('69aaaa14')
+ })
+
+ it('flattens whitespace and caps preview with an ellipsis', () => {
+ expect(preview(' hello\n\n world ')).toBe('hello world')
+ expect(preview('abcdef', 3)).toBe('abc…')
+ expect(preview('')).toBe('')
+ })
+
+ it('prepends a timestamp yet preserves the original args (waitForReady marker intact)', () => {
+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ // Capture the wrapper by re-reading console.log AFTER install.
+ installTimestampedConsole()
+ console.log('[backend] connected → wss://x')
+ const line = spy.mock.calls.at(-1)!.join(' ')
+ expect(line).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3} \[backend\] connected/)
+ expect(line).toContain('[backend] connected') // substring the self-update readiness check scans
+ })
+})
+
+describe('log file cap', () => {
+ let dir: string
+ let file: string
+ let legacy: string
+ const line = (i: number): string => `line-${String(i).padStart(6, '0')} ${'x'.repeat(80)}\n`
+
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'adapter-log-'))
+ file = join(dir, 'machine.log')
+ legacy = join(dir, 'adapter.log')
+ })
+ afterEach(() => rmSync(dir, { recursive: true, force: true }))
+
+ const fill = (bytes: number): number => {
+ let out = ''
+ let i = 0
+ while (out.length < bytes) out += line(i++)
+ writeFileSync(file, out)
+ return i
+ }
+
+ it('leaves a file under the cap alone', () => {
+ fill(2_000)
+ const before = readFileSync(file, 'utf-8')
+ expect(trimLogFile(file, 10_000)).toBe(false)
+ expect(readFileSync(file, 'utf-8')).toBe(before)
+ })
+
+ it('is a no-op when there is no log yet', () => {
+ expect(trimLogFile(join(dir, 'nope.log'))).toBe(false)
+ })
+
+ it('drops the OLDEST half and keeps the newest lines, at a line boundary', () => {
+ const cap = 40_000
+ const written = fill(cap * 2)
+ expect(trimLogFile(file, cap)).toBe(true)
+
+ const after = readFileSync(file, 'utf-8')
+ expect(statSync(file).size).toBeLessThanOrEqual(cap)
+ // Newest line survived, oldest is gone.
+ expect(after).toContain(`line-${String(written - 1).padStart(6, '0')}`)
+ expect(after).not.toContain('line-000000')
+ // First line is the trim marker; the second is a WHOLE line, not a fragment.
+ const lines = after.split('\n')
+ expect(lines[0]).toMatch(/\[log\] trimmed — dropped the oldest \d+ MB \(cap 0 MB\)$/)
+ expect(lines[1]).toMatch(/^line-\d{6} x+$/)
+ })
+
+ it('keeps an O_APPEND writer landing at the end — no sparse hole', () => {
+ // The daemon holds the log as its stdout fd across a trim; this is the property that makes an
+ // in-place rewrite safe (a non-append fd would resume at its old offset and leave NUL bytes).
+ const cap = 40_000
+ fill(cap * 2)
+ const fd = openSync(file, 'a')
+ try {
+ expect(trimLogFile(file, cap)).toBe(true)
+ writeSync(fd, 'after-the-trim\n')
+ } finally {
+ closeSync(fd)
+ }
+ const after = readFileSync(file)
+ expect(after.toString('utf-8').trimEnd().endsWith('after-the-trim')).toBe(true)
+ expect(after.includes(0)).toBe(false)
+ expect(after.length).toBeLessThanOrEqual(cap)
+ })
+
+ it('caps at 10 MB by default', () => {
+ expect(LOG_MAX_BYTES).toBe(10 * 1024 * 1024)
+ })
+
+ it('adopts a legacy log by RENAME, so an open fd keeps writing to the same file', () => {
+ writeFileSync(legacy, 'old-history\n')
+ const inode = statSync(legacy).ino
+ const fd = openSync(legacy, 'a') // stands in for a daemon started before the rename
+ try {
+ adoptLegacyLog(file, legacy)
+ writeSync(fd, 'written-after-rename\n')
+ } finally {
+ closeSync(fd)
+ }
+ expect(existsSync(legacy)).toBe(false)
+ expect(statSync(file).ino).toBe(inode)
+ expect(readFileSync(file, 'utf-8')).toBe('old-history\nwritten-after-rename\n')
+ })
+
+ it('never clobbers an existing log, and shrugs off a missing legacy one', () => {
+ writeFileSync(file, 'current\n')
+ writeFileSync(legacy, 'stale\n')
+ adoptLegacyLog(file, legacy)
+ expect(readFileSync(file, 'utf-8')).toBe('current\n')
+ expect(readFileSync(legacy, 'utf-8')).toBe('stale\n') // left for the user to delete
+
+ rmSync(legacy)
+ expect(() => adoptLegacyLog(file, legacy)).not.toThrow()
+ })
+
+ it('prepareLogFile adopts then trims in one pass', () => {
+ let out = ''
+ while (out.length < 30_000) out += line(out.length)
+ writeFileSync(legacy, out)
+ prepareLogFile(file, legacy, 10_000)
+ expect(existsSync(legacy)).toBe(false)
+ expect(statSync(file).size).toBeLessThanOrEqual(10_000)
+ })
+})
diff --git a/cli/src/lib/log.ts b/cli/src/lib/log.ts
new file mode 100644
index 000000000..19d4d4bfb
--- /dev/null
+++ b/cli/src/lib/log.ts
@@ -0,0 +1,111 @@
+/**
+ * Daemon logging helpers: a wall-clock timestamp prefix on every console line, the log FILE's size
+ * cap, plus small formatters used by the per-step pipeline logs. The timestamp shim is installed
+ * once at daemon boot (`installTimestampedConsole`) — CLI subcommands never call it, so their
+ * terminal output stays clean. It only PREPENDS to each line, so substring log-markers (e.g. the
+ * `[backend] connected` token scanned by the self-update readiness check) stay intact.
+ */
+
+import { closeSync, existsSync, openSync, readSync, renameSync, statSync, writeFileSync } from 'fs'
+
+function pad(n: number, width = 2): string {
+ return String(n).padStart(width, '0')
+}
+
+/** Local wall-clock "YYYY-MM-DD HH:MM:SS.mmm" — unambiguous for a single-user local daemon. */
+export function ts(date: Date = new Date()): string {
+ return (
+ `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
+ `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}.${pad(date.getMilliseconds(), 3)}`
+ )
+}
+
+let installed = false
+
+/** Wrap console.* so every daemon line is timestamped. Idempotent; safe to call more than once. */
+export function installTimestampedConsole(): void {
+ if (installed) return
+ installed = true
+ const levels = ['log', 'warn', 'error', 'info'] as const
+ for (const level of levels) {
+ const original = console[level].bind(console)
+ console[level] = (...args: unknown[]): void => original(ts(), ...args)
+ }
+}
+
+// ── log FILE size cap ────────────────────────────────────────────────────────────────────────────
+// The daemon does not write the log through this process's `fs` calls — it is spawned with the file
+// as its stdout/stderr fd, so nothing in-process sees a line to count. The cap is therefore enforced
+// by whoever is about to open the file (a `join`, an update-restart) plus a timer inside the running
+// daemon.
+
+/** Hard ceiling for the log file. Never exceeded by more than one check interval's worth of output. */
+export const LOG_MAX_BYTES = 10 * 1024 * 1024
+/** How often the running daemon re-checks the size. A `statSync`, so cheap enough to keep tight. */
+export const LOG_CHECK_INTERVAL_MS = 60_000
+
+const mib = (bytes: number): string => (bytes / (1024 * 1024)).toFixed(0)
+
+/**
+ * Trim the log back under `maxBytes` by dropping the OLDEST half, keeping the newest — the recent
+ * lines are the ones worth having when something just broke.
+ *
+ * Rewrites the file in place rather than rotating to a `.1` sibling: the cap is meant to bound what
+ * this daemon costs on disk, and a rotation would make that 2× the number asked for. Safe against
+ * the daemon's inherited fd because that fd is O_APPEND — after the truncate its next write lands at
+ * the new end of file, not at a stale offset (which would leave a multi-MB sparse hole).
+ *
+ * Returns true when it trimmed. Every failure is swallowed: log upkeep must never take the daemon down.
+ */
+export function trimLogFile(file: string, maxBytes = LOG_MAX_BYTES): boolean {
+ let size: number
+ try { size = statSync(file).size } catch { return false } // not created yet
+ if (size <= maxBytes) return false
+ const keep = Math.floor(maxBytes / 2)
+ let fd: number | null = null
+ try {
+ fd = openSync(file, 'r')
+ const buf = Buffer.alloc(keep)
+ const read = readSync(fd, buf, 0, keep, size - keep)
+ let tail = buf.subarray(0, read)
+ // Start at a line boundary so the first surviving line isn't a fragment.
+ const nl = tail.indexOf(0x0a)
+ if (nl >= 0) tail = tail.subarray(nl + 1)
+ const header = `${ts()} [log] trimmed — dropped the oldest ${mib(size - tail.length)} MB (cap ${mib(maxBytes)} MB)\n`
+ writeFileSync(file, Buffer.concat([Buffer.from(header), tail]))
+ return true
+ } catch {
+ return false
+ } finally {
+ if (fd !== null) { try { closeSync(fd) } catch { /* ignore */ } }
+ }
+}
+
+/**
+ * Adopt a log written under an older name. Renaming keeps the INODE, so a daemon still running from
+ * a previous build — holding an fd on the old path — keeps writing into the very same file under its
+ * new name: no lost lines and no orphan left behind. No-op once the new name exists.
+ */
+export function adoptLegacyLog(file: string, legacy: string): void {
+ try {
+ if (existsSync(file) || !existsSync(legacy)) return
+ renameSync(legacy, file)
+ } catch { /* best-effort: a missing legacy log is not worth a failed start */ }
+}
+
+/** Called before the log file is opened for a daemon: adopt an older name, then enforce the cap. */
+export function prepareLogFile(file: string, legacy: string, maxBytes = LOG_MAX_BYTES): void {
+ adoptLegacyLog(file, legacy)
+ trimLogFile(file, maxBytes)
+}
+
+/** Short session id for log lines. */
+export function sid(id: string): string {
+ return id.slice(0, 8)
+}
+
+/** One-line, whitespace-flattened preview of user/assistant text, capped with an ellipsis. */
+export function preview(text: string, max = 60): string {
+ const flat = (text || '').replace(/\s+/g, ' ').trim()
+ return flat.length > max ? `${flat.slice(0, max)}…` : flat
+}
diff --git a/cli/src/lib/normalize.spec.ts b/cli/src/lib/normalize.spec.ts
new file mode 100644
index 000000000..d6e79b38a
--- /dev/null
+++ b/cli/src/lib/normalize.spec.ts
@@ -0,0 +1,148 @@
+import { describe, expect, it } from 'vitest'
+import { lineToEvents, newTurnState, type LiveEvent } from './normalize.js'
+
+const userPrompt = (text: string): string =>
+ JSON.stringify({ type: 'user', message: { role: 'user', content: [{ type: 'text', text }] } })
+
+const assistantText = (text: string, stopReason?: string): string =>
+ JSON.stringify({
+ type: 'assistant',
+ message: { role: 'assistant', content: [{ type: 'text', text }], stop_reason: stopReason ?? null },
+ })
+
+/**
+ * A first attach folds the whole transcript through `lineToEvents` and drops the events, so old turns
+ * do not replay live. That is only safe while the history is complete. When a prompt lands during the
+ * attach, the history ends mid-turn and the live turn's `turn_started` is in the part being dropped —
+ * the commander mirror then never opens the turn and its close yields no recap. `cli.ts` recovers by
+ * replaying the last `turn_started` when the folded state says a turn is still open, which needs both
+ * halves of that contract to hold.
+ */
+describe('folding a transcript that ends mid-turn', () => {
+ it('leaves the turn open and the last turn_started recoverable', () => {
+ const state = newTurnState()
+ const events: LiveEvent[] = []
+ for (const line of [
+ userPrompt('first question'),
+ assistantText('first answer', 'end_turn'),
+ userPrompt('second question'), // still running when the attach folded the file
+ assistantText('partial answer'), // no terminal stop reason yet
+ ]) {
+ events.push(...lineToEvents(line, state))
+ }
+
+ expect(state.turnOpen).toBe(true)
+ const opened = events.findLast((event) => event.type === 'turn_started')
+ expect(opened).toEqual({ type: 'turn_started', payload: { userMessage: 'second question' } })
+ })
+
+ it('leaves no open turn when the history is complete', () => {
+ const state = newTurnState()
+ const events: LiveEvent[] = []
+ for (const line of [userPrompt('a question'), assistantText('an answer', 'end_turn')]) {
+ events.push(...lineToEvents(line, state))
+ }
+
+ // Nothing to recover: replaying here would resurrect a finished turn as a live one.
+ expect(state.turnOpen).toBe(false)
+ expect(events.map((event) => event.type)).toEqual(['turn_started', 'text_delta', 'turn_ended'])
+ })
+
+ it('keeps the turn open while a tool call is unresolved', () => {
+ // A turn parked in a tool has no terminal stop reason either, and it is just as live.
+ const state = newTurnState()
+ for (const line of [
+ userPrompt('run something'),
+ JSON.stringify({
+ type: 'assistant',
+ message: {
+ role: 'assistant',
+ content: [{ type: 'tool_use', id: 'tool-1', name: 'Bash', input: { command: 'ls' } }],
+ stop_reason: 'tool_use',
+ },
+ }),
+ ]) {
+ lineToEvents(line, state)
+ }
+
+ expect(state.turnOpen).toBe(true)
+ expect(state.pendingTools.size).toBe(1)
+ })
+})
+
+/**
+ * Cancelling a turn (device Stop, web C-c, or ESC in the terminal) leaves a synthetic user line in the
+ * transcript. It carries no flag, so only its text tells it apart from a typed prompt — and reading it as
+ * one opened a fresh turn the moment a turn was killed. The device then showed "Working" and counted
+ * seconds forever, because no assistant would ever answer that turn and no recap would ever close it.
+ */
+describe('an interrupted turn', () => {
+ const INTERRUPTS = ['[Request interrupted by user]', '[Request interrupted by user for tool use]']
+
+ for (const marker of INTERRUPTS) {
+ it(`closes the turn instead of opening one: ${marker}`, () => {
+ const state = newTurnState()
+ const events: LiveEvent[] = []
+ for (const line of [userPrompt('do a long thing'), assistantText('starting'), userPrompt(marker)]) {
+ events.push(...lineToEvents(line, state))
+ }
+
+ expect(state.turnOpen).toBe(false)
+ expect(events.filter((event) => event.type === 'turn_started')).toHaveLength(1)
+ // `aborted` is what tells the mirror to clear the tile WITHOUT a recap or a done beep.
+ expect(events.at(-1)).toEqual({ type: 'turn_ended', payload: { aborted: true } })
+ })
+ }
+
+ it('emits nothing when no turn is open', () => {
+ // Folding history on attach replays interrupts from turns that ended long ago; none of them may
+ // close a turn that a later line opened, nor synthesize an event out of nothing.
+ const state = newTurnState()
+ expect(lineToEvents(userPrompt(INTERRUPTS[0]), state)).toEqual([])
+ expect(state.turnOpen).toBe(false)
+ })
+
+ it('still treats a real prompt that only mentions an interrupt as a prompt', () => {
+ const state = newTurnState()
+ const events = lineToEvents(userPrompt('why do I keep seeing [Request interrupted by user]?'), state)
+ expect(events[0]).toMatchObject({ type: 'turn_started' })
+ expect(state.turnOpen).toBe(true)
+ })
+})
+
+// Regression: a `/loop` fires every N minutes and each iteration is written as an isMeta user line.
+// Blanket-suppressing isMeta made every iteration after the first invisible on the device — the loop ran
+// fine in the terminal, produced no turn_started, and so produced no recap. Shapes taken verbatim from a
+// real ~/.claude JSONL.
+describe('a /loop iteration', () => {
+ const line = (o: Record<string, unknown>) => JSON.stringify(o)
+
+ it('opens a turn: it is a real prompt the system submitted on the user behalf', () => {
+ const st = newTurnState()
+ const ev = lineToEvents(line({
+ type: 'user', isMeta: true, promptSource: 'system', queuePriority: 'later',
+ message: { role: 'user', content: 'Báo giá Bitcoin' },
+ }), st)
+ expect(ev.map((e) => e.type)).toContain('turn_started')
+ expect(st.turnOpen).toBe(true)
+ })
+
+ it('still suppresses real bookkeeping meta — a slash command expansion has no promptSource', () => {
+ const st = newTurnState()
+ const ev = lineToEvents(line({
+ type: 'user', isMeta: true, userType: 'external', entrypoint: 'cli',
+ message: { role: 'user', content: [{ type: 'text', text: '# /loop — schedule a recurring prompt' }] },
+ }), st)
+ expect(ev).toEqual([])
+ expect(st.turnOpen).toBe(false)
+ })
+
+ it('still suppresses the compact summary', () => {
+ const st = newTurnState()
+ expect(lineToEvents(line({
+ type: 'user', isCompactSummary: true, promptSource: 'system',
+ message: { role: 'user', content: 'This session is being continued…' },
+ }), st)).toEqual([])
+ expect(st.turnOpen).toBe(false)
+ })
+})
diff --git a/cli/src/lib/normalize.test.ts b/cli/src/lib/normalize.test.ts
new file mode 100644
index 000000000..54c868646
--- /dev/null
+++ b/cli/src/lib/normalize.test.ts
@@ -0,0 +1,207 @@
+import { describe, it, expect } from 'vitest'
+import {
+ lastTurnTextFromRawLines,
+ lineToEvents,
+ messagesToEvents,
+ newTurnState,
+ windowRawLines,
+} from './normalize.js'
+
+// Build a synthetic transcript: 3 turns, each = [user prompt, assistant tool_use, user tool_result].
+// uuids: u1 a1 r1 | u2 a2 r2 | u3 a3 r3 (turn starts at line indices 0, 3, 6).
+const line = (o: Record<string, unknown>) => JSON.stringify(o)
+const userPrompt = (uuid: string, text: string) =>
+ line({ type: 'user', uuid, message: { role: 'user', content: [{ type: 'text', text }] } })
+const asstToolUse = (uuid: string, id: string, name: string) =>
+ line({ type: 'assistant', uuid, message: { role: 'assistant', content: [{ type: 'tool_use', id, name, input: {} }] } })
+const asstText = (uuid: string, text: string) =>
+ line({ type: 'assistant', uuid, message: { role: 'assistant', content: [{ type: 'text', text }] } })
+const userToolResult = (uuid: string, toolUseId: string) =>
+ line({ type: 'user', uuid, message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: toolUseId, content: 'ok' }] } })
+
+const LINES = [
+ userPrompt('u1', 'hello 1'), asstToolUse('a1', 't1', 'Bash'), userToolResult('r1', 't1'),
+ userPrompt('u2', 'hello 2'), asstToolUse('a2', 't2', 'Read'), userToolResult('r2', 't2'),
+ userPrompt('u3', 'hello 3'), asstToolUse('a3', 't3', 'Grep'), userToolResult('r3', 't3'),
+]
+
+describe('windowRawLines', () => {
+ it('newest window is turn-snapped, reports hasMore + a real oldestCursor', () => {
+ const w = windowRawLines(LINES, { limit: 2 })
+ // limit=2 lands mid-turn (index 7); snaps back to the turn start u3 (index 6).
+ expect(w.window).toEqual(LINES.slice(6, 9))
+ expect(w.hasMore).toBe(true)
+ expect(w.oldestCursor).toBe('u3')
+ expect(w.staleCursor).toBeUndefined()
+
+ // The window is self-contained: the tool_use precedes its tool_result, so messagesToEvents'
+ // stateful tool-name map resolves — the tool card renders with its real name.
+ const events = messagesToEvents(w.window)
+ expect(events.some((e) => e.type === 'user_message' && (e.payload as { content: string }).content === 'hello 3')).toBe(true)
+ expect(events.some((e) => e.type === 'tool_start' && (e.payload as { tool: string }).tool === 'Grep')).toBe(true)
+ })
+
+ it('pages backward with before=oldestCursor until hasMore=false', () => {
+ const p1 = windowRawLines(LINES, { limit: 2, before: 'u3' })
+ expect(p1.window).toEqual(LINES.slice(3, 6)) // turn 2
+ expect(p1.hasMore).toBe(true)
+ expect(p1.oldestCursor).toBe('u2')
+
+ const p2 = windowRawLines(LINES, { limit: 2, before: 'u2' })
+ expect(p2.window).toEqual(LINES.slice(0, 3)) // turn 1 — oldest
+ expect(p2.hasMore).toBe(false)
+ expect(p2.oldestCursor).toBe('u1')
+ })
+
+ it('flags a stale cursor (empty window) when before is not in the file', () => {
+ const w = windowRawLines(LINES, { limit: 2, before: 'does-not-exist' })
+ expect(w.staleCursor).toBe(true)
+ expect(w.window).toEqual([])
+ expect(w.hasMore).toBe(false)
+ })
+
+ it('returns everything when the window is larger than the transcript', () => {
+ const w = windowRawLines(LINES, { limit: 100 })
+ expect(w.window).toEqual(LINES)
+ expect(w.hasMore).toBe(false)
+ expect(w.oldestCursor).toBe('u1')
+ })
+})
+
+describe('lastTurnTextFromRawLines', () => {
+ it('extracts the last real user ask and assistant text from session JSONL', () => {
+ const lines = [
+ userPrompt('u1', 'old ask'),
+ asstText('a1', 'old answer'),
+ userPrompt('u2', 'current ask'),
+ asstToolUse('a2', 't2', 'Bash'),
+ userToolResult('r2', 't2'),
+ asstText('a3', 'first answer part'),
+ asstText('a4', 'second answer part'),
+ ]
+
+ expect(lastTurnTextFromRawLines(lines)).toEqual({
+ userMessage: 'current ask',
+ assistantText: 'first answer part\n\nsecond answer part',
+ })
+ })
+
+ it('skips compact metadata, platform prompts, and tool_result user echoes', () => {
+ const lines = [
+ line({ type: 'system', subtype: 'compact_boundary', compactMetadata: { trigger: 'auto' } }),
+ line({ type: 'user', uuid: 'meta', isCompactSummary: true, message: { role: 'user', content: [{ type: 'text', text: 'summary' }] } }),
+ userPrompt('u1', '<!-- CONTEXT SUMMARY -->\nplatform prompt'),
+ userPrompt('u2', 'real ask'),
+ userToolResult('r2', 'tool'),
+ asstText('a2', 'real answer'),
+ ]
+
+ expect(lastTurnTextFromRawLines(lines)).toEqual({
+ userMessage: 'real ask',
+ assistantText: 'real answer',
+ })
+ })
+})
+
+describe('Claude local command records', () => {
+ const modelOutput = userPrompt(
+ 'local-model',
+ '<local-command-stdout>Set model to \u001b[1mOpus 4.8\u001b[22m and saved as your default for new sessions</local-command-stdout>',
+ )
+ const effortOutput = userPrompt(
+ 'local-effort',
+ '<local-command-stdout>Set effort level to high (saved as your default for new sessions)</local-command-stdout>',
+ )
+
+ it('does not render local command stdout during replay', () => {
+ expect(messagesToEvents([modelOutput, effortOutput])).toEqual([
+ { type: 'done', payload: { result: 'success' } },
+ ])
+ })
+
+ it('does not open a live turn for local command stdout', () => {
+ const state = newTurnState()
+
+ expect(lineToEvents(modelOutput, state)).toEqual([])
+ expect(lineToEvents(effortOutput, state)).toEqual([])
+ expect(state.turnOpen).toBe(false)
+ })
+})
+
+describe('turn close on terminal stop reasons', () => {
+ const asstStop = (uuid: string, text: string, stopReason: string) =>
+ line({ type: 'assistant', uuid, message: { role: 'assistant', content: [{ type: 'text', text }], stop_reason: stopReason } })
+
+ const openTurn = () => {
+ const state = newTurnState()
+ lineToEvents(userPrompt('u1', 'hello'), state)
+ expect(state.turnOpen).toBe(true)
+ return state
+ }
+
+ it('closes the turn on max_tokens and refusal (not just end_turn/stop_sequence)', () => {
+ for (const reason of ['end_turn', 'stop_sequence', 'max_tokens', 'refusal']) {
+ const state = openTurn()
+ const events = lineToEvents(asstStop('a1', 'partial', reason), state)
+ expect(events).toContainEqual({ type: 'turn_ended', payload: {} })
+ expect(state.turnOpen).toBe(false)
+ }
+ })
+
+ it('does NOT close on tool_use or pause_turn (turn continues)', () => {
+ for (const reason of ['tool_use', 'pause_turn']) {
+ const state = openTurn()
+ const events = lineToEvents(asstStop('a1', 'thinking', reason), state)
+ expect(events).not.toContainEqual({ type: 'turn_ended', payload: {} })
+ expect(state.turnOpen).toBe(true)
+ }
+ })
+
+ it('does NOT close on a terminal stop reason while a tool is still pending', () => {
+ const state = openTurn()
+ lineToEvents(asstToolUse('a1', 't1', 'Bash'), state) // adds t1 to pendingTools
+ const events = lineToEvents(asstStop('a2', 'done', 'end_turn'), state)
+ expect(events).not.toContainEqual({ type: 'turn_ended', payload: {} })
+ expect(state.turnOpen).toBe(true)
+ })
+})
+
+describe('slash-command prompts', () => {
+ // Claude Code records a typed command ONLY as these tags; the expansion it sends to the model is a
+ // separate `isMeta` line we suppress. Before the fix both normalized to "" and NO turn ever opened,
+ // so the device's `/goal <text>` (deviceWs sends exactly this) tripped the submit-verify retries and
+ // surfaced "The agent did not accept the message" even though claude had run the command fine.
+ const goalCmd = userPrompt(
+ 'c1',
+ '<command-name>/goal</command-name>\n <command-message>goal</command-message>\n <command-args>ship the release</command-args>',
+ )
+ const goalStdout = userPrompt('c2', '<local-command-stdout>Goal set: ship the release</local-command-stdout>')
+ const modelCmd = userPrompt(
+ 'c3',
+ '<command-name>/model</command-name>\n <command-message>model</command-message>\n <command-args>haiku</command-args>',
+ )
+
+ it('opens a live turn with the command text verbatim (matches the injected fingerprint)', () => {
+ const state = newTurnState()
+
+ expect(lineToEvents(goalCmd, state)).toEqual([
+ { type: 'turn_started', payload: { userMessage: '/goal ship the release' } },
+ ])
+ expect(state.turnOpen).toBe(true)
+ expect(lineToEvents(goalStdout, state)).toEqual([]) // the echo must not re-open a turn
+ })
+
+ it('keeps local-only TUI commands silent', () => {
+ const state = newTurnState()
+
+ expect(lineToEvents(modelCmd, state)).toEqual([])
+ expect(state.turnOpen).toBe(false)
+ })
+
+ it('leads the recap with the command text', () => {
+ expect(lastTurnTextFromRawLines([goalCmd, goalStdout, asstText('a1', 'done')])).toEqual({
+ userMessage: '/goal ship the release',
+ assistantText: 'done',
+ })
+ })
+})
diff --git a/cli/src/lib/normalize.ts b/cli/src/lib/normalize.ts
new file mode 100644
index 000000000..6ce98f239
--- /dev/null
+++ b/cli/src/lib/normalize.ts
@@ -0,0 +1,798 @@
+/**
+ * Claude-Code JSONL → web ServerEvent normalizer.
+ *
+ * Self-contained port of the hosted runtime’s replay normalizer
+ * (`the hosted runtime`: transformCCMessageToSessionMessage,
+ * sessionMessagesToEvents, stripContextSummary/stripSystemBlocks + tool-summary)
+ * — this package has no dependency outside itself.
+ *
+ * Two entry points:
+ * - messagesToEvents(rawLines) → full SessionEvent[] replay for `session_get`.
+ * - lineToEvents(rawLine, state) → incremental events for live tailing, PLUS a derived
+ * turn lifecycle (turn_started / turn_ended) so a prompt typed directly in the terminal
+ * renders identically to one sent from the web (mirror-all).
+ */
+
+// ── Event shapes (match the server’s SessionEvent contract SessionEvent + live turn frames) ──────
+
+export interface SubagentSummary {
+ agentId?: string
+ agentType?: string
+ totalTokens?: number
+ totalDurationMs?: number
+ totalToolUseCount?: number
+}
+
+export type SessionEvent =
+ | { type: 'user_message'; payload: { content: string; images?: Array<{ media_type: string; data: string }> } }
+ | { type: 'thinking_delta'; payload: { content: string; thinkingId?: string } }
+ | { type: 'thinking_title'; payload: { thinkingId?: string; title: string } }
+ | { type: 'text_delta'; payload: { content: string } }
+ | { type: 'tool_start'; payload: { id: string; tool: string; input: unknown; parentToolUseId?: string } }
+ | { type: 'tool_end'; payload: { id: string; tool: string; output: string; isError: boolean; summary: string; parentToolUseId?: string; subagent?: SubagentSummary; durationSeconds?: number } }
+ | { type: 'context_compact'; payload: { message: string; trigger?: string } }
+ | { type: 'done'; payload: { result: string } }
+
+/** Live-stream events: replay events + the derived turn lifecycle. */
+export type LiveEvent =
+ | SessionEvent
+ | { type: 'turn_started'; payload: { userMessage: string } }
+ | { type: 'turn_ended'; payload: { aborted?: true } } // aborted = killed by an interrupt, no recap
+ // An ASYNC sub-agent actually finished. `id` is the spawning tool_use id, so it pairs with the
+ // `tool_start`/`tool_end` of the same sub-agent (see taskNotificationEvent).
+ | { type: 'subagent_finished'; payload: { id: string; status: string; summary?: string } }
+
+export interface LastTurnText {
+ userMessage: string
+ assistantText: string
+}
+
+interface RawContentBlock {
+ type: 'text' | 'tool_use' | 'tool_result' | 'thinking' | 'image'
+ text?: string
+ thinking?: string
+ id?: string
+ name?: string
+ input?: unknown
+ tool_use_id?: string
+ content?: string | Array<{ type: string; text?: string }>
+ is_error?: boolean
+ source?: { type: string; media_type: string; data: string }
+}
+
+interface NormalizedMessage {
+ type: 'user' | 'assistant'
+ message?: { role: 'user' | 'assistant'; content: RawContentBlock[] }
+ toolUseResult?: SubagentSummary & { status?: string; durationSeconds?: number }
+ /** Raw Anthropic stop_reason from the assistant line (drives turn_ended). */
+ stopReason?: string | null
+}
+
+const MAX_OUTPUT = 2000
+const MAX_THINKING = 500
+const MAX_DIFF_SIDE = 1500
+const PREVIEW_LINES = 8
+
+// ── Text cleanup (ported verbatim) ────────────────────────────────────────────────────────────────
+
+/** Strip the compaction-injected context summary; null if the whole message was summary. */
+export function stripContextSummary(text: string): string | null {
+ const endMarker = '<!-- END CONTEXT SUMMARY -->'
+ const idx = text.indexOf(endMarker)
+ if (idx === -1) return text
+ let remaining = text.slice(idx + endMarker.length)
+ remaining = remaining.replace(/^\s*---\s*Now,?\s*continuing.*?:\s*/is, '')
+ remaining = remaining.trim()
+ return remaining || null
+}
+
+/** Strip system-injected blocks not meant for UI display. */
+export function stripSystemBlocks(text: string): string {
+ return text
+ .replace(/<task-notification>[\s\S]*?<\/task-notification>\s*/g, '')
+ .replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g, '')
+ .replace(/<goal-context>[\s\S]*?<\/goal-context>\s*/g, '')
+ .replace(/<dev-server-context>[\s\S]*?<\/dev-server-context>\s*/g, '')
+ .replace(/<available-deferred-tools>[\s\S]*?<\/available-deferred-tools>\s*/g, '')
+ .replace(/<local-command-caveat>[\s\S]*?<\/local-command-caveat>\s*/g, '')
+ .replace(/<command-name>[\s\S]*?<\/command-name>\s*/g, '')
+ .replace(/<command-message>[\s\S]*?<\/command-message>\s*/g, '')
+ .replace(/<command-args>[\s\S]*?<\/command-args>\s*/g, '')
+ .replace(/<local-command-stdout>[\s\S]*?<\/local-command-stdout>\s*/g, '')
+ .replace(/Read the output file to retrieve the result:[^\n]*/g, '')
+ .trim()
+}
+
+// Built-in CLI commands that only drive the local TUI and never dispatch an agent turn. Surfacing
+// them as a user prompt would open a turn nothing ever closes (device tile stuck busy), so they stay
+// invisible — same as before. Anything else (a custom `~/.claude/commands/*.md`, `/goal`, `/review`,
+// a plugin skill) DOES run a turn and must be visible.
+const LOCAL_ONLY_COMMANDS = new Set([
+ 'add-dir', 'agents', 'bug', 'clear', 'compact', 'config', 'context', 'copy', 'cost', 'desktop',
+ 'doctor', 'effort', 'exit', 'export', 'help', 'hooks', 'ide', 'login', 'logout', 'mcp', 'memory',
+ 'model', 'output-style', 'permissions', 'privacy-settings', 'quit', 'release-notes',
+ 'reload-plugins', 'resume', 'skills', 'statusline', 'status', 'terminal-setup', 'todos',
+ 'upgrade', 'vim',
+])
+
+/**
+ * `<command-name>/goal</command-name>…<command-args>x</command-args>` → `/goal x`.
+ *
+ * Claude Code records a slash command ONLY as these tags (the expansion it actually sends to the
+ * model is written as a separate `isMeta` line, which we suppress). `stripSystemBlocks` erases the
+ * tags, so without this the whole line normalizes to "" → `realUserText` returns null → NO
+ * `turn_started` is ever emitted for a command prompt. That broke the device's goal mode: the
+ * injected `/goal <text>` ran fine in the terminal, but `SessionInputController` never saw the turn
+ * open and reported "The agent did not accept the message" after its submit retries — and the recap
+ * had no user message to lead with.
+ */
+function commandPromptText(text: string): string | null {
+ const name = text.match(/<command-name>\s*([^<]*?)\s*<\/command-name>/)?.[1]
+ if (!name) return null
+ const bare = name.replace(/^\//, '').trim()
+ if (!bare || LOCAL_ONLY_COMMANDS.has(bare.toLowerCase())) return null
+ const args = text.match(/<command-args>([\s\S]*?)<\/command-args>/)?.[1]?.trim() ?? ''
+ return args ? `/${bare} ${args}` : `/${bare}`
+}
+
+/** Short title heuristic for a thinking block (first 3-8 words of the first line). */
+function extractThinkingTitle(thinking: string): string | null {
+ const trimmed = thinking.trim()
+ if (!trimmed || trimmed.length < 10) return null
+ const firstLine = trimmed.split('\n')[0].replace(/^[\s#*\->]+/, '').trim()
+ if (!firstLine) return null
+ const words = firstLine.split(/\s+/).slice(0, 8)
+ if (words.length < 2) return null
+ let title = words.join(' ').replace(/[.,:;!?]+$/, '')
+ if (title.length > 60) title = title.slice(0, 57) + '...'
+ return title
+}
+
+/** The short ⎿ label shown after a tool finishes (e.g. "Read 247 lines"). */
+function computeToolSummary(toolName: string, rawOutput: string, isError: boolean): string {
+ if (isError) return rawOutput.split('\n')[0]?.slice(0, 80) || 'Error'
+ switch (toolName) {
+ case 'Bash': {
+ const match = rawOutput.match(/^Exit code (\d+)/)
+ return match ? `Exit ${match[1]}` : 'Done'
+ }
+ case 'Read': {
+ const lineCount = (rawOutput.match(/^\s*\d+→/gm) || []).length
+ return lineCount > 0 ? `Read ${lineCount} lines` : 'Read'
+ }
+ case 'Write':
+ case 'WriteFile':
+ return rawOutput.includes('successfully') ? 'Written' : rawOutput.slice(0, 60)
+ case 'Edit':
+ case 'EditFile':
+ return rawOutput.includes('successfully') ? 'Updated' : rawOutput.slice(0, 60)
+ case 'Glob': {
+ const count = rawOutput.trim() ? rawOutput.trim().split('\n').length : 0
+ return `${count} file${count !== 1 ? 's' : ''}`
+ }
+ case 'Grep': {
+ const count = rawOutput.trim() ? rawOutput.trim().split('\n').length : 0
+ return `${count} match${count !== 1 ? 'es' : ''}`
+ }
+ case 'WebFetch':
+ case 'WebSearch':
+ return 'Fetched'
+ case 'TodoRead':
+ case 'TodoWrite':
+ return 'Done'
+ default:
+ return rawOutput.split('\n')[0]?.slice(0, 80) || 'Done'
+ }
+}
+
+// ── Raw JSONL line → normalized message (port of transformCCMessageToSessionMessage) ─────────────
+
+function smartWriteInput(input: Record<string, unknown>): Record<string, unknown> {
+ const raw = input.content as string
+ const lines = raw.split('\n')
+ const preview = lines.slice(0, PREVIEW_LINES).join('\n')
+ return {
+ ...input,
+ content: undefined,
+ content_stats: {
+ lines: lines.length,
+ chars: raw.length,
+ preview: preview + (lines.length > PREVIEW_LINES ? '\n…' : ''),
+ },
+ }
+}
+
+function smartEditInput(input: Record<string, unknown>): Record<string, unknown> {
+ const truncSide = (s: unknown): unknown => {
+ if (typeof s !== 'string') return s
+ if (s.length <= MAX_DIFF_SIDE) return s
+ const half = Math.floor(MAX_DIFF_SIDE / 2)
+ return s.slice(0, half) + '\n…\n' + s.slice(s.length - half)
+ }
+ return { ...input, old_string: truncSide(input.old_string), new_string: truncSide(input.new_string) }
+}
+
+function mapContentItem(item: unknown): RawContentBlock {
+ const c = (item ?? {}) as Record<string, unknown> // a null content block must not throw on `.type`
+ const type = (c.type || 'text') as RawContentBlock['type']
+
+ if (type === 'image') {
+ return { type: 'image', source: c.source as RawContentBlock['source'] }
+ }
+
+ let resultContent = c.content as RawContentBlock['content']
+ if (type === 'tool_result' && typeof resultContent === 'string' && resultContent.length > MAX_OUTPUT) {
+ resultContent = resultContent.slice(0, MAX_OUTPUT) + '\n…[truncated]'
+ }
+
+ let toolInput = c.input as Record<string, unknown> | undefined
+ const toolName = c.name as string | undefined
+ if (type === 'tool_use' && toolInput) {
+ if ((toolName === 'Write' || toolName === 'WriteFile') && typeof toolInput.content === 'string' && toolInput.content.length > 500) {
+ toolInput = smartWriteInput(toolInput)
+ } else if (
+ (toolName === 'Edit' || toolName === 'EditFile') &&
+ (((toolInput.old_string as string)?.length ?? 0) > MAX_DIFF_SIDE || ((toolInput.new_string as string)?.length ?? 0) > MAX_DIFF_SIDE)
+ ) {
+ toolInput = smartEditInput(toolInput)
+ }
+ }
+
+ return {
+ type,
+ text: c.text as string | undefined,
+ thinking: c.thinking as string | undefined,
+ id: c.id as string | undefined,
+ name: toolName,
+ input: toolInput,
+ tool_use_id: c.tool_use_id as string | undefined,
+ content: resultContent,
+ is_error: c.is_error as boolean | undefined,
+ }
+}
+
+/** Parse one raw JSONL entry into a normalized user/assistant message (null for other types). */
+export function transformLine(rawMessage: Record<string, unknown>): NormalizedMessage | null {
+ const type = rawMessage.type as string
+ if (type !== 'user' && type !== 'assistant') return null
+
+ const messageObj = rawMessage.message as Record<string, unknown> | undefined
+ let messageContent: RawContentBlock[] | undefined
+
+ if (messageObj) {
+ const role = messageObj.role as string
+ const content = messageObj.content
+ if (role === 'user' || role === 'assistant') {
+ if (typeof content === 'string') {
+ messageContent = [{ type: 'text', text: content }]
+ } else if (Array.isArray(content)) {
+ messageContent = content.length > 0 ? content.map(mapContentItem) : [{ type: 'text', text: '' }]
+ } else if (content === null || content === undefined) {
+ messageContent = [{ type: 'text', text: '' }]
+ }
+ }
+ } else if (type === 'user') {
+ const directContent = rawMessage.content
+ if (typeof directContent === 'string') {
+ messageContent = [{ type: 'text', text: directContent }]
+ } else if (Array.isArray(directContent)) {
+ messageContent = directContent.map(mapContentItem)
+ }
+ }
+
+ let toolUseResult: NormalizedMessage['toolUseResult']
+ if (rawMessage.tool_use_result || rawMessage.toolUseResult) {
+ const tr = (rawMessage.tool_use_result || rawMessage.toolUseResult) as Record<string, unknown>
+ toolUseResult = {
+ status: (tr.status || 'complete') as string,
+ agentId: (tr.agentId ?? tr.agent_id) as string | undefined,
+ agentType: (tr.agentType ?? tr.agent_type) as string | undefined,
+ totalTokens: tr.totalTokens as number | undefined,
+ totalDurationMs: tr.totalDurationMs as number | undefined,
+ totalToolUseCount: tr.totalToolUseCount as number | undefined,
+ // WebSearch carries its search time here (the CLI's "Did 1 search in Ns" line).
+ durationSeconds: typeof tr.durationSeconds === 'number' ? tr.durationSeconds : undefined,
+ }
+ }
+
+ const role = (messageObj?.role || (type === 'user' ? 'user' : 'assistant')) as 'user' | 'assistant'
+
+ if (role === 'user' && messageContent) {
+ for (const block of messageContent) {
+ if (block.type !== 'text' || !block.text) continue
+ // A typed slash command survives as `/name args`; everything else is stripped as before.
+ block.text = commandPromptText(block.text) ?? stripSystemBlocks(block.text)
+ }
+ }
+
+ if (messageContent === undefined) messageContent = [{ type: 'text', text: '' }]
+
+ return {
+ type: type as 'user' | 'assistant',
+ message: { role, content: messageContent },
+ toolUseResult,
+ stopReason: (messageObj?.stop_reason as string | null | undefined) ?? null,
+ }
+}
+
+// ── Shared per-message event emission ─────────────────────────────────────────────────────────────
+
+// Auto-fix / platform prompts filtered from replay (sent by the platform, not the user).
+const SYSTEM_PROMPT_PATTERNS = [
+ 'The dev server is running but the app has an error:',
+ 'Please fix this code issue. Check the page component, routing, and any compile errors.',
+ '<!-- CONTEXT SUMMARY',
+ 'This session is being continued from a previous conversation',
+ '<local-command-stdout>Compacted',
+]
+
+function isSystemPrompt(content: RawContentBlock[]): boolean {
+ const text = content.filter((c) => c.type === 'text' && c.text).map((c) => c.text!).join('')
+ return SYSTEM_PROMPT_PATTERNS.some((p) => text.includes(p))
+}
+
+/** A REAL user prompt (not a tool_result echo, not a platform prompt). Returns the cleaned text or null. */
+/**
+ * An ESC interrupt (terminal, or a Stop from the web/device) is written to the transcript as a plain user
+ * line — `type:'user'`, `userType:'external'`, no `isMeta`, no flag of ANY kind — so its text is the only
+ * thing distinguishing it from something the user typed. Treating it as a prompt opened a brand-new turn at
+ * the instant a turn was cancelled, and the device then counted seconds forever on a turn no assistant
+ * would ever answer. Covers the `for tool use` variant too. A user who literally types this loses one turn
+ * card; that is the cheaper failure.
+ */
+const INTERRUPT_MARKER = /^\[Request interrupted by user[^\]]*\]$/
+
+/** The user-authored text of a line, before interrupt markers are judged. null = not a user prompt. */
+function userTextRaw(msg: NormalizedMessage): string | null {
+ if (msg.type !== 'user' || !msg.message) return null
+ const content = msg.message.content
+ if (isSystemPrompt(content)) return null
+ if (content.some((c) => c.type === 'tool_result')) return null
+ const parts: string[] = []
+ for (const block of content) {
+ if (block.type !== 'text' || !block.text) continue
+ let cleaned = stripContextSummary(block.text)
+ if (cleaned) cleaned = stripSystemBlocks(cleaned)
+ if (cleaned && !cleaned.match(/^\[Image: original \d+x\d+/)) parts.push(cleaned)
+ }
+ const text = parts.join('\n')
+ return text || null
+}
+
+/**
+ * An async sub-agent's REAL completion. Claude's `Agent` tool returns in milliseconds with
+ * "Async agent launched successfully." — that `tool_result` is a launch ack, not a result, and taking it
+ * for one made the device tick a sub-agent off the moment it started. The actual finish arrives much
+ * later as a `type:"user"` record the CLI injects into the parent transcript:
+ *
+ * <task-notification><task-id>…</task-id><tool-use-id>toolu_018wkW…</tool-use-id>
+ * <output-file>…</output-file><status>completed</status><summary>Agent "…" finished…
+ *
+ * `stripSystemBlocks` erases the whole block, so it correctly starts no turn — but that also meant the
+ * only signal a sub-agent had finished was being thrown away. Read it here, keyed by tool-use-id.
+ *
+ * Takes the RAW record, not a NormalizedMessage: `transformLine` already ran the strip (line ~304), so by
+ * then the text block is empty and there is nothing left to parse.
+ */
+function taskNotificationEvent(raw: Record<string, unknown>): LiveEvent | null {
+ if (raw.type !== 'user') return null
+ const content = (raw.message as { content?: unknown } | undefined)?.content ?? raw.content
+ let text = ''
+ if (typeof content === 'string') text = content
+ else if (Array.isArray(content)) {
+ text = content
+ .map((b) => (typeof b === 'string' ? b : (b as RawContentBlock)?.type === 'text' ? String((b as RawContentBlock).text ?? '') : ''))
+ .join('\n')
+ }
+ if (!text.includes('<task-notification>')) return null
+ const id = text.match(/<tool-use-id>([^<]+)<\/tool-use-id>/)?.[1]?.trim()
+ if (!id) return null
+ const status = text.match(/<status>([^<]+)<\/status>/)?.[1]?.trim() || 'completed'
+ const summary = text.match(/<summary>([\s\S]*?)(?:<\/summary>|$)/)?.[1]?.trim()
+ return { type: 'subagent_finished', payload: { id, status, ...(summary ? { summary } : {}) } }
+}
+
+/** True for the synthetic line an interrupt leaves behind. It ends a turn; it never starts one. */
+function isInterruptLine(msg: NormalizedMessage): boolean {
+ const text = userTextRaw(msg)
+ return text !== null && INTERRUPT_MARKER.test(text)
+}
+
+// Every caller of this asks "is this a prompt the user made?" — turn slicing for replay and the recap's
+// user-message source as well as the live turn lifecycle — and an interrupt marker is not one of those.
+function realUserText(msg: NormalizedMessage): string | null {
+ const text = userTextRaw(msg)
+ if (text === null || INTERRUPT_MARKER.test(text)) return null
+ return text
+}
+
+/**
+ * Extract the last real user prompt and the assistant text that followed it from
+ * raw Claude JSONL. This is the recap source of truth: it matches replay parsing
+ * rules, skips tool_result echoes / platform prompts / compact metadata, and only
+ * summarizes assistant text blocks.
+ */
+export function lastTurnTextFromRawLines(rawLines: string[]): LastTurnText | null {
+ let userMessage = ''
+ let assistantParts: string[] = []
+
+ for (const line of rawLines) {
+ if (!line.trim()) continue
+ let raw: Record<string, unknown>
+ try { raw = JSON.parse(line) as Record<string, unknown> } catch { continue }
+ const compact = compactEventFromRaw(raw)
+ if (compact !== undefined) continue
+
+ const msg = transformLine(raw)
+ if (!msg?.message) continue
+
+ const userText = realUserText(msg)
+ if (userText !== null) {
+ userMessage = userText
+ assistantParts = []
+ continue
+ }
+
+ if (msg.type !== 'assistant') continue
+ const text = msg.message.content
+ .filter((c) => c.type === 'text' && c.text)
+ .map((c) => c.text!)
+ .join('')
+ .trim()
+ if (text) assistantParts.push(text)
+ }
+
+ const assistantText = assistantParts.join('\n\n').trim()
+ return assistantText ? { userMessage, assistantText } : null
+}
+
+/** Aggregates computed from a sub-agent's OWN transcript. Async/background agents never get totals
+ * in the launcher's toolUseResult (it only records `{isAsync, status:'async_launched', agentId}` at
+ * launch) — the real numbers live in `<session>/subagents/agent-<id>.jsonl`. totalTokens mirrors the
+ * CLI's definition: input + output + cache_read + cache_creation summed over assistant turns. */
+export function subagentStatsFromRawLines(rawLines: string[]): { totalToolUseCount: number; totalDurationMs?: number; totalTokens?: number } {
+ let toolCount = 0
+ let tokens = 0
+ let first: number | undefined
+ let last: number | undefined
+ for (const line of rawLines) {
+ if (!line.trim()) continue
+ let raw: Record<string, unknown>
+ try { raw = JSON.parse(line) as Record<string, unknown> } catch { continue }
+ if (!raw || typeof raw !== 'object') continue
+ const ts = typeof raw.timestamp === 'string' ? Date.parse(raw.timestamp) : NaN
+ if (!Number.isNaN(ts)) { if (first === undefined) first = ts; last = ts }
+ if (raw.type !== 'assistant') continue
+ const msg = raw.message as { content?: unknown; usage?: Record<string, unknown> } | undefined
+ if (!msg) continue
+ if (Array.isArray(msg.content)) {
+ for (const b of msg.content) if ((b as { type?: string }).type === 'tool_use') toolCount++
+ }
+ const u = msg.usage
+ if (u) {
+ tokens += (Number(u.input_tokens) || 0) + (Number(u.output_tokens) || 0)
+ + (Number(u.cache_read_input_tokens) || 0) + (Number(u.cache_creation_input_tokens) || 0)
+ }
+ }
+ return {
+ totalToolUseCount: toolCount,
+ totalDurationMs: first !== undefined && last !== undefined && last > first ? last - first : undefined,
+ totalTokens: tokens || undefined,
+ }
+}
+
+/** Emit tool_end events for a user message's tool_result blocks. */
+function toolResultEvents(msg: NormalizedMessage, toolIdToName: Map<string, string>): SessionEvent[] {
+ const events: SessionEvent[] = []
+ if (!msg.message) return events
+ for (const block of msg.message.content) {
+ if (block.type !== 'tool_result') continue
+ const toolUseId = block.tool_use_id || ''
+ const isError = block.is_error === true
+ let rawOutput = ''
+ if (typeof block.content === 'string') {
+ rawOutput = block.content
+ } else if (Array.isArray(block.content)) {
+ rawOutput = block.content.filter((c) => c.type === 'text' && c.text).map((c) => c.text!).join('')
+ }
+ const toolName = toolIdToName.get(toolUseId) || ''
+ const summary = computeToolSummary(toolName, rawOutput, isError)
+ if (rawOutput.length > MAX_OUTPUT) rawOutput = rawOutput.slice(0, MAX_OUTPUT) + '\n…[truncated]'
+ const agg = msg.toolUseResult
+ const subagent = agg?.agentId
+ ? { agentId: agg.agentId, agentType: agg.agentType, totalTokens: agg.totalTokens, totalDurationMs: agg.totalDurationMs, totalToolUseCount: agg.totalToolUseCount }
+ : undefined
+ events.push({
+ type: 'tool_end',
+ payload: {
+ id: toolUseId, tool: toolName, output: rawOutput, isError, summary,
+ ...(subagent ? { subagent } : {}),
+ ...(typeof agg?.durationSeconds === 'number' ? { durationSeconds: agg.durationSeconds } : {}),
+ },
+ })
+ }
+ return events
+}
+
+/** Emit thinking/text/tool_start events for an assistant message's blocks. */
+function assistantEvents(
+ msg: NormalizedMessage,
+ toolIdToName: Map<string, string>,
+ thinkingIdPrefix: string,
+ thinkingCounterStart = 0,
+): SessionEvent[] {
+ const events: SessionEvent[] = []
+ if (!msg.message) return events
+ let thinkingCounter = thinkingCounterStart
+ for (const block of msg.message.content) {
+ if (block.type === 'thinking' && block.thinking) {
+ const thinkingId = `${thinkingIdPrefix}${thinkingCounter++}`
+ const thinkingContent = block.thinking.length > MAX_THINKING
+ ? block.thinking.slice(0, MAX_THINKING) + '\n…[truncated]'
+ : block.thinking
+ events.push({ type: 'thinking_delta', payload: { content: thinkingContent, thinkingId } })
+ const title = extractThinkingTitle(block.thinking)
+ if (title) events.push({ type: 'thinking_title', payload: { thinkingId, title } })
+ } else if (block.type === 'text' && block.text) {
+ events.push({ type: 'text_delta', payload: { content: block.text } })
+ } else if (block.type === 'tool_use') {
+ const toolId = block.id || ''
+ const toolName = block.name || ''
+ toolIdToName.set(toolId, toolName)
+ let toolInput = block.input
+ if (toolInput && typeof toolInput === 'object') {
+ const inputCopy = { ...(toolInput as Record<string, unknown>) }
+ for (const [key, val] of Object.entries(inputCopy)) {
+ if (typeof val === 'string' && val.length > MAX_OUTPUT) {
+ inputCopy[key] = val.slice(0, MAX_OUTPUT) + '\n…[truncated]'
+ }
+ }
+ toolInput = inputCopy
+ }
+ events.push({ type: 'tool_start', payload: { id: toolId, tool: toolName, input: toolInput } })
+ }
+ }
+ return events
+}
+
+// ── Compaction lines ────────────────────────────────────────────────────────────────────────────
+//
+// When a tmux claude session compacts (auto or `/compact`), it does an IN-FILE compact: the JSONL
+// keeps the SAME sessionId and is append-only (pre-compact history stays on disk), so the byte-offset
+// tail streams straight through — there is no dead file to re-point at and no truncation to re-read.
+// The compact only injects a few bookkeeping lines we must handle so the stream stays clean:
+// • `system` / `subtype:"compact_boundary"` (+ `compactMetadata.trigger`) → one `context_compact`
+// indicator (purely a UI hint; the actual stream continuity is already guaranteed by the tail).
+// • the injected `isCompactSummary` user line (the big "This session is being continued…" summary)
+// and any `isMeta` bookkeeping line → suppressed via the AUTHORITATIVE flags (not a fragile
+// English-string match), so the summary is never rendered as a giant fake user turn / new turn.
+//
+// Returns the events to emit for a compact line (possibly `[]` to suppress it), or `undefined` when
+// `raw` is not a compact line and should fall through to the normal user/assistant path.
+export function compactEventFromRaw(raw: Record<string, unknown>): SessionEvent[] | undefined {
+ if (raw.type === 'system' && raw.subtype === 'compact_boundary') {
+ const meta = raw.compactMetadata as { trigger?: string } | undefined
+ return [{
+ type: 'context_compact',
+ payload: {
+ message: 'Context was compacted — the previous conversation has been summarized to free up space.',
+ ...(meta?.trigger ? { trigger: meta.trigger } : {}),
+ },
+ }]
+ }
+ if (raw.isCompactSummary === true) return []
+ if (raw.isMeta === true) {
+ // NOT all isMeta user lines are bookkeeping. A `/loop` iteration is a REAL prompt that Claude
+ // submits on the user's behalf every time the loop fires, and it is written as isMeta — so blanket
+ // suppression made every iteration after the first invisible: no turn_started, therefore no recap,
+ // therefore nothing on the device, while the loop kept running perfectly in the terminal.
+ //
+ // The discriminator is `promptSource`, which Claude sets authoritatively (same principle as the
+ // flags above — never an English-string match):
+ // 'typed' + no isMeta → the human typed it
+ // 'system' + isMeta → submitted programmatically: a loop iteration. This IS a turn.
+ // (absent) + isMeta → real bookkeeping: a compact summary, or a slash command's expansion
+ // text. Still suppressed, so one `/goal` is not three user turns.
+ if (raw.type === 'user' && raw.promptSource === 'system') return undefined
+ return []
+ }
+ return undefined
+}
+
+// ── Full replay (session_get) ─────────────────────────────────────────────────────────────────────
+
+/** Convert a whole session's raw JSONL lines to replay events (same render path as streaming). */
+export function messagesToEvents(rawLines: string[]): SessionEvent[] {
+ const events: SessionEvent[] = []
+ const toolIdToName = new Map<string, string>()
+ let thinkingCounter = 0
+ let inAutoFixSequence = false
+
+ for (const line of rawLines) {
+ if (!line.trim()) continue
+ let raw: Record<string, unknown>
+ try { raw = JSON.parse(line) as Record<string, unknown> } catch { continue }
+ const compact = compactEventFromRaw(raw)
+ if (compact) { events.push(...compact); continue } // compact boundary → indicator; summary/meta → suppressed
+ const msg = transformLine(raw)
+ if (!msg?.message) continue
+
+ if (msg.type === 'user') {
+ const content = msg.message.content
+ if (isSystemPrompt(content)) { inAutoFixSequence = true; continue }
+ const hasToolResult = content.some((c) => c.type === 'tool_result')
+ const hasUserText = content.some((c) => c.type === 'text' && c.text?.trim())
+ if (inAutoFixSequence && hasToolResult && !hasUserText) continue
+ if (inAutoFixSequence) inAutoFixSequence = false
+
+ if (!hasToolResult) {
+ const textParts: string[] = []
+ const images: Array<{ media_type: string; data: string }> = []
+ for (const block of content) {
+ if (block.type === 'text' && block.text) {
+ let cleaned = stripContextSummary(block.text)
+ if (cleaned) cleaned = stripSystemBlocks(cleaned)
+ if (cleaned && !cleaned.match(/^\[Image: original \d+x\d+/)) textParts.push(cleaned)
+ } else if (block.type === 'image' && block.source) {
+ images.push({ media_type: block.source.media_type, data: block.source.data })
+ }
+ }
+ const textContent = textParts.join('\n')
+ if (textContent || images.length > 0) {
+ events.push({ type: 'user_message', payload: { content: textContent, ...(images.length > 0 ? { images } : {}) } })
+ }
+ continue
+ }
+
+ events.push(...toolResultEvents(msg, toolIdToName))
+ continue
+ }
+
+ // assistant
+ if (inAutoFixSequence) continue
+ const before = events.length
+ events.push(...assistantEvents(msg, toolIdToName, 'thinking-hist-', thinkingCounter))
+ // keep the per-session thinking counter monotonic across messages
+ thinkingCounter += events.slice(before).filter((e) => e.type === 'thinking_delta').length
+ }
+
+ events.push({ type: 'done', payload: { result: 'success' } })
+ return events
+}
+
+/**
+ * Turn-snapped pagination window over raw JSONL lines, for `session_get` with `{limit, before}`.
+ * `before` = uuid of the oldest line the client already holds (exclusive upper bound). Returns the
+ * line slice to feed `messagesToEvents` plus cursor metadata.
+ *
+ * The window START is snapped back to a real user-prompt line so a window never splits an assistant
+ * turn's `tool_use` from its `tool_result`: `messagesToEvents` is stateful (`toolIdToName` carries a
+ * tool_use id → name across lines so the later tool_result renders the tool name), so a mid-turn cut
+ * would drop tool names. A user-prompt line never sits between a tool_use and its tool_result, so
+ * snapping there keeps every turn whole.
+ */
+export function windowRawLines(
+ rawLines: string[],
+ opts: { limit: number; before?: string },
+): { window: string[]; hasMore: boolean; oldestCursor: string | null; staleCursor?: boolean } {
+ // Per-line uuid + whether the line is a real user-prompt turn start (parse each line once).
+ const meta = rawLines.map((line) => {
+ if (!line.trim()) return { uuid: null as string | null, turnStart: false }
+ let raw: Record<string, unknown>
+ try { raw = JSON.parse(line) as Record<string, unknown> } catch { return { uuid: null as string | null, turnStart: false } }
+ const uuid = (raw.uuid ?? raw.id ?? raw.message_id ?? null) as string | null
+ const msg = transformLine(raw)
+ const turnStart = msg ? realUserText(msg) !== null : false
+ return { uuid, turnStart }
+ })
+
+ let endIndex = rawLines.length
+ if (opts.before) {
+ const ci = meta.findIndex((m) => m.uuid === opts.before)
+ // Cursor no longer in the file (should not happen — the transcript is append-only) → signal a
+ // full reload rather than returning a wrong window.
+ if (ci < 0) return { window: [], hasMore: false, oldestCursor: null, staleCursor: true }
+ endIndex = ci // exclusive: the client already holds this line
+ }
+
+ let start = Math.max(0, endIndex - opts.limit)
+ while (start > 0 && !meta[start].turnStart) start--
+
+ return {
+ window: rawLines.slice(start, endIndex),
+ hasMore: start > 0,
+ oldestCursor: meta[start]?.uuid ?? null,
+ }
+}
+
+// ── Live tailing (watcher lines) with derived turn lifecycle ──────────────────────────────────────
+
+export interface TurnState {
+ turnOpen: boolean
+ toolIdToName: Map<string, string>
+ /** tool_use ids started but not yet resolved by a tool_result. */
+ pendingTools: Set<string>
+ thinkingCounter: number
+}
+
+export function newTurnState(): TurnState {
+ return { turnOpen: false, toolIdToName: new Map(), pendingTools: new Set(), thinkingCounter: 0 }
+}
+
+// Terminal assistant stop reasons that close a turn. `tool_use` is deliberately absent (the turn
+// continues into the tool). `pause_turn` is absent too — it may legitimately resume; the Stop hook
+// (which only fires when the agent is truly done) is the authoritative catch-all for that case.
+// `max_tokens`/`refusal` are included so a turn that ends on them still closes from the JSONL alone.
+const TERMINAL_STOP_REASONS = new Set(['end_turn', 'stop_sequence', 'max_tokens', 'refusal'])
+
+/**
+ * Convert ONE appended JSONL line into live events. Derives turn_started/turn_ended from content:
+ * - a real user prompt → (turn_ended if one was open) + turn_started{userMessage}
+ * - assistant blocks → thinking/text/tool_start (tool ids tracked as pending)
+ * - user tool_results → tool_end (resolves pending ids)
+ * - assistant stop_reason in TERMINAL_STOP_REASONS with no pending tools → turn_ended
+ */
+export function lineToEvents(rawLine: string, state: TurnState): LiveEvent[] {
+ if (!rawLine.trim()) return []
+ let raw: Record<string, unknown>
+ try { raw = JSON.parse(rawLine) as Record<string, unknown> } catch { return [] }
+ // A valid-JSON but non-object line (the literal `null`, a number, a bare string) would make the
+ // property access in compactEventFromRaw / transformLine throw — and on the unguarded watcher path
+ // that kills the daemon. Any non-object line has nothing to emit.
+ if (!raw || typeof raw !== 'object') return []
+ // Compaction: emit the boundary indicator; suppress the injected summary/meta lines. The turn state
+ // is left untouched, so an auto-compact that fires MID-TURN keeps the open turn open (the assistant
+ // continuation after the boundary just streams under it) instead of the summary opening a fake turn.
+ const compact = compactEventFromRaw(raw)
+ if (compact) return compact
+ // Sub-agent finished. Deliberately does NOT touch the turn state: the parent turn already closed on the
+ // launch ack, and this record is not a prompt.
+ const finished = taskNotificationEvent(raw)
+ if (finished) return [finished]
+ const msg = transformLine(raw)
+ if (!msg?.message) return []
+
+ const events: LiveEvent[] = []
+
+ if (msg.type === 'user') {
+ // Interrupt: close the open turn and start NOTHING. This is also the only signal for an ESC pressed
+ // straight in the terminal — no cancel frame reaches the adapter there — so the turn has to end here.
+ if (isInterruptLine(msg)) {
+ if (!state.turnOpen) return []
+ state.turnOpen = false
+ state.pendingTools.clear()
+ return [{ type: 'turn_ended', payload: { aborted: true } }]
+ }
+ const userText = realUserText(msg)
+ if (userText !== null) {
+ // New prompt (typed in the terminal OR injected from the web) — starts a turn.
+ if (state.turnOpen) events.push({ type: 'turn_ended', payload: {} })
+ state.turnOpen = true
+ state.pendingTools.clear()
+ events.push({ type: 'turn_started', payload: { userMessage: userText } })
+ return events
+ }
+ // tool_result echoes: resolve pending tools.
+ const ends = toolResultEvents(msg, state.toolIdToName)
+ for (const e of ends) {
+ if (e.type === 'tool_end') state.pendingTools.delete(e.payload.id)
+ }
+ events.push(...ends)
+ return events
+ }
+
+ // assistant
+ const before = events.length
+ events.push(...assistantEvents(msg, state.toolIdToName, 'thinking-live-', state.thinkingCounter))
+ state.thinkingCounter += events.slice(before).filter((e) => e.type === 'thinking_delta').length
+ for (const e of events) {
+ if (e.type === 'tool_start') state.pendingTools.add(e.payload.id)
+ }
+
+ const stop = msg.stopReason
+ if (state.turnOpen && stop && TERMINAL_STOP_REASONS.has(stop) && state.pendingTools.size === 0) {
+ state.turnOpen = false
+ events.push({ type: 'turn_ended', payload: {} })
+ }
+ return events
+}
diff --git a/cli/src/lib/oneshot.ts b/cli/src/lib/oneshot.ts
new file mode 100644
index 000000000..99dbcf4dd
--- /dev/null
+++ b/cli/src/lib/oneshot.ts
@@ -0,0 +1,1049 @@
+/** Disposable, pre-spawned Claude/Codex/Cursor processes used by the device turn recap. */
+
+import { spawn, type ChildProcess } from 'child_process'
+import { mkdirSync, readFileSync, writeFileSync } from 'fs'
+import { readFile, readdir, rm, unlink } from 'fs/promises'
+import { dirname, join } from 'path'
+import { randomUUID } from 'crypto'
+import { homedir, tmpdir, userInfo } from 'os'
+import { env } from '../config/env.js'
+import { findCursorTranscript } from '../engines/cursor/discovery.js'
+import {
+ DisposableOneShotPool,
+ type ActiveEngineCounts,
+ type DisposableWorker,
+ type OneShotEngine,
+} from './disposableOneShotPool.js'
+
+function claudeBin(): string {
+ return env.CLAUDE_PATH || 'claude'
+}
+
+/**
+ * Add one directory to devin's trusted-workspace list, if it is not already there.
+ *
+ * Devin 3000.3.22 refuses to run anywhere it has not been trusted interactively:
+ *
+ * Error: Refusing to run in an untrusted workspace: <dir>
+ * Start `devin` interactively in this directory to trust it, or set
+ * `respect_workspace_trust: false` in your config to restore the previous behavior.
+ *
+ * The recap is headless and runs in a scratch dir machine just created, so there is no prompt for anyone
+ * to answer and no session that survives it — hence this narrow exception to "harness edits no config":
+ * ONE path is appended, the one being created here. The config-wide `respect_workspace_trust: false`
+ * would switch the check off for the user's real projects too; every other entry, and the setting
+ * itself, is left alone. `harness devin` does NOT use this — an interactive pane can ask.
+ */
+export function trustDevinWorkspace(dir: string, onError?: (message: string) => void): void {
+ const file = join(env.DEVIN_HOME, 'trusted_workspaces.json')
+ let config: { trusted_paths?: unknown } = {}
+ try {
+ const parsed: unknown = JSON.parse(readFileSync(file, 'utf-8'))
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) config = parsed
+ } catch { /* absent or unreadable — a fresh list below is the right answer either way */ }
+ const paths = Array.isArray(config.trusted_paths)
+ ? config.trusted_paths.filter((p): p is string => typeof p === 'string')
+ : []
+ if (paths.includes(dir)) return
+ try {
+ mkdirSync(dirname(file), { recursive: true })
+ writeFileSync(file, `${JSON.stringify({ ...config, trusted_paths: [...paths, dir] }, null, 2)}\n`)
+ } catch (err) {
+ // Never fatal: devin then refuses with its own message, which is clearer than anything said here.
+ onError?.(err instanceof Error ? err.message : String(err))
+ }
+}
+
+function cursorBin(): string {
+ return env.CURSOR_PATH || 'agent'
+}
+
+function buildEnv(): NodeJS.ProcessEnv {
+ return {
+ PATH: process.env.PATH || '',
+ HOME: process.env.HOME || homedir(),
+ USER: process.env.USER || userInfo().username,
+ LOGNAME: process.env.LOGNAME || process.env.USER || userInfo().username,
+ TMPDIR: tmpdir(),
+ LANG: process.env.LANG || 'en_US.UTF-8',
+ TERM: process.env.TERM || 'xterm-256color',
+ NODE_ENV: process.env.NODE_ENV || 'production',
+ ...(process.env.ANTHROPIC_BASE_URL && { ANTHROPIC_BASE_URL: process.env.ANTHROPIC_BASE_URL }),
+ ...(process.env.ANTHROPIC_AUTH_TOKEN && { ANTHROPIC_AUTH_TOKEN: process.env.ANTHROPIC_AUTH_TOKEN }),
+ }
+}
+
+export interface OneShotOptions {
+ prompt: string
+ model?: string
+ effort?: 'low' | 'medium' | 'high'
+ cwd: string
+ timeoutMs?: number
+ signal?: AbortSignal
+}
+
+type OneShotResult = { text: string; sessionId: string | null }
+
+function abortError(engine: OneShotEngine): Error {
+ return Object.assign(new Error(`${engine} one-shot aborted`), { name: 'AbortError' })
+}
+
+function killGroup(child: ChildProcess, signal: NodeJS.Signals = 'SIGKILL'): void {
+ if (child.pid == null || child.exitCode != null) return
+ try { process.kill(-child.pid, signal) } catch {
+ try { child.kill(signal) } catch { /* already gone */ }
+ }
+}
+
+export async function cleanupCursorOneShotSession(sessionId: string): Promise<void> {
+ const transcript = await findCursorTranscript(env.CURSOR_HOME, sessionId)
+ if (transcript) await rm(dirname(transcript), { recursive: true, force: true }).catch(() => {})
+
+ const chatsRoot = join(env.CURSOR_HOME, 'chats')
+ const workspaces = await readdir(chatsRoot, { withFileTypes: true }).catch(() => [])
+ await Promise.all(workspaces
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => rm(join(chatsRoot, entry.name, sessionId), { recursive: true, force: true }).catch(() => {})))
+}
+
+abstract class ProcessWorker implements DisposableWorker<OneShotOptions, OneShotResult> {
+ readonly createdAt = Date.now()
+ protected assigned = false
+ protected readonly child: ChildProcess
+ private readonly exitListeners = new Set<() => void>()
+ private readonly spawned: Promise<void>
+
+ abstract readonly engine: OneShotEngine
+ abstract run(options: OneShotOptions): Promise<OneShotResult>
+
+ constructor(child: ChildProcess) {
+ this.child = child
+ this.spawned = new Promise((resolve, reject) => {
+ child.once('spawn', () => resolve())
+ child.once('error', reject)
+ })
+ child.once('close', () => {
+ for (const listener of this.exitListeners) listener()
+ this.exitListeners.clear()
+ })
+ }
+
+ ready(): Promise<this> {
+ return this.spawned.then(() => this)
+ }
+
+ isAlive(): boolean {
+ return this.child.exitCode == null && !this.child.killed
+ }
+
+ onExit(listener: () => void): void {
+ this.exitListeners.add(listener)
+ }
+
+ dispose(): void {
+ killGroup(this.child)
+ }
+}
+
+class ClaudeWorker extends ProcessWorker {
+ readonly engine = 'claude' as const
+ private buffer = ''
+ private stderr = ''
+ private sessionId: string | null = null
+ private resultText = ''
+ private readonly assistantParts: string[] = []
+ private pending: {
+ resolve: (result: OneShotResult) => void
+ reject: (err: unknown) => void
+ timer: NodeJS.Timeout
+ signal?: AbortSignal
+ onAbort: () => void
+ } | null = null
+
+ constructor(cwd: string, model?: string, effort?: OneShotOptions['effort']) {
+ const args = [
+ '--print', '--verbose',
+ '--input-format', 'stream-json',
+ '--output-format', 'stream-json',
+ '--no-session-persistence',
+ // Recap is pure text condensation. Keep Claude from loading project/user customizations,
+ // slash-command skills, MCP servers, or built-in tools.
+ '--safe-mode',
+ '--disable-slash-commands',
+ '--tools', '',
+ '--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}',
+ ...(model ? ['--model', model] : []),
+ ...(effort ? ['--effort', effort] : []),
+ ]
+ const child = spawn(claudeBin(), args, {
+ cwd, env: buildEnv(), detached: true, stdio: ['pipe', 'pipe', 'pipe'],
+ })
+ super(child)
+ child.stdout?.on('data', (chunk: Buffer) => this.onStdout(chunk.toString()))
+ child.stderr?.on('data', (chunk: Buffer) => { this.stderr += chunk.toString() })
+ child.stdin?.on('error', (err) => this.fail(err))
+ child.on('error', (err) => this.fail(err))
+ child.on('close', (code) => {
+ if (this.buffer.trim()) this.handleLine(this.buffer)
+ if (!this.pending) return
+ const text = (this.resultText || this.assistantParts.join('')).trim()
+ if (!text && code !== 0) this.fail(new Error(`claude one-shot exited ${code}: ${this.stderr.slice(0, 500)}`))
+ else this.complete(text)
+ })
+ }
+
+ run(options: OneShotOptions): Promise<OneShotResult> {
+ if (this.assigned) return Promise.reject(new Error('claude recap worker already consumed'))
+ this.assigned = true
+ if (options.signal?.aborted) return Promise.reject(abortError(this.engine))
+ const timeoutMs = options.timeoutMs ?? 60_000
+ return new Promise((resolve, reject) => {
+ const onAbort = (): void => { this.fail(abortError(this.engine)); this.dispose() }
+ const timer = setTimeout(() => {
+ this.fail(new Error(`claude one-shot timed out after ${timeoutMs}ms`))
+ this.dispose()
+ }, timeoutMs)
+ this.pending = { resolve, reject, timer, signal: options.signal, onAbort }
+ options.signal?.addEventListener('abort', onAbort)
+ if (!this.child.stdin || this.child.stdin.destroyed || !this.isAlive()) {
+ this.fail(new Error('claude recap worker is not writable'))
+ return
+ }
+ try {
+ this.child.stdin.write(JSON.stringify({ type: 'user', message: { role: 'user', content: options.prompt } }) + '\n')
+ } catch (err) {
+ this.fail(err)
+ }
+ })
+ }
+
+ private onStdout(chunk: string): void {
+ this.buffer += chunk
+ const lines = this.buffer.split('\n')
+ this.buffer = lines.pop() ?? ''
+ for (const line of lines) this.handleLine(line)
+ }
+
+ private handleLine(line: string): void {
+ const trimmed = line.trim()
+ if (!trimmed) return
+ let evt: Record<string, unknown>
+ try { evt = JSON.parse(trimmed) } catch { return }
+ if (typeof evt.session_id === 'string' && !this.sessionId) this.sessionId = evt.session_id
+ if (evt.type === 'assistant') {
+ const content = (evt.message as { content?: Array<{ type?: string; text?: string }> } | undefined)?.content
+ if (Array.isArray(content)) {
+ const text = content.filter((part) => part?.type === 'text').map((part) => part.text ?? '').join('')
+ if (text) this.assistantParts.push(text)
+ }
+ }
+ if (evt.type === 'result') {
+ if (typeof evt.result === 'string') this.resultText = evt.result
+ this.complete((this.resultText || this.assistantParts.join('')).trim())
+ }
+ }
+
+ private cleanupPending(): typeof this.pending {
+ const pending = this.pending
+ if (!pending) return null
+ this.pending = null
+ clearTimeout(pending.timer)
+ pending.signal?.removeEventListener('abort', pending.onAbort)
+ return pending
+ }
+
+ private complete(text: string): void {
+ const pending = this.cleanupPending()
+ pending?.resolve({ text, sessionId: this.sessionId })
+ }
+
+ private fail(err: unknown): void {
+ this.cleanupPending()?.reject(err)
+ }
+}
+
+class CodexWorker extends ProcessWorker {
+ readonly engine = 'codex' as const
+ private stderr = ''
+ private readonly output: string
+ private pending: {
+ resolve: (result: OneShotResult) => void
+ reject: (err: unknown) => void
+ timer: NodeJS.Timeout
+ signal?: AbortSignal
+ onAbort: () => void
+ } | null = null
+
+ constructor(cwd: string, model?: string, effort?: OneShotOptions['effort']) {
+ const output = join(cwd, `.codex-recap-${randomUUID()}.txt`)
+ const args = [
+ 'exec', '--json', '--ephemeral', '--sandbox', 'read-only', '--skip-git-repo-check',
+ '--ignore-user-config', '--ignore-rules', '--output-last-message', output,
+ ...(model ? ['--model', model] : []),
+ ...(effort ? ['-c', `model_reasoning_effort="${effort}"`] : []),
+ '-',
+ ]
+ const processEnv = { ...process.env }
+ delete processEnv.TMUX
+ delete processEnv.TMUX_PANE
+ const child = spawn(process.env.CODEX_PATH || 'codex', args, {
+ cwd, env: processEnv, detached: true, stdio: ['pipe', 'ignore', 'pipe'],
+ })
+ super(child)
+ this.output = output
+ child.stderr?.on('data', (chunk: Buffer) => { this.stderr += chunk.toString() })
+ child.stdin?.on('error', (err) => this.fail(err))
+ child.on('error', (err) => this.fail(err))
+ child.on('close', (code) => { void this.onClose(code) })
+ }
+
+ override dispose(): void {
+ super.dispose()
+ void unlink(this.output).catch(() => {})
+ }
+
+ run(options: OneShotOptions): Promise<OneShotResult> {
+ if (this.assigned) return Promise.reject(new Error('codex recap worker already consumed'))
+ this.assigned = true
+ if (options.signal?.aborted) return Promise.reject(abortError(this.engine))
+ const timeoutMs = options.timeoutMs ?? 60_000
+ return new Promise((resolve, reject) => {
+ const onAbort = (): void => { this.fail(abortError(this.engine)); this.dispose() }
+ const timer = setTimeout(() => {
+ this.fail(new Error(`codex one-shot timed out after ${timeoutMs}ms`))
+ this.dispose()
+ }, timeoutMs)
+ this.pending = { resolve, reject, timer, signal: options.signal, onAbort }
+ options.signal?.addEventListener('abort', onAbort)
+ if (!this.child.stdin || this.child.stdin.destroyed || !this.isAlive()) {
+ this.fail(new Error('codex recap worker is not writable'))
+ return
+ }
+ try { this.child.stdin.end(options.prompt) } catch (err) { this.fail(err) }
+ })
+ }
+
+ private async onClose(code: number | null): Promise<void> {
+ if (!this.pending) return
+ const text = (await readFile(this.output, 'utf8').catch(() => '')).trim()
+ await unlink(this.output).catch(() => {})
+ if (!text && code !== 0) this.fail(new Error(`codex one-shot exited ${code}: ${this.stderr.slice(0, 500)}`))
+ else this.complete(text)
+ }
+
+ private cleanupPending(): typeof this.pending {
+ const pending = this.pending
+ if (!pending) return null
+ this.pending = null
+ clearTimeout(pending.timer)
+ pending.signal?.removeEventListener('abort', pending.onAbort)
+ return pending
+ }
+
+ private complete(text: string): void {
+ this.cleanupPending()?.resolve({ text, sessionId: null })
+ }
+
+ private fail(err: unknown): void {
+ this.cleanupPending()?.reject(err)
+ }
+}
+
+class CursorWorker extends ProcessWorker {
+ readonly engine = 'cursor' as const
+ private buffer = ''
+ private stderr = ''
+ private sessionId: string | null = null
+ private resultText = ''
+ private cleanupScheduled = false
+ private readonly assistantParts: string[] = []
+ private pending: {
+ resolve: (result: OneShotResult) => void
+ reject: (err: unknown) => void
+ timer: NodeJS.Timeout
+ signal?: AbortSignal
+ onAbort: () => void
+ } | null = null
+
+ constructor(cwd: string, model?: string) {
+ const args = [
+ '--print',
+ '--mode', 'ask',
+ '--sandbox', 'enabled',
+ '--trust',
+ '--output-format', 'stream-json',
+ ...(model ? ['--model', model] : []),
+ ]
+ const processEnv = { ...process.env }
+ delete processEnv.TMUX
+ delete processEnv.TMUX_PANE
+ const child = spawn(cursorBin(), args, {
+ cwd, env: processEnv, detached: true, stdio: ['pipe', 'pipe', 'pipe'],
+ })
+ super(child)
+ child.stdout?.on('data', (chunk: Buffer) => this.onStdout(chunk.toString()))
+ child.stderr?.on('data', (chunk: Buffer) => { this.stderr += chunk.toString() })
+ child.stdin?.on('error', (err) => this.fail(err))
+ child.on('error', (err) => this.fail(err))
+ child.on('close', (code) => {
+ if (this.buffer.trim()) this.handleLine(this.buffer)
+ if (!this.pending) return
+ const text = (this.resultText || this.assistantParts.join('')).trim()
+ if (!text && code !== 0) this.fail(new Error(`cursor one-shot exited ${code}: ${this.stderr.slice(0, 500)}`))
+ else this.complete(text)
+ })
+ }
+
+ run(options: OneShotOptions): Promise<OneShotResult> {
+ if (this.assigned) return Promise.reject(new Error('cursor recap worker already consumed'))
+ this.assigned = true
+ if (options.signal?.aborted) return Promise.reject(abortError(this.engine))
+ const timeoutMs = options.timeoutMs ?? 60_000
+ return new Promise((resolve, reject) => {
+ const onAbort = (): void => { this.fail(abortError(this.engine)); this.dispose() }
+ const timer = setTimeout(() => {
+ this.fail(new Error(`cursor one-shot timed out after ${timeoutMs}ms`))
+ this.dispose()
+ }, timeoutMs)
+ this.pending = { resolve, reject, timer, signal: options.signal, onAbort }
+ options.signal?.addEventListener('abort', onAbort)
+ if (!this.child.stdin || this.child.stdin.destroyed || !this.isAlive()) {
+ this.fail(new Error('cursor recap worker is not writable'))
+ return
+ }
+ try { this.child.stdin.end(options.prompt) } catch (err) { this.fail(err) }
+ })
+ }
+
+ override dispose(): void {
+ super.dispose()
+ if (this.cleanupScheduled) return
+ this.cleanupScheduled = true
+ const cleanup = (): void => {
+ if (this.sessionId) void cleanupCursorOneShotSession(this.sessionId)
+ }
+ if (this.child.exitCode != null) cleanup()
+ else this.child.once('close', cleanup)
+ }
+
+ private onStdout(chunk: string): void {
+ this.buffer += chunk
+ const lines = this.buffer.split('\n')
+ this.buffer = lines.pop() ?? ''
+ for (const line of lines) this.handleLine(line)
+ }
+
+ private handleLine(line: string): void {
+ const trimmed = line.trim()
+ if (!trimmed) return
+ let evt: Record<string, unknown>
+ try { evt = JSON.parse(trimmed) } catch { return }
+ if (typeof evt.session_id === 'string' && !this.sessionId) this.sessionId = evt.session_id
+ if (evt.type === 'assistant') {
+ const content = (evt.message as { content?: Array<{ type?: string; text?: string }> } | undefined)?.content
+ if (Array.isArray(content)) {
+ const text = content.filter((part) => part?.type === 'text').map((part) => part.text ?? '').join('')
+ if (text) this.assistantParts.push(text)
+ }
+ }
+ if (evt.type !== 'result') return
+ if (typeof evt.result === 'string') this.resultText = evt.result
+ if (evt.is_error === true || evt.subtype === 'error') {
+ this.fail(new Error(`cursor one-shot failed: ${(this.resultText || this.stderr).slice(0, 500)}`))
+ return
+ }
+ this.complete((this.resultText || this.assistantParts.join('')).trim())
+ }
+
+ private cleanupPending(): typeof this.pending {
+ const pending = this.pending
+ if (!pending) return null
+ this.pending = null
+ clearTimeout(pending.timer)
+ pending.signal?.removeEventListener('abort', pending.onAbort)
+ return pending
+ }
+
+ private complete(text: string): void {
+ this.cleanupPending()?.resolve({ text, sessionId: this.sessionId })
+ }
+
+ private fail(err: unknown): void {
+ this.cleanupPending()?.reject(err)
+ }
+}
+
+function opencodeBin(): string {
+ return env.OPENCODE_PATH || 'opencode'
+}
+
+// Recap runs in an isolated OpenCode data dir so ephemeral summary sessions never land in the user's
+// real opencode.db, while still reading their ~/.config/opencode provider/model config.
+const OPENCODE_RECAP_DATA_DIR = join(env.ADAPTER_DATA_DIR, 'opencode-recap')
+
+class OpencodeWorker extends ProcessWorker {
+ readonly engine = 'opencode' as const
+ private buffer = ''
+ private stderr = ''
+ private readonly assistantParts: string[] = []
+ private pending: {
+ resolve: (result: OneShotResult) => void
+ reject: (err: unknown) => void
+ timer: NodeJS.Timeout
+ signal?: AbortSignal
+ onAbort: () => void
+ } | null = null
+
+ constructor(model?: string) {
+ // `opencode run` reads the prompt from stdin (pipe → EOF), so the worker can be pre-warmed and fed
+ // the prompt later. `--pure` skips external plugins (so the machine discovery plugin never
+ // 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
+ 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'],
+ })
+ super(child)
+ child.stdout?.on('data', (chunk: Buffer) => this.onStdout(chunk.toString()))
+ child.stderr?.on('data', (chunk: Buffer) => { this.stderr += chunk.toString() })
+ child.stdin?.on('error', (err) => this.fail(err))
+ child.on('error', (err) => this.fail(err))
+ child.on('close', (code) => {
+ if (this.buffer.trim()) this.handleLine(this.buffer)
+ if (!this.pending) return
+ const text = this.assistantParts.join('').trim()
+ if (!text && code !== 0) this.fail(new Error(`opencode one-shot exited ${code}: ${this.stderr.slice(0, 500)}`))
+ else this.complete(text)
+ })
+ }
+
+ run(options: OneShotOptions): Promise<OneShotResult> {
+ if (this.assigned) return Promise.reject(new Error('opencode recap worker already consumed'))
+ this.assigned = true
+ if (options.signal?.aborted) return Promise.reject(abortError(this.engine))
+ const timeoutMs = options.timeoutMs ?? 60_000
+ return new Promise((resolve, reject) => {
+ const onAbort = (): void => { this.fail(abortError(this.engine)); this.dispose() }
+ const timer = setTimeout(() => {
+ this.fail(new Error(`opencode one-shot timed out after ${timeoutMs}ms`))
+ this.dispose()
+ }, timeoutMs)
+ this.pending = { resolve, reject, timer, signal: options.signal, onAbort }
+ options.signal?.addEventListener('abort', onAbort)
+ if (!this.child.stdin || this.child.stdin.destroyed || !this.isAlive()) {
+ this.fail(new Error('opencode recap worker is not writable'))
+ return
+ }
+ try { this.child.stdin.end(options.prompt) } catch (err) { this.fail(err) }
+ })
+ }
+
+ private onStdout(chunk: string): void {
+ this.buffer += chunk
+ const lines = this.buffer.split('\n')
+ this.buffer = lines.pop() ?? ''
+ for (const line of lines) this.handleLine(line)
+ }
+
+ private handleLine(line: string): void {
+ const trimmed = line.trim()
+ if (!trimmed) return
+ let evt: Record<string, unknown>
+ try { evt = JSON.parse(trimmed) } catch { return }
+ if (evt.type === 'text') {
+ const part = evt.part as { text?: string } | undefined
+ if (part && typeof part.text === 'string') this.assistantParts.push(part.text)
+ }
+ }
+
+ private cleanupPending(): typeof this.pending {
+ const pending = this.pending
+ if (!pending) return null
+ this.pending = null
+ clearTimeout(pending.timer)
+ pending.signal?.removeEventListener('abort', pending.onAbort)
+ return pending
+ }
+
+ private complete(text: string): void {
+ this.cleanupPending()?.resolve({ text, sessionId: null })
+ }
+
+ private fail(err: unknown): void {
+ this.cleanupPending()?.reject(err)
+ }
+}
+
+function piBin(): string {
+ return env.PI_PATH || 'pi'
+}
+
+class PiWorker extends ProcessWorker {
+ readonly engine = 'pi' as const
+ private stdout = ''
+ private stderr = ''
+ private pending: {
+ resolve: (result: OneShotResult) => void
+ reject: (err: unknown) => void
+ timer: NodeJS.Timeout
+ signal?: AbortSignal
+ onAbort: () => void
+ } | null = null
+
+ constructor(cwd: string, model?: string) {
+ // `pi -p` reads the prompt from piped stdin (merged into the initial prompt) and prints the plain
+ // 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 child = spawn(piBin(), args, {
+ cwd, env: processEnv, detached: true, stdio: ['pipe', 'pipe', 'pipe'],
+ })
+ super(child)
+ child.stdout?.on('data', (chunk: Buffer) => { this.stdout += chunk.toString() })
+ child.stderr?.on('data', (chunk: Buffer) => { this.stderr += chunk.toString() })
+ child.stdin?.on('error', (err) => this.fail(err))
+ child.on('error', (err) => this.fail(err))
+ child.on('close', (code) => {
+ if (!this.pending) return
+ const text = this.stdout.trim()
+ if (!text && code !== 0) this.fail(new Error(`pi one-shot exited ${code}: ${this.stderr.slice(0, 500)}`))
+ else this.complete(text)
+ })
+ }
+
+ run(options: OneShotOptions): Promise<OneShotResult> {
+ if (this.assigned) return Promise.reject(new Error('pi recap worker already consumed'))
+ this.assigned = true
+ if (options.signal?.aborted) return Promise.reject(abortError(this.engine))
+ const timeoutMs = options.timeoutMs ?? 60_000
+ return new Promise((resolve, reject) => {
+ const onAbort = (): void => { this.fail(abortError(this.engine)); this.dispose() }
+ const timer = setTimeout(() => {
+ this.fail(new Error(`pi one-shot timed out after ${timeoutMs}ms`))
+ this.dispose()
+ }, timeoutMs)
+ this.pending = { resolve, reject, timer, signal: options.signal, onAbort }
+ options.signal?.addEventListener('abort', onAbort)
+ if (!this.child.stdin || this.child.stdin.destroyed || !this.isAlive()) {
+ this.fail(new Error('pi recap worker is not writable'))
+ return
+ }
+ try { this.child.stdin.end(options.prompt) } catch (err) { this.fail(err) }
+ })
+ }
+
+ private cleanupPending(): typeof this.pending {
+ const pending = this.pending
+ if (!pending) return null
+ this.pending = null
+ clearTimeout(pending.timer)
+ pending.signal?.removeEventListener('abort', pending.onAbort)
+ return pending
+ }
+
+ private complete(text: string): void {
+ this.cleanupPending()?.resolve({ text, sessionId: null })
+ }
+
+ private fail(err: unknown): void {
+ this.cleanupPending()?.reject(err)
+ }
+}
+
+function commandCodeBin(): string {
+ return env.COMMANDCODE_PATH || 'commandcode'
+}
+
+class CommandCodeWorker extends ProcessWorker {
+ readonly engine = 'commandcode' as const
+ private stdout = ''
+ private stderr = ''
+ private pending: {
+ resolve: (result: OneShotResult) => void
+ reject: (err: unknown) => void
+ timer: NodeJS.Timeout
+ signal?: AbortSignal
+ onAbort: () => void
+ } | null = null
+
+ 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
+ // 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 child = spawn(commandCodeBin(), args, {
+ cwd, env: processEnv, detached: true, stdio: ['pipe', 'pipe', 'pipe'],
+ })
+ super(child)
+ child.stdout?.on('data', (chunk: Buffer) => { this.stdout += chunk.toString() })
+ child.stderr?.on('data', (chunk: Buffer) => { this.stderr += chunk.toString() })
+ child.stdin?.on('error', (err) => this.fail(err))
+ child.on('error', (err) => this.fail(err))
+ child.on('close', (code) => {
+ if (!this.pending) return
+ const text = this.stdout.trim()
+ if (!text && code !== 0) this.fail(new Error(`commandcode one-shot exited ${code}: ${this.stderr.slice(0, 500)}`))
+ else this.complete(text)
+ })
+ }
+
+ run(options: OneShotOptions): Promise<OneShotResult> {
+ if (this.assigned) return Promise.reject(new Error('commandcode recap worker already consumed'))
+ this.assigned = true
+ if (options.signal?.aborted) return Promise.reject(abortError(this.engine))
+ const timeoutMs = options.timeoutMs ?? 60_000
+ return new Promise((resolve, reject) => {
+ const onAbort = (): void => { this.fail(abortError(this.engine)); this.dispose() }
+ const timer = setTimeout(() => {
+ this.fail(new Error(`commandcode one-shot timed out after ${timeoutMs}ms`))
+ this.dispose()
+ }, timeoutMs)
+ this.pending = { resolve, reject, timer, signal: options.signal, onAbort }
+ options.signal?.addEventListener('abort', onAbort)
+ if (!this.child.stdin || this.child.stdin.destroyed || !this.isAlive()) {
+ this.fail(new Error('commandcode recap worker is not writable'))
+ return
+ }
+ try { this.child.stdin.end(options.prompt) } catch (err) { this.fail(err) }
+ })
+ }
+
+ private cleanupPending(): typeof this.pending {
+ const pending = this.pending
+ if (!pending) return null
+ this.pending = null
+ clearTimeout(pending.timer)
+ pending.signal?.removeEventListener('abort', pending.onAbort)
+ return pending
+ }
+
+ private complete(text: string): void {
+ this.cleanupPending()?.resolve({ text, sessionId: null })
+ }
+
+ private fail(err: unknown): void {
+ this.cleanupPending()?.reject(err)
+ }
+}
+
+let config: {
+ cwd: string
+ claudeModel?: string
+ codexModel?: string
+ cursorModel?: string
+ opencodeModel?: string
+ piModel?: string
+ commandcodeModel?: string
+ effort?: OneShotOptions['effort']
+} | null = null
+const pool = new DisposableOneShotPool<OneShotOptions, OneShotResult>(async (engine) => {
+ if (!config) throw new Error('recap pool is not configured')
+ if (engine === 'claude') return new ClaudeWorker(config.cwd, config.claudeModel, config.effort).ready()
+ if (engine === 'codex') return new CodexWorker(config.cwd, config.codexModel, config.effort).ready()
+ if (engine === 'cursor') return new CursorWorker(config.cwd, config.cursorModel).ready()
+ if (engine === 'pi') return new PiWorker(config.cwd, config.piModel).ready()
+ if (engine === 'commandcode') return new CommandCodeWorker(config.cwd, config.commandcodeModel).ready()
+ return new OpencodeWorker(config.opencodeModel).ready()
+})
+
+export function configureOneShotPool(next: {
+ cwd: string
+ claudeModel?: string
+ codexModel?: string
+ cursorModel?: string
+ opencodeModel?: string
+ piModel?: string
+ commandcodeModel?: string
+ effort?: OneShotOptions['effort']
+}): void {
+ const changed = config != null && (
+ config.cwd !== next.cwd || config.claudeModel !== next.claudeModel ||
+ config.codexModel !== next.codexModel || config.cursorModel !== next.cursorModel ||
+ config.opencodeModel !== next.opencodeModel || config.piModel !== next.piModel ||
+ config.commandcodeModel !== next.commandcodeModel || config.effort !== next.effort
+ )
+ config = next
+ if (changed) pool.recycleReady()
+}
+
+export function setOneShotPoolActiveCounts(counts: ActiveEngineCounts): void {
+ pool.setActiveCounts(counts)
+}
+
+export function setOneShotPoolDeviceConnected(connected: boolean): void {
+ pool.setDeviceConnected(connected)
+}
+
+export function shutdownOneShotPool(): void {
+ pool.shutdown()
+}
+
+/** Spawn ONE worker for an engine. Shared by the cold path and both warm pools so a pooled worker can
+ * never be started differently from a direct one. */
+function createOneShotWorker(
+ engine: OneShotEngine,
+ cwd: string,
+ model?: string,
+ effort?: OneShotOptions['effort'],
+): Promise<DisposableWorker<OneShotOptions, OneShotResult>> {
+ return engine === 'claude'
+ ? new ClaudeWorker(cwd, model, effort).ready()
+ : engine === 'codex'
+ ? new CodexWorker(cwd, model, effort).ready()
+ : engine === 'cursor'
+ ? new CursorWorker(cwd, model).ready()
+ : engine === 'pi'
+ ? new PiWorker(cwd, model).ready()
+ : engine === 'commandcode'
+ ? new CommandCodeWorker(cwd, model).ready()
+ : new OpencodeWorker(model).ready()
+}
+
+async function runDirect(engine: OneShotEngine, opts: OneShotOptions): Promise<OneShotResult> {
+ const worker = await createOneShotWorker(engine, opts.cwd, opts.model, opts.effort)
+ try { return await worker.run(opts) } finally { worker.dispose() }
+}
+
+export function runClaudeOneShot(opts: OneShotOptions): Promise<OneShotResult> {
+ if (opts.signal?.aborted) return Promise.reject(abortError('claude'))
+ if (!config || config.cwd !== opts.cwd || config.claudeModel !== opts.model || config.effort !== opts.effort) {
+ return runDirect('claude', opts)
+ }
+ return pool.run('claude', opts)
+}
+
+export function runCodexOneShot(opts: OneShotOptions): Promise<{ text: string; sessionId: null }> {
+ if (opts.signal?.aborted) return Promise.reject(abortError('codex'))
+ const run = !config || config.cwd !== opts.cwd || config.codexModel !== opts.model || config.effort !== opts.effort
+ ? runDirect('codex', opts)
+ : pool.run('codex', opts)
+ return run.then((result) => ({ text: result.text, sessionId: null }))
+}
+
+export function runCursorOneShot(opts: OneShotOptions): Promise<OneShotResult> {
+ if (opts.signal?.aborted) return Promise.reject(abortError('cursor'))
+ if (!config || config.cwd !== opts.cwd || config.cursorModel !== opts.model) {
+ return runDirect('cursor', opts)
+ }
+ return pool.run('cursor', opts)
+}
+
+function hermesBin(): string {
+ return env.HERMES_PATH || 'hermes'
+}
+
+/**
+ * Hermes recap. Unlike every other engine, `hermes chat -q` takes the prompt as **argv, not stdin**, so
+ * a worker cannot be pre-warmed — each recap spawns a fresh process (Hermes is deliberately absent from
+ * `OneShotEngine`/the warm pool).
+ *
+ * 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.
+ */
+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 timeoutMs = opts.timeoutMs ?? 60_000
+
+ return new Promise<OneShotResult>((resolve, reject) => {
+ const child = spawn(hermesBin(), args, {
+ cwd: opts.cwd, env: processEnv, detached: true, stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ let stdout = ''
+ let stderr = ''
+ let settled = false
+ const finish = (fn: () => void): void => {
+ if (settled) return
+ settled = true
+ clearTimeout(timer)
+ opts.signal?.removeEventListener('abort', onAbort)
+ fn()
+ }
+ const kill = (): void => {
+ if (child.pid == null || child.exitCode != null) return
+ try { process.kill(-child.pid, 'SIGKILL') } catch { try { child.kill('SIGKILL') } catch { /* gone */ } }
+ }
+ const onAbort = (): void => {
+ finish(() => reject(Object.assign(new Error('hermes one-shot aborted'), { name: 'AbortError' })))
+ kill()
+ }
+ const timer = setTimeout(() => {
+ finish(() => reject(new Error(`hermes one-shot timed out after ${timeoutMs}ms`)))
+ kill()
+ }, timeoutMs)
+ opts.signal?.addEventListener('abort', onAbort)
+
+ child.stdout?.on('data', (chunk: Buffer) => { stdout += chunk.toString() })
+ child.stderr?.on('data', (chunk: Buffer) => { stderr += chunk.toString() })
+ child.on('error', (err) => finish(() => reject(err)))
+ child.on('close', (code) => {
+ // `-Q` still prints a `session_id: …` line before the answer — drop it.
+ const text = stdout.split('\n').filter((line) => !/^\s*session_id:\s/.test(line)).join('\n').trim()
+ finish(() => {
+ if (!text && code !== 0) reject(new Error(`hermes one-shot exited ${code}: ${stderr.slice(0, 500)}`))
+ else resolve({ text, sessionId: null })
+ })
+ })
+ })
+}
+
+function devinBin(): string {
+ return env.DEVIN_PATH || 'devin'
+}
+
+
+/**
+ * Devin recap. Like Hermes — and unlike every pooled engine — the prompt must be **argv**: piping it to
+ * `devin -p` panics the CLI outright (`called Result::unwrap() on an Err value`, verified on 3000.2.17),
+ * 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.
+ */
+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 timeoutMs = opts.timeoutMs ?? 60_000
+
+ return new Promise<OneShotResult>((resolve, reject) => {
+ const child = spawn(devinBin(), args, {
+ cwd: opts.cwd, env: processEnv, detached: true, stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ let stdout = ''
+ let stderr = ''
+ let settled = false
+ const finish = (fn: () => void): void => {
+ if (settled) return
+ settled = true
+ clearTimeout(timer)
+ opts.signal?.removeEventListener('abort', onAbort)
+ fn()
+ }
+ const kill = (): void => {
+ if (child.pid == null || child.exitCode != null) return
+ try { process.kill(-child.pid, 'SIGKILL') } catch { try { child.kill('SIGKILL') } catch { /* gone */ } }
+ }
+ const onAbort = (): void => {
+ finish(() => reject(Object.assign(new Error('devin one-shot aborted'), { name: 'AbortError' })))
+ kill()
+ }
+ const timer = setTimeout(() => {
+ finish(() => reject(new Error(`devin one-shot timed out after ${timeoutMs}ms`)))
+ kill()
+ }, timeoutMs)
+ opts.signal?.addEventListener('abort', onAbort)
+
+ child.stdout?.on('data', (chunk: Buffer) => { stdout += chunk.toString() })
+ child.stderr?.on('data', (chunk: Buffer) => { stderr += chunk.toString() })
+ child.on('error', (err) => finish(() => reject(err)))
+ child.on('close', (code) => {
+ const text = stdout.trim()
+ finish(() => {
+ if (!text && code !== 0) reject(new Error(`devin one-shot exited ${code}: ${stderr.slice(0, 500)}`))
+ else resolve({ text, sessionId: null })
+ })
+ })
+ })
+}
+
+export function runCommandCodeOneShot(opts: OneShotOptions): Promise<OneShotResult> {
+ if (opts.signal?.aborted) return Promise.reject(abortError('commandcode'))
+ if (!config || config.cwd !== opts.cwd || config.commandcodeModel !== opts.model) {
+ return runDirect('commandcode', opts)
+ }
+ return pool.run('commandcode', opts)
+}
+
+export function runPiOneShot(opts: OneShotOptions): Promise<OneShotResult> {
+ if (opts.signal?.aborted) return Promise.reject(abortError('pi'))
+ if (!config || config.cwd !== opts.cwd || config.piModel !== opts.model) {
+ return runDirect('pi', opts)
+ }
+ return pool.run('pi', opts)
+}
+
+export function runOpencodeOneShot(opts: OneShotOptions): Promise<OneShotResult> {
+ if (opts.signal?.aborted) return Promise.reject(abortError('opencode'))
+ if (!config || config.cwd !== opts.cwd || config.opencodeModel !== opts.model) {
+ return runDirect('opencode', opts)
+ }
+ return pool.run('opencode', opts)
+}
+
+// ── Voice-router warm worker ─────────────────────────────────────────────────────────────────────────
+// The Overview voice router runs a tiny classifier on EVERY voice turn. Spawning the CLI each time paid a
+// cold start (Node boot + CLI init + auth) that occasionally blew the 12s budget → "voice_route timed out".
+// Keep ONE router worker warm (device-gated, like the recap pool) so the classify skips the spawn. Separate
+// from the recap `pool` because the router uses its own small model, and only ever needs one worker.
+//
+// The ENGINE is chosen by the caller from the machine's live agents (see voiceRouter.chooseRouterEngine).
+// It used to be pinned to claude here, which meant a machine with no Claude CLI never routed at all: the
+// warm spawn failed on a loop and every voice fell through to the name-matching heuristic, whose capped
+// confidence can never clear the backend's auto-dispatch threshold.
+let routerConfig: { engine: OneShotEngine; cwd: string; model?: string; effort?: OneShotOptions['effort'] } | null = null
+const routerPool = new DisposableOneShotPool<OneShotOptions, OneShotResult>(
+ async () => {
+ if (!routerConfig) throw new Error('router pool is not configured')
+ return createOneShotWorker(routerConfig.engine, routerConfig.cwd, routerConfig.model, routerConfig.effort)
+ },
+ 5 * 60_000,
+ (line) => console.log(line.replace('[recap-pool]', '[router-pool]')),
+)
+
+/** Routing needs exactly ONE warm worker, of the configured engine — active=1 there, 0 everywhere else. */
+function pinRouterEngine(engine: OneShotEngine): void {
+ routerPool.setActiveCounts({
+ claude: 0, codex: 0, cursor: 0, opencode: 0, pi: 0, commandcode: 0, [engine]: 1,
+ } as Parameters<typeof routerPool.setActiveCounts>[0])
+}
+
+export function configureRouterOneShot(next: { engine: OneShotEngine; cwd: string; model?: string; effort?: OneShotOptions['effort'] }): void {
+ const changed = routerConfig != null && (
+ routerConfig.engine !== next.engine || routerConfig.cwd !== next.cwd ||
+ routerConfig.model !== next.model || routerConfig.effort !== next.effort
+ )
+ routerConfig = next
+ pinRouterEngine(next.engine)
+ // An engine change must drop the warm worker too — it is the wrong CLI now, not just the wrong model.
+ if (changed) routerPool.recycleReady()
+}
+
+export function setRouterOneShotDeviceConnected(connected: boolean): void {
+ routerPool.setDeviceConnected(connected)
+}
+
+export function shutdownRouterOneShot(): void {
+ routerPool.shutdown()
+}
+
+/** Like runClaudeOneShot but served from the dedicated warm router worker (a cold spawn only if the pool
+ * isn't configured for this exact cwd/model/effort). */
+export function runRouterOneShot(engine: OneShotEngine, opts: OneShotOptions): Promise<OneShotResult> {
+ if (opts.signal?.aborted) return Promise.reject(abortError(engine))
+ if (!routerConfig || routerConfig.engine !== engine || routerConfig.cwd !== opts.cwd ||
+ routerConfig.model !== opts.model || routerConfig.effort !== opts.effort) {
+ return runDirect(engine, opts)
+ }
+ return routerPool.run(engine, opts)
+}
diff --git a/cli/src/lib/paths.ts b/cli/src/lib/paths.ts
new file mode 100644
index 000000000..82d2d4842
--- /dev/null
+++ b/cli/src/lib/paths.ts
@@ -0,0 +1,31 @@
+/**
+ * Path helpers for locating Claude Code session JSONL files.
+ *
+ * Layout on disk (written by the local `claude` CLI):
+ * {CLAUDE_PROJECTS_DIR}/<mangled-workdir>/<sessionId>.jsonl
+ *
+ * The `<mangled-workdir>` is the absolute project dir with every non-alphanumeric
+ * character replaced by `-`. It is lossy (not reversible), so we derive the real
+ * working directory from the `cwd` field carried on the JSONL lines instead.
+ *
+ * This module is intentionally self-contained — machine-adapter does not import from
+ * anything outside this package.
+ */
+
+import { basename } from 'path'
+
+/** True for a session JSONL we want to surface (excludes subagent mirrors). */
+export function isSessionFile(filePath: string): boolean {
+ const name = basename(filePath)
+ return name.endsWith('.jsonl') && !name.startsWith('agent-')
+}
+
+/** True for a path inside a `.codex/` engine subdir (skipped for now). */
+export function isCodexPath(filePath: string): boolean {
+ return filePath.includes('/.codex/') || filePath.includes('\\.codex\\')
+}
+
+/** The sessionId is the JSONL filename without its extension. */
+export function sessionIdFromFile(filePath: string): string {
+ return basename(filePath).replace(/\.jsonl$/, '')
+}
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
new file mode 100644
index 000000000..d0abbd993
--- /dev/null
+++ b/cli/src/lib/registry.spec.ts
@@ -0,0 +1,554 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+
+let dataDir = ''
+
+async function loadRegistryModule() {
+ vi.resetModules()
+ process.env.ADAPTER_DATA_DIR = dataDir
+ process.env.CLAUDE_PROJECTS_DIR = dataDir
+ process.env.CODEX_HOME = dataDir
+ process.env.CURSOR_HOME = dataDir
+ return import('./registry.js')
+}
+
+describe('registry remote display names', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-'))
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ rmSync(dataDir, { recursive: true, force: true })
+ delete process.env.ADAPTER_DATA_DIR
+ delete process.env.CLAUDE_PROJECTS_DIR
+ delete process.env.CODEX_HOME
+ delete process.env.CURSOR_HOME
+ })
+
+ it('persists renamed display names independently from session removal', async () => {
+ const transcriptPath = join(dataDir, 'session-1.jsonl')
+ writeFileSync(transcriptPath, '{}\n')
+
+ const { registry, projectDisplayName } = await loadRegistryModule()
+ registry.load()
+ const registered = registry.register({ launcherId: 'h1', sessionId: 'session-1', transcriptPath, tmuxPane: '%1', cwd: '/tmp/demo' })
+ expect(registered?.entry).toBeTruthy()
+ expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))).toMatchObject([
+ { sessionId: 'session-1', transcriptPath },
+ ])
+
+ const renamed = registry.rename('session-1', 'Production API')
+ expect(renamed).toBeTruthy()
+ expect(projectDisplayName(registered!.entry)).toBe('Production API')
+
+ const persisted = JSON.parse(readFileSync(join(dataDir, 'agent-names.json'), 'utf-8')) as Record<string, string>
+ expect(persisted).toEqual({ 'session-1': 'Production API' })
+
+ registry.remove('session-1')
+ expect(registry.get('session-1')).toBeUndefined()
+ expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))).toEqual([])
+ expect(JSON.parse(readFileSync(join(dataDir, 'agent-names.json'), 'utf-8'))).toEqual({ 'session-1': 'Production API' })
+ })
+
+ 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([{
+ launcherId: 'h1',
+ sessionId: 'session-2',
+ transcriptPath,
+ projectDir: 'tmp-demo',
+ cwd: '/tmp/demo',
+ tmuxPane: '%2',
+ source: null,
+ title: null,
+ model: null,
+ registeredAt: 1,
+ updatedAt: 1,
+ }]))
+
+ const { registry, projectDisplayName } = await loadRegistryModule()
+ registry.load()
+ const session = registry.get('session-2')
+ expect(session).toBeTruthy()
+ expect(session?.engine).toBe('claude')
+ expect(projectDisplayName(session!)).toBe('Research box')
+ expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))[0]).toMatchObject({
+ sessionId: 'session-2',
+ engine: 'claude',
+ tmuxPane: '%2',
+ })
+ })
+
+ it('auto-follows the tmux pane title until renamed, then the manual name stays fixed', async () => {
+ const transcriptPath = join(dataDir, 'session-title.jsonl')
+ writeFileSync(transcriptPath, '{}\n')
+
+ const { registry, projectDisplayName } = await loadRegistryModule()
+ registry.load()
+ const registered = registry.register({
+ launcherId: 'h1',
+ sessionId: 'session-title',
+ transcriptPath,
+ tmuxPane: '%7',
+ cwd: '/tmp/demo',
+ title: '📋 ✳ Clarify assistant identity',
+ })
+ expect(registered?.entry).toBeTruthy()
+ expect(registered?.entry.title).toBe('Clarify assistant identity')
+ // Un-renamed: display auto-follows the tmux title.
+ expect(projectDisplayName(registered!.entry)).toBe('Clarify assistant identity')
+
+ const updated = registry.updateTitle('session-title', '🧪 — * Ship settings page')
+ expect(updated?.title).toBe('Ship settings page')
+ expect(projectDisplayName(updated!)).toBe('Ship settings page')
+
+ // After a manual rename the override wins and is FIXED — it must NOT drift back to the title.
+ registry.rename('session-title', 'Manual name')
+ expect(projectDisplayName(updated!)).toBe('Manual name')
+
+ // A later tmux-title change (Claude rewrites it to the latest topic) does not move the display name.
+ const retitled = registry.updateTitle('session-title', '⚡ New convo topic')
+ expect(retitled?.title).toBe('New convo topic') // internal title still tracked
+ expect(projectDisplayName(retitled!)).toBe('Manual name') // display stays fixed
+ })
+
+ 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' }))
+
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ registry.register({ launcherId: 'h1', sessionId: 'session-3', transcriptPath, tmuxPane: '%3', cwd: '/tmp/demo' })
+ registry.rename('session-3', 'New name')
+
+ expect(JSON.parse(readFileSync(join(dataDir, 'agent-names.json'), 'utf-8'))).toEqual({
+ old: 'Keep me',
+ 'session-3': 'New name',
+ })
+ })
+
+ it('persists Codex engine metadata and rejects records without a valid pane', async () => {
+ const sessionsDir = join(dataDir, 'sessions')
+ const transcriptPath = join(sessionsDir, 'codex-session.jsonl')
+ mkdirSync(sessionsDir)
+ writeFileSync(transcriptPath, '{}\n')
+
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ registry.register({
+ launcherId: 'h1',
+ engine: 'codex',
+ sessionId: 'codex-session',
+ transcriptPath,
+ tmuxPane: '%4',
+ cwd: '/tmp/codex',
+ })
+ const valid = registry.get('codex-session')
+ 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))
+
+ registry.load()
+ expect(registry.get('codex-session')?.engine).toBe('codex')
+ expect(registry.get('invalid-session')).toBeUndefined()
+ expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))).toHaveLength(1)
+ })
+
+ it('repairs a Codex parent registry entry overwritten with a child rollout', async () => {
+ const parentId = '019f7f1b-195d-70f2-861b-de5d54a3e141'
+ const childId = '019f8dae-e5f4-7c11-90d1-600854063b2c'
+ const sessionsDir = join(dataDir, 'sessions', '2026', '07', '23')
+ mkdirSync(sessionsDir, { recursive: true })
+ const parentPath = join(sessionsDir, `rollout-${parentId}.jsonl`)
+ const childPath = join(sessionsDir, `rollout-${childId}.jsonl`)
+ writeFileSync(parentPath, JSON.stringify({
+ type: 'session_meta',
+ payload: { id: parentId, source: 'cli' },
+ }) + '\n')
+ writeFileSync(childPath, JSON.stringify({
+ type: 'session_meta',
+ payload: {
+ id: childId,
+ source: { subagent: { thread_spawn: { parent_thread_id: parentId, depth: 1 } } },
+ },
+ }) + '\n')
+ writeFileSync(join(dataDir, 'registry.json'), JSON.stringify([{
+ launcherId: 'h1',
+ sessionId: parentId,
+ engine: 'codex',
+ transcriptPath: childPath,
+ projectDir: '23',
+ cwd: '/tmp/codex',
+ tmuxPane: '%8',
+ source: null,
+ title: null,
+ model: null,
+ cliVersion: '0.144.6',
+ processIdentity: null,
+ registeredAt: 1,
+ updatedAt: 1,
+ lastHookAt: 1,
+ lastTranscriptAt: 1,
+ }]))
+
+ const { registry } = await loadRegistryModule()
+ registry.load()
+
+ expect(registry.get(parentId)?.transcriptPath).toBe(parentPath)
+ expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))[0].transcriptPath).toBe(parentPath)
+ expect(registry.register({
+ launcherId: 'h1',
+ engine: 'codex',
+ sessionId: parentId,
+ transcriptPath: childPath,
+ tmuxPane: '%8',
+ })).toBeNull()
+ })
+
+ it('clears stale process identity for lowercase Cursor sessionStart hooks', async () => {
+ const sessionId = '53d3843c-724e-47ff-ae3a-9fedfa328bba'
+ const transcriptPath = join(
+ dataDir,
+ 'projects',
+ 'workspace',
+ 'agent-transcripts',
+ sessionId,
+ `${sessionId}.jsonl`,
+ )
+ mkdirSync(join(transcriptPath, '..'), { recursive: true })
+ writeFileSync(transcriptPath, '{}\n')
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ registry.register({
+ launcherId: 'h1',
+ engine: 'cursor',
+ sessionId,
+ transcriptPath,
+ tmuxPane: '%3',
+ processIdentity: { pid: 100, executable: 'agent', startMarker: 'old' },
+ hookEvent: 'beforeSubmitPrompt',
+ })
+
+ const resumed = registry.register({
+ launcherId: 'h1',
+ engine: 'cursor',
+ sessionId,
+ transcriptPath,
+ tmuxPane: '%3',
+ hookEvent: 'sessionStart',
+ })
+
+ expect(resumed?.entry.processIdentity).toBeNull()
+ })
+
+ it('persists a pending Cursor session and attaches its exact transcript later', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ expect(registry.register({
+ launcherId: 'h1',
+ engine: 'cursor',
+ sessionId: '12345678-1234-1234-1234-123456789abc',
+ tmuxPane: '%5',
+ cwd: '/tmp/cursor',
+ cliVersion: '2026.07.20-8cc9c0b',
+ })?.entry.transcriptPath).toBeNull()
+
+ registry.load()
+ expect(registry.get('12345678-1234-1234-1234-123456789abc')?.transcriptPath).toBeNull()
+
+ const transcript = join(
+ dataDir,
+ 'projects',
+ 'workspace',
+ 'agent-transcripts',
+ '12345678-1234-1234-1234-123456789abc',
+ '12345678-1234-1234-1234-123456789abc.jsonl',
+ )
+ mkdirSync(join(transcript, '..'), { recursive: true })
+ writeFileSync(transcript, '{}\n')
+ const attached = registry.register({
+ launcherId: 'h1',
+ engine: 'cursor',
+ sessionId: '12345678-1234-1234-1234-123456789abc',
+ transcriptPath: transcript,
+ tmuxPane: '%5',
+ })
+ expect(attached?.entry.transcriptPath).toBe(transcript)
+ })
+})
+
+describe('registry model coercion', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-'))
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ rmSync(dataDir, { recursive: true, force: true })
+ delete process.env.ADAPTER_DATA_DIR
+ delete process.env.CLAUDE_PROJECTS_DIR
+ delete process.env.CODEX_HOME
+ delete process.env.CURSOR_HOME
+ })
+
+ // Claude Code's hooks report `model` as {id, display_name}. Persisting that object took the daemon down
+ // at STARTUP (runtimeProfile called .toLowerCase() on it) — and no restart could heal it, because the bad
+ // value was already on disk.
+ it('stores the id when the hook reports a model object', async () => {
+ const transcriptPath = join(dataDir, 'm1.jsonl')
+ writeFileSync(transcriptPath, '{}\n')
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ registry.register({
+ launcherId: 'h1',
+ sessionId: 'm1', transcriptPath, tmuxPane: '%1', cwd: '/tmp/demo',
+ model: { id: 'claude-opus-4-8', display_name: 'Opus 4.8' } as unknown as string,
+ })
+ expect(registry.get('m1')?.model).toBe('claude-opus-4-8')
+ })
+
+ it('keeps a plain string and drops anything else', async () => {
+ const transcriptPath = join(dataDir, 'm2.jsonl')
+ writeFileSync(transcriptPath, '{}\n')
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ registry.register({ launcherId: 'h1', sessionId: 'm2', transcriptPath, tmuxPane: '%1', cwd: '/tmp/demo', model: 'gpt-5.6-sol' })
+ expect(registry.get('m2')?.model).toBe('gpt-5.6-sol')
+ // A SECOND launcher, not the same one: one launcher owns one pane owns one agent, so registering
+ // another session under 'h1' would be a rotation (which inherits the previous model) rather than the
+ // fresh record this coercion check needs.
+ registry.register({ launcherId: 'h2', sessionId: 'm3', transcriptPath, tmuxPane: '%2', cwd: '/tmp/demo', model: 42 as unknown as string })
+ expect(registry.get('m3')?.model).toBeNull()
+ })
+})
+
+/**
+ * A Command Code session announces itself BEFORE its transcript exists, so the path used to arrive only
+ * with the first Stop hook — after the first turn had already failed for want of a watcher.
+ */
+describe('a Command Code session without a transcript path', () => {
+ beforeEach(() => {
+ dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-cc-'))
+ })
+
+ afterEach(() => {
+ rmSync(dataDir, { recursive: true, force: true })
+ delete process.env.COMMANDCODE_HOME
+ })
+
+ it('gets the deterministic one derived from its cwd', async () => {
+ process.env.COMMANDCODE_HOME = dataDir
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const registered = registry.register({
+ launcherId: 'h1',
+ engine: 'commandcode',
+ sessionId: 'ae93cc89-0dff-452a-a875-33b1516bbc80',
+ tmuxPane: '%9',
+ cwd: '/Users/me/Working/Tmux/Agent-6',
+ })
+ // The file does not exist yet — that is the whole point. The watcher opens at offset 0 and chokidar
+ // delivers the lines when the CLI finally writes them.
+ expect(registered?.entry.transcriptPath).toBe(
+ join(dataDir, 'projects', 'users-me-working-tmux-agent-6', 'ae93cc89-0dff-452a-a875-33b1516bbc80.jsonl'),
+ )
+ })
+
+ it('keeps a path the CLI reported over the derived one', async () => {
+ process.env.COMMANDCODE_HOME = dataDir
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const reported = join(dataDir, 'projects', 'somewhere-else', 'reported.jsonl')
+ mkdirSync(join(dataDir, 'projects', 'somewhere-else'), { recursive: true })
+ writeFileSync(reported, '')
+ const registered = registry.register({
+ launcherId: 'h1',
+ engine: 'commandcode',
+ sessionId: 'reported',
+ tmuxPane: '%9',
+ cwd: '/Users/me/Working/Tmux/Agent-6',
+ transcriptPath: reported,
+ })
+ expect(registered?.entry.transcriptPath).toBe(reported)
+ })
+})
+
+describe('agent identity: the launcher owns the agent, the session is bound to it', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-id-'))
+ })
+ afterEach(() => {
+ vi.useRealTimers()
+ rmSync(dataDir, { recursive: true, force: true })
+ delete process.env.ADAPTER_DATA_DIR
+ delete process.env.CLAUDE_PROJECTS_DIR
+ delete process.env.CODEX_HOME
+ delete process.env.CURSOR_HOME
+ })
+
+ function transcript(name: string): string {
+ const p = join(dataDir, `${name}.jsonl`)
+ writeFileSync(p, '{}\n')
+ return p
+ }
+
+ it('resolves a record by EITHER id', async () => {
+ // Web and device address turn control with a bare sessionId (`cancel`, `question_response`) and
+ // everything else with the agentId; both have to land on the same record.
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const res = registry.register({ launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
+ expect(res?.entry.agentId).toBe('agent-1')
+ expect(registry.resolve('agent-1')?.sessionId).toBe('s1')
+ expect(registry.resolve('s1')?.agentId).toBe('agent-1')
+ expect(registry.byAgent('s1')).toBeUndefined()
+ expect(registry.bySession('agent-1')).toBeUndefined()
+ })
+
+ it('a rotation rebinds the SAME agent instead of creating a second one', async () => {
+ // `/clear` in claude (and `/new` in opencode) ends one session id and starts another in the same pane
+ // under the same launcher. That is one agent with a new session underneath, not two agents.
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ registry.register({ launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
+ const rot = registry.register({ launcherId: 'agent-1', sessionId: 's2', transcriptPath: transcript('s2'), tmuxPane: '%1', cwd: '/tmp/demo' })
+
+ expect(rot?.rebound).toBe('s1')
+ expect(rot?.isNew).toBe(true) // the SESSION is new — the caller still announces it
+ expect(registry.list()).toHaveLength(1)
+ expect(registry.byAgent('agent-1')?.sessionId).toBe('s2')
+ expect(registry.bySession('s1')).toBeUndefined() // the dead session no longer resolves
+ expect(registry.resolve('agent-1')?.boundAt).toBe(Date.now())
+ })
+
+ it('a re-register of the same session is not a rotation', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ registry.register({ launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
+ const again = registry.register({ launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
+ expect(again?.isNew).toBe(false)
+ expect(again?.rebound).toBeNull()
+ expect(registry.list()).toHaveLength(1)
+ })
+
+ it('one engine session cannot belong to two agents', async () => {
+ // `claude --resume <id>` in a second pane: the newest bind wins and the loser is dropped rather than
+ // left pointing at a session it no longer owns.
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ registry.register({ launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
+ registry.register({ launcherId: 'agent-2', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%2', cwd: '/tmp/demo' })
+ expect(registry.list()).toHaveLength(1)
+ expect(registry.resolve('s1')?.agentId).toBe('agent-2')
+ expect(registry.byAgent('agent-1')).toBeUndefined()
+ })
+
+ it('accepts a payload from an OLD launcher, which knows only launcherId', async () => {
+ // A launcher started before this build owns the tty and cannot upgrade itself, so it keeps sending
+ // the v1 `open` frame and its hook keeps posting `launcherId` alone — for hours. That id IS the agent
+ // id, so nothing new is required on the wire: the daemon just reinterprets what it already receives.
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const res = registry.register({ launcherId: 'old-launcher', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
+ expect(res?.entry.agentId).toBe('old-launcher')
+ expect(registry.resolve('old-launcher')?.sessionId).toBe('s1')
+ // …and its rotation still lands on the same agent.
+ const rot = registry.register({ launcherId: 'old-launcher', sessionId: 's2', transcriptPath: transcript('s2'), tmuxPane: '%1', cwd: '/tmp/demo' })
+ expect(rot?.rebound).toBe('s1')
+ expect(registry.list()).toHaveLength(1)
+ })
+
+ it('creates an agent at launcher open, before any engine session exists', async () => {
+ // `harness <engine>` must put an agent on screen the moment it is typed — the engine has not picked a
+ // session yet, and for a resumed one it may never report a NEW id at all.
+ const { registry, projectDisplayName } = await loadRegistryModule()
+ registry.load()
+ const opened = registry.openAgent({ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo' })
+ expect(opened?.isNew).toBe(true)
+ expect(opened?.entry.sessionId).toBe('')
+ expect(registry.unbound().map((s) => s.agentId)).toEqual(['agent-1'])
+ expect(registry.resolve('agent-1')?.agentId).toBe('agent-1')
+ expect(projectDisplayName(opened!.entry)).toContain('demo') // nameable while unbound
+
+ // The engine reports its session later — same agent, now bound.
+ const bound = registry.register({ launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
+ expect(bound?.entry.agentId).toBe('agent-1')
+ expect(registry.list()).toHaveLength(1)
+ expect(registry.unbound()).toHaveLength(0)
+ expect(registry.resolve('s1')?.agentId).toBe('agent-1')
+ })
+
+ it('re-opening the same launcher keeps the session it had already bound', async () => {
+ // A launcher reconnects after a daemon restart / self-update with the SAME id — that is not a new
+ // agent, and it must not lose its binding.
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ registry.openAgent({ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo' })
+ registry.register({ launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
+ const again = registry.openAgent({ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo' })
+ expect(again?.isNew).toBe(false)
+ expect(again?.entry.sessionId).toBe('s1')
+ expect(registry.list()).toHaveLength(1)
+ })
+
+ it('an unbound agent survives a daemon restart', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ registry.openAgent({ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo' })
+ const { registry: reloaded } = await loadRegistryModule()
+ reloaded.load()
+ expect(reloaded.byAgent('agent-1')?.sessionId).toBe('')
+ expect(reloaded.unbound()).toHaveLength(1)
+ })
+
+ it('keeps a name given before the agent had a session', async () => {
+ // Names live under the ENGINE session id — that is what survives the launcher and comes back on a
+ // resume, since the agent id is minted fresh each launch. An agent renamed while still unbound has
+ // its name parked under the agent id, and the bind must carry it over.
+ const { registry, projectDisplayName } = await loadRegistryModule()
+ registry.load()
+ registry.openAgent({ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo' })
+ expect(registry.rename('agent-1', 'Backend fix')).toBeTruthy()
+ expect(projectDisplayName(registry.byAgent('agent-1')!)).toBe('Backend fix')
+
+ const bound = registry.register({ launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
+ registry.inheritName('agent-1', 's1')
+ expect(projectDisplayName(bound!.entry)).toBe('Backend fix')
+
+ // …and a LATER agent that resumes the same session inherits it, because the key is the session.
+ registry.removeAgent('agent-1')
+ const resumed = registry.register({ launcherId: 'agent-2', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
+ expect(projectDisplayName(resumed!.entry)).toBe('Backend fix')
+ })
+
+ it('loads a pre-agentId snapshot by reading launcherId as the agent id', async () => {
+ // No migration file and no version gate: every record already carried the launcher uuid, and that
+ // uuid IS the agent id.
+ const path = transcript('legacy')
+ const now = Date.now()
+ writeFileSync(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,
+ lastHookAt: now, lastTranscriptAt: now,
+ }]))
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ expect(registry.byAgent('legacy-agent')?.sessionId).toBe('legacy-session')
+ expect(registry.resolve('legacy-session')?.agentId).toBe('legacy-agent')
+ // …and it is written back with BOTH ids, so rolling back to the previous build still loads it.
+ const saved = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8')) as Array<Record<string, unknown>>
+ expect(saved[0]).toMatchObject({ agentId: 'legacy-agent', launcherId: 'legacy-agent' })
+ })
+})
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
new file mode 100644
index 000000000..f9a36b4f3
--- /dev/null
+++ b/cli/src/lib/registry.ts
@@ -0,0 +1,601 @@
+/**
+ * Registry of AGENTS — one per `harness <engine>` launch.
+ *
+ * An agent is created the moment its launcher opens (its uuid IS the agent id) and lives exactly as long
+ * as that launcher, which is why "N panes running the CLI = N agents" holds at every instant. The ENGINE
+ * session is a mapping bound to the agent afterwards, and rebound whenever the engine rotates it
+ * (`/clear`, `/new`) — the agent, its tab, its name and its place in the list do not move.
+ *
+ * Two indexes, because the outside world speaks both languages: `agentId` for anything the user
+ * addresses, and a bare `sessionId` for turn control (`cancel`, `question_response`, `session_get`).
+ * `resolve()` accepts either. Persisted to disk so a live agent survives a self-update restart.
+ *
+ * Module singleton (like the ws `clients` set) — imported by routes + reaper.
+ */
+
+import { mkdirSync, readFileSync, writeFileSync, renameSync, realpathSync, statSync } from 'fs'
+import { join, basename, dirname, relative } from 'path'
+import { uptime } from 'os'
+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'
+
+export interface ProcessIdentity {
+ pid: number
+ executable: string
+ startMarker: string
+}
+
+/** 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 —
+ * a non-string here reaches runtimeProfile's `.toLowerCase()` and takes the daemon down AT STARTUP, which
+ * no restart can heal because the bad value is on disk. */
+function modelString(value: unknown): string | null {
+ if (typeof value === 'string') return value.slice(0, 200)
+ const id = (value as { id?: unknown } | null)?.id
+ return typeof id === 'string' ? id.slice(0, 200) : null
+}
+
+export interface RegisteredSession {
+ /**
+ * THE AGENT. Public identity: this is what web tabs, device tiles and every inbound frame address.
+ *
+ * It is the launcher's own uuid — minted in `launch.ts` before the engine even starts and sent in the
+ * `open` frame — so an agent exists from the moment the user runs `harness <engine>`, and keeps the same
+ * identity while the engine underneath rotates its session (`/clear`, `/new`). Immutable.
+ */
+ agentId: string
+ /**
+ * The engine session currently BOUND to this agent — internal mapping, not identity. It changes on a
+ * rotation and is only ever addressed through the session index.
+ */
+ sessionId: string
+ /** When the CURRENT sessionId was bound (vs `registeredAt`, which is when the agent appeared). */
+ boundAt: number | null
+ engine: AgentEngine
+ /** Same value as `agentId`. Kept on disk for one release so a rollback to a pre-agentId build still
+ * loads these records (that build drops any entry without it — see load()). */
+ launcherId: string
+ transcriptPath: string | null
+ projectDir: string
+ cwd: string | null
+ tmuxPane: string
+ source: string | null
+ title: string | null
+ model: string | null
+ cliVersion: string | null
+ processIdentity: ProcessIdentity | null
+ registeredAt: number
+ updatedAt: number
+ lastHookAt: number
+ lastTranscriptAt: number
+}
+
+export interface RegisterInput {
+ engine?: AgentEngine
+ /** Set by `hook/notify.mjs` from the `MACHINE_ID` the launcher exported. Required — the hook server
+ * rejects a payload whose id is not a live machine session. */
+ launcherId?: string
+ sessionId?: string
+ transcriptPath?: string
+ cwd?: string
+ source?: string
+ tmuxPane?: string
+ title?: string
+ model?: string
+ cliVersion?: string
+ processIdentity?: ProcessIdentity
+ hookEvent?: string
+}
+
+/** Display name for a session's "project" tab/tile. A user rename (persisted override) is
+ * authoritative and FIXED — it must NOT drift back to the tmux pane title, which Claude keeps
+ * rewriting to the latest convo topic. Only a session the user never renamed auto-follows the title,
+ * then falls back to "<id4> · <folder>". */
+export function projectDisplayName(s: RegisteredSession): string {
+ return NAME_OVERRIDES.get(s.sessionId) || NAME_OVERRIDES.get(s.agentId) || titleDisplayName(s.title) || defaultProjectDisplayName(s)
+}
+
+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 NAME_OVERRIDES = new Map<string, string>()
+
+const PANE_RE = /^%\d+$/
+
+function isWithin(root: string, file: string): boolean {
+ const rel = relative(root, file)
+ return rel === '' || (!rel.startsWith('..') && !rel.startsWith(`/`) && !rel.startsWith(`\\`))
+}
+
+export function validTranscriptPath(engine: AgentEngine, filePath: string): boolean {
+ try {
+ const actual = realpathSync(filePath)
+ const root = realpathSync(
+ engine === 'codex'
+ ? join(env.CODEX_HOME, 'sessions')
+ : engine === 'cursor'
+ ? join(env.CURSOR_HOME, 'projects')
+ : engine === 'pi'
+ ? join(env.PI_HOME, 'agent', 'sessions')
+ : engine === 'commandcode'
+ ? join(env.COMMANDCODE_HOME, 'projects')
+ : env.CLAUDE_PROJECTS_DIR,
+ )
+ const st = statSync(actual)
+ if (!st.isFile() || !isWithin(root, actual)) return false
+ if (engine === 'cursor') {
+ const id = basename(actual).replace(/\.jsonl$/, '')
+ if (!id || basename(dirname(actual)) !== id || basename(dirname(dirname(actual))) !== 'agent-transcripts') return false
+ }
+ const uid = typeof process.getuid === 'function' ? process.getuid() : null
+ return uid === null || st.uid === uid
+ } catch {
+ return false
+ }
+}
+
+/** 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. */
+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 writeBoot(): void {
+ try { mkdirSync(env.ADAPTER_DATA_DIR, { recursive: true }); writeFileSync(BOOT_FILE, String(bootTimeSec())) } catch { /* best effort */ }
+}
+
+class Registry {
+ /** agentId → record. The store. */
+ private agents = new Map<string, RegisteredSession>()
+ /** engine sessionId → agentId. Needed because web and device address turn control with a bare
+ * `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>()
+
+ private index(entry: RegisteredSession): void {
+ this.agents.set(entry.agentId, entry)
+ if (entry.sessionId) this.sessionIndex.set(entry.sessionId, entry.agentId)
+ }
+
+ private drop(entry: RegisteredSession | undefined): void {
+ if (!entry) return
+ this.agents.delete(entry.agentId)
+ if (entry.sessionId && this.sessionIndex.get(entry.sessionId) === entry.agentId) {
+ this.sessionIndex.delete(entry.sessionId)
+ }
+ }
+
+ /** Load persisted entries, dropping any whose transcript file is gone — and, if the computer has
+ * REBOOTED since this snapshot was written, dropping ALL of them (their tmux panes died with the old
+ * tmux server; keeping them would show ghost agents that the reaper can't reap once pane ids collide). */
+ load(): void {
+ this.agents.clear()
+ this.sessionIndex.clear()
+ 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
+ try {
+ const arr = JSON.parse(readFileSync(FILE, 'utf-8')) as RegisteredSession[]
+ 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
+ return
+ }
+ 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 : 'claude'
+ const pane = typeof raw?.tmuxPane === 'string' && PANE_RE.test(raw.tmuxPane) ? raw.tmuxPane : ''
+ let transcriptPath =
+ typeof raw?.transcriptPath === 'string' && raw.transcriptPath
+ ? raw.transcriptPath
+ : null
+ 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'))
+ : null
+ if (!repaired || !validTranscriptPath('codex', repaired) || readCodexRolloutMeta(repaired)?.isSubagent) {
+ changed = true
+ continue
+ }
+ console.log(`[registry] repaired Codex parent ${raw.sessionId.slice(0, 8)} transcript after child hook overwrite`)
+ transcriptPath = repaired
+ repairedCodexTranscript = true
+ changed = true
+ }
+ }
+ // An UNBOUND agent (launcher open, engine hasn't reported a session yet) is a valid record: it has
+ // no transcript to validate, and dropping it here would make a restart lose an agent the user can
+ // see in their pane. Only a BOUND record has to prove its transcript still exists.
+ const bound = typeof raw?.sessionId === 'string' && raw.sessionId !== ''
+ if (!bound) transcriptPath = null
+ if (
+ !pane
+ || (bound && engine !== 'cursor' && engine !== 'opencode' && engine !== 'pi' && engine !== 'hermes' && engine !== 'commandcode' && engine !== 'devin' && !transcriptPath)
+ || (bound && transcriptPath !== null && !validTranscriptPath(engine, transcriptPath))
+ ) {
+ changed = true
+ continue
+ }
+ // Pre-machine-ID snapshots describe sessions nobody owns any more: their lifetime used to hang
+ // off argv heuristics, and there is no launcher process to re-validate them against. Drop them
+ // rather than resurrect an agent that can never be reaped correctly.
+ if (typeof raw?.launcherId !== 'string' || !raw.launcherId) { changed = true; continue }
+ // A snapshot written before agents had their own id still carries `launcherId` — which IS the
+ // agent id. So there is no migration file and no version gate: read one, fall back to the other.
+ const agentId = typeof raw.agentId === 'string' && raw.agentId ? raw.agentId : raw.launcherId
+ if (agentId !== raw.agentId) changed = true
+ const now = Date.now()
+ const s: RegisteredSession = {
+ ...raw,
+ agentId,
+ launcherId: agentId,
+ boundAt: typeof raw.boundAt === 'number' ? raw.boundAt : (raw.registeredAt ?? now),
+ engine,
+ transcriptPath,
+ title: titleDisplayName(typeof raw.title === 'string' ? raw.title : null),
+ sessionId: bound ? raw.sessionId : '',
+ projectDir: !repairedCodexTranscript && typeof raw.projectDir === 'string' && raw.projectDir
+ ? raw.projectDir
+ : transcriptPath
+ ? basename(dirname(transcriptPath))
+ : (bound ? raw.sessionId : agentId),
+ tmuxPane: pane,
+ cliVersion: typeof raw.cliVersion === 'string' ? raw.cliVersion : null,
+ processIdentity: validProcessIdentity(raw.processIdentity) ? raw.processIdentity : null,
+ lastHookAt: typeof raw.lastHookAt === 'number' ? raw.lastHookAt : (raw.updatedAt ?? now),
+ lastTranscriptAt: typeof raw.lastTranscriptAt === 'number' ? raw.lastTranscriptAt : (raw.updatedAt ?? now),
+ }
+ if (
+ raw.engine !== engine
+ || raw.tmuxPane !== pane
+ || raw.transcriptPath !== transcriptPath
+ || raw.title !== s.title
+ || raw.lastHookAt == null
+ || raw.lastTranscriptAt == null
+ ) changed = true
+ // Two records claiming one agent id cannot both be right (the id is per launcher run); 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 }
+ this.index(s)
+ }
+ if (changed) this.save()
+ } catch {
+ // no file yet / unreadable — start empty
+ }
+ }
+
+ private loadNames(): void {
+ try {
+ const obj = JSON.parse(readFileSync(NAMES_FILE, 'utf-8')) as Record<string, unknown>
+ for (const [id, name] of Object.entries(obj)) {
+ if (typeof name === 'string' && name.trim()) NAME_OVERRIDES.set(id, name.trim())
+ }
+ } catch {
+ // no file yet / unreadable — start without display-name overrides
+ }
+ }
+
+ /**
+ * Create the agent for a launcher that just opened, BEFORE any engine session exists.
+ *
+ * This is what makes `harness <engine>` show up the moment it is typed: the launcher's uuid is the
+ * agent, so the agent is real from that instant and the engine session is bound to it later (bindSession
+ * / register). Idempotent — a launcher reconnecting after a daemon restart re-opens the same id and must
+ * not lose the session it had already bound.
+ *
+ * An agent whose `sessionId` is empty is UNBOUND: known, addressable, not yet mapped to a transcript.
+ */
+ openAgent(input: { agentId: string; engine: AgentEngine; tmuxPane: string; cwd?: string | null }):
+ { entry: RegisteredSession; isNew: boolean; evicted: string | null } | null {
+ const { agentId, engine, tmuxPane } = input
+ if (!agentId || !tmuxPane || !PANE_RE.test(tmuxPane)) return null
+ const existing = this.agents.get(agentId)
+ if (existing) {
+ existing.tmuxPane = tmuxPane
+ existing.cwd = input.cwd ?? existing.cwd
+ existing.updatedAt = Date.now()
+ this.save()
+ return { entry: existing, isNew: false, evicted: null }
+ }
+ // Whoever else holds this pane is gone — a launcher only opens a pane it is running in.
+ 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 }
+ }
+ const now = Date.now()
+ const entry: RegisteredSession = {
+ agentId,
+ sessionId: '',
+ boundAt: null,
+ engine,
+ launcherId: agentId,
+ transcriptPath: null,
+ projectDir: basename(input.cwd ?? '') || agentId,
+ cwd: input.cwd ?? null,
+ tmuxPane,
+ source: null,
+ title: null,
+ model: null,
+ cliVersion: null,
+ processIdentity: null,
+ registeredAt: now,
+ updatedAt: now,
+ lastHookAt: now,
+ lastTranscriptAt: now,
+ }
+ this.index(entry)
+ this.save()
+ return { entry, isNew: true, evicted }
+ }
+
+ /** Agents this launcher opened that have no engine session bound yet. */
+ unbound(): RegisteredSession[] {
+ return this.list().filter((s) => !s.sessionId)
+ }
+
+ /**
+ * Upsert a session. Idempotent — a re-register (e.g. from the UserPromptSubmit catch hook) just
+ * refreshes `updatedAt`. Deduped by tmux pane: one session per pane, so a `/clear` rotation
+ * (SessionEnd of the old id → SessionStart of a new id, same pane) evicts the old one instead of
+ * showing two tiles. Returns { entry, isNew, evicted } — isNew=false on a re-register (so callers
+ * 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 {
+ const transcriptPath = input.transcriptPath
+ const sessionId =
+ input.sessionId || (transcriptPath ? basename(transcriptPath).replace(/\.jsonl$/, '') : '')
+ const engine: AgentEngine =
+ input.engine === 'codex' || input.engine === 'cursor' || input.engine === 'opencode' || input.engine === 'pi' || input.engine === 'hermes' || input.engine === 'commandcode' || input.engine === 'devin' ? input.engine : 'claude'
+ const pane = input.tmuxPane
+ // The machine id may be omitted only when re-registering a session we already know (the catch hook
+ // fires on every prompt and older payloads carried no id) — a NEW session always needs one, because
+ // the id is what binds the session's lifetime to a live launcher.
+ const agentId = input.launcherId || this.bySession(sessionId)?.agentId || ''
+ if (
+ !sessionId
+ || !agentId
+ || !pane
+ || !PANE_RE.test(pane)
+ || (engine !== 'cursor' && engine !== 'opencode' && engine !== 'pi' && engine !== 'hermes' && engine !== 'commandcode' && engine !== 'devin' && !transcriptPath)
+ || (transcriptPath && !validTranscriptPath(engine, transcriptPath))
+ ) return null
+ if (engine === 'codex' && transcriptPath && readCodexRolloutMeta(transcriptPath)?.isSubagent) return null
+
+ const now = Date.now()
+ const existing = this.agents.get(agentId)
+ // `isNew` still means "this SESSION id was not bound here before" — a rotation counts as new, which is
+ // what makes the caller announce the newly bound session. The agent itself may be long-lived.
+ const isNew = !existing || existing.sessionId !== sessionId
+ // A rotation: the same agent (same launcher, same pane) swapping the engine session underneath it.
+ const rebound = existing && existing.sessionId && existing.sessionId !== sessionId ? existing.sessionId : null
+
+ let evicted: string | null = rebound
+ if (!existing && pane) {
+ // A new agent claiming a pane: whoever else holds it is gone (its launcher died without saying so).
+ for (const other of this.agents.values()) {
+ if (other.agentId !== agentId && other.tmuxPane === pane) { this.drop(other); evicted = other.sessionId; break }
+ }
+ }
+ // The same engine session cannot belong to two agents — `claude --resume X` in a second pane. The
+ // newest bind wins; the loser is dropped rather than left pointing at a session it no longer owns.
+ const stolenFrom = this.bySession(sessionId)
+ if (stolenFrom && stolenFrom.agentId !== agentId) {
+ console.log(`[registry] session ${sessionId.slice(0, 8)} moved from agent ${stolenFrom.agentId.slice(0, 8)} to ${agentId.slice(0, 8)}`)
+ this.drop(stolenFrom)
+ evicted = evicted ?? stolenFrom.sessionId
+ }
+
+ // Command Code announces SessionStart BEFORE writing its transcript, and validTranscriptPath stats the
+ // file — so a real path is rejected at that moment and only arrives with the first Stop hook, AFTER the
+ // first turn. Nothing tailed the transcript for that turn, and a transcript-derived turn_started is the
+ // ONLY thing that tells Command Code a message was accepted: every new session's first message reported
+ // "the agent did not accept this message" and produced no recap. Its layout is deterministic, so derive
+ // the path rather than wait to be told. A file that does not exist yet is fine — the watcher starts at
+ // offset 0 and chokidar fires when it appears.
+ const derived = !transcriptPath && engine === 'commandcode'
+ ? commandcodeTranscriptPath(input.cwd ?? existing?.cwd, sessionId)
+ : null
+ const effectiveTranscriptPath = transcriptPath ?? existing?.transcriptPath ?? derived ?? null
+ const entry: RegisteredSession = {
+ agentId,
+ sessionId,
+ boundAt: isNew ? now : existing?.boundAt ?? now,
+ engine,
+ launcherId: agentId,
+ transcriptPath: effectiveTranscriptPath,
+ projectDir: effectiveTranscriptPath
+ ? basename(dirname(effectiveTranscriptPath))
+ : basename(input.cwd ?? existing?.cwd ?? '') || sessionId,
+ cwd: input.cwd ?? existing?.cwd ?? null,
+ tmuxPane: pane,
+ source: input.source ?? existing?.source ?? null,
+ title: titleDisplayName(input.title ?? existing?.title ?? null),
+ model: modelString(input.model) ?? existing?.model ?? null,
+ cliVersion: input.cliVersion ?? existing?.cliVersion ?? null,
+ processIdentity: validProcessIdentity(input.processIdentity)
+ ? input.processIdentity
+ : (/^(?:SessionStart|sessionStart)$/.test(input.hookEvent ?? '') ? null : existing?.processIdentity ?? null),
+ registeredAt: existing?.registeredAt ?? now,
+ updatedAt: now,
+ lastHookAt: now,
+ lastTranscriptAt: existing?.lastTranscriptAt ?? now,
+ }
+ if (rebound) this.sessionIndex.delete(rebound)
+ this.index(entry)
+ this.save()
+ return { entry, isNew, evicted, rebound }
+ }
+
+ remove(sessionId: string): boolean {
+ const entry = this.bySession(sessionId)
+ if (!entry) return false
+ this.drop(entry)
+ this.save()
+ return true
+ }
+
+ /** Drop an agent outright, bound or not. */
+ removeAgent(agentId: string): boolean {
+ const entry = this.agents.get(agentId)
+ if (!entry) return false
+ this.drop(entry)
+ this.save()
+ return true
+ }
+
+ has(sessionId: string): boolean {
+ return this.sessionIndex.has(sessionId)
+ }
+
+ byAgent(agentId: string): RegisteredSession | undefined {
+ return this.agents.get(agentId)
+ }
+
+ bySession(sessionId: string): RegisteredSession | undefined {
+ const agentId = this.sessionIndex.get(sessionId)
+ return agentId ? this.agents.get(agentId) : undefined
+ }
+
+ /** The one lookup for anything that arrives from outside: web and device address an agent by `agentId`
+ * for most things but by a bare `sessionId` for turn control, and both must land on the same record. */
+ resolve(id: string): RegisteredSession | undefined {
+ return this.agents.get(id) ?? this.bySession(id)
+ }
+
+ get(sessionId: string): RegisteredSession | undefined {
+ return this.bySession(sessionId)
+ }
+
+ updateProcessIdentity(sessionId: string, processIdentity: ProcessIdentity): boolean {
+ const session = this.resolve(sessionId)
+ if (!session || !validProcessIdentity(processIdentity)) return false
+ session.processIdentity = processIdentity
+ session.updatedAt = Date.now()
+ this.save()
+ return true
+ }
+
+ touchTranscript(sessionId: string, at = Date.now()): boolean {
+ const session = this.bySession(sessionId)
+ if (!session) return false
+ session.lastTranscriptAt = at
+ session.updatedAt = Math.max(session.updatedAt, at)
+ this.save()
+ return true
+ }
+
+ updateTitle(sessionId: string, title: string | null): RegisteredSession | null {
+ const session = this.resolve(sessionId)
+ if (!session) return null
+ const next = titleDisplayName(title)
+ const current = titleDisplayName(session.title)
+ if (next === current) return session
+ session.title = next
+ session.updatedAt = Date.now()
+ this.save()
+ return session
+ }
+
+ displayName(s: RegisteredSession): string {
+ return projectDisplayName(s)
+ }
+
+ /**
+ * Carry a user-chosen name from one session id to another.
+ *
+ * For a session ROTATION: `/clear` in claude (and `/new` in opencode) ends one session id and starts
+ * another in the same pane, under the same launcher. That is the same agent to the person watching it,
+ * so the name they gave it has to come along — otherwise clearing the context silently renames their
+ * agent back to a default.
+ */
+ inheritName(fromSessionId: string, toSessionId: string): void {
+ const name = NAME_OVERRIDES.get(fromSessionId)
+ if (!name || NAME_OVERRIDES.has(toSessionId)) return
+ NAME_OVERRIDES.set(toSessionId, name)
+ this.saveNames()
+ }
+
+ rename(id: string, name: string): RegisteredSession | null {
+ const s = this.resolve(id)
+ if (!s) return null
+ const trimmed = name.trim()
+ if (!trimmed) return null
+ // Names are stored under the ENGINE session id on purpose: that is what makes `claude --resume <id>`
+ // come back wearing the name the user gave it, even though the resume is a brand-new agent.
+ NAME_OVERRIDES.set(s.sessionId || s.agentId, trimmed)
+ this.saveNames()
+ return s
+ }
+
+ list(): RegisteredSession[] {
+ return Array.from(this.agents.values())
+ }
+
+ flush(): void {
+ this.save()
+ this.saveNames()
+ }
+
+ private save(): void {
+ 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)
+ } catch (err) {
+ console.error('[registry] save failed:', err)
+ }
+ }
+
+ private saveNames(): void {
+ try {
+ mkdirSync(env.ADAPTER_DATA_DIR, { recursive: true })
+ let existing: Record<string, string> = {}
+ try {
+ const obj = JSON.parse(readFileSync(NAMES_FILE, 'utf-8')) 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))
+ } catch (err) {
+ console.error('[registry] save names failed:', err)
+ }
+ }
+}
+
+export const registry = new Registry()
+
+function defaultProjectDisplayName(s: RegisteredSession): string {
+ const folder = s.cwd ? s.cwd.split('/').filter(Boolean).pop() || s.cwd : s.projectDir
+ return `${(s.sessionId || s.agentId).slice(0, 4)} · ${folder}`
+}
+
+function titleDisplayName(title: string | null | undefined): string | null {
+ const cleaned = title
+ ?.trim()
+ .replace(/^[\s\p{Mark}\p{Punctuation}\p{Symbol}]+/u, '')
+ .trim()
+ .slice(0, 80)
+ return cleaned || null
+}
+
+function validProcessIdentity(value: unknown): value is ProcessIdentity {
+ const p = value as Partial<ProcessIdentity> | null | undefined
+ return !!p && Number.isSafeInteger(p.pid) && (p.pid ?? 0) > 0 && typeof p.executable === 'string' && typeof p.startMarker === 'string'
+}
diff --git a/cli/src/lib/runtimeProfile.spec.ts b/cli/src/lib/runtimeProfile.spec.ts
new file mode 100644
index 000000000..ade670015
--- /dev/null
+++ b/cli/src/lib/runtimeProfile.spec.ts
@@ -0,0 +1,330 @@
+import { mkdtemp, mkdir, rm, writeFile } from 'fs/promises'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import { afterEach, describe, expect, it } from 'vitest'
+import type { RegisteredSession } from './registry.js'
+import {
+ codexEffortAllowed,
+ encodeRuntimeProfile,
+ parseRuntimeProfile,
+ parseCursorModelsOutput,
+ RuntimeProfileManager,
+ supportsNativeRuntimeControl,
+} from './runtimeProfile.js'
+
+const cleanup: string[] = []
+
+afterEach(async () => {
+ await Promise.all(cleanup.splice(0).map((path) => rm(path, { recursive: true, force: true })))
+})
+
+function session(engine: 'claude' | 'codex' | 'cursor'): RegisteredSession {
+ return {
+ 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,
+ 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,
+ }
+}
+
+describe('RuntimeProfileManager', () => {
+ it('limits Codex Max and Ultra to GPT-5.6 models', () => {
+ expect(codexEffortAllowed('gpt-5.6-sol', 'max')).toBe(true)
+ expect(codexEffortAllowed('gpt-5.6-terra', 'ultra')).toBe(true)
+ expect(codexEffortAllowed('codex-auto-review', 'ultra')).toBe(true)
+ expect(codexEffortAllowed('gpt-5.5', 'max')).toBe(false)
+ expect(codexEffortAllowed('gpt-5.3-codex-spark', 'ultra')).toBe(false)
+ expect(codexEffortAllowed('gpt-5.4', 'xhigh')).toBe(true)
+ })
+
+ it('round trips opaque session-scoped profiles', () => {
+ const id = encodeRuntimeProfile({ sessionId: 'session:1', engine: 'codex', model: 'provider/model:v2', effort: 'xhigh' })
+ expect(parseRuntimeProfile(id)).toEqual({
+ id, sessionId: 'session:1', engine: 'codex', model: 'provider/model:v2', effort: 'xhigh',
+ })
+ expect(parseRuntimeProfile('runtime-v1:session%3A1:codex:gpt-5.6-sol@ultra')).toMatchObject({
+ sessionId: 'session:1', engine: 'codex', model: 'gpt-5.6-sol', effort: 'ultra',
+ })
+ expect(parseRuntimeProfile('runtime-v1:%ZZ:codex:model@high')).toBeNull()
+
+ // Every engine that can produce options must also parse them back. Widening the picker to a new
+ // engine and forgetting this line is silent: the id round-trips through web and device fine, then
+ // setProfile rejects it as INVALID_RUNTIME_PROFILE the moment someone picks a row.
+ for (const engine of ['claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin']) {
+ expect(parseRuntimeProfile(`runtime-v1:s1:${engine}:some-model@high`)).toMatchObject({ engine })
+ }
+ expect(parseRuntimeProfile('runtime-v1:cursor-1:cursor:gpt-5.6-sol@none')).toMatchObject({
+ engine: 'cursor', effort: 'none',
+ })
+ })
+
+ it('parses Cursor catalog variants without hardcoding the account model list', () => {
+ const entries = parseCursorModelsOutput([
+ 'Available models',
+ '',
+ 'auto - Auto (current, default)',
+ 'gpt-5.6-sol-none - GPT-5.6 Sol 1M None',
+ 'gpt-5.6-sol-extra-high-fast - GPT-5.6 Sol Extra High Fast',
+ 'claude-opus-4-8-thinking-high - Opus 4.8 1M Thinking',
+ 'gpt-5.3-codex-low - Codex 5.3 Low',
+ 'gpt-5.3-codex - Codex 5.3',
+ 'Tip: ignored',
+ ].join('\n'))
+
+ expect(entries.map((entry) => ({
+ rawId: entry.target.rawId,
+ model: entry.target.modelKey,
+ effort: entry.effort,
+ context: entry.target.context,
+ fast: entry.target.fast,
+ thinking: entry.target.thinking,
+ }))).toEqual([
+ { rawId: 'auto', model: 'auto', effort: 'auto', context: null, fast: null, thinking: null },
+ { rawId: 'gpt-5.6-sol-none', model: 'gpt-5.6-sol', effort: 'none', context: '1m', fast: false, thinking: false },
+ { rawId: 'gpt-5.6-sol-extra-high-fast', model: 'gpt-5.6-sol-fast', effort: 'xhigh', context: null, fast: true, thinking: false },
+ { rawId: 'claude-opus-4-8-thinking-high', model: 'claude-opus-4-8-thinking', effort: 'high', context: '1m', fast: false, thinking: true },
+ { rawId: 'gpt-5.3-codex-low', model: 'gpt-5.3-codex', effort: 'low', context: null, fast: false, thinking: false },
+ { rawId: 'gpt-5.3-codex', model: 'gpt-5.3-codex', effort: 'medium', context: null, fast: false, thinking: false },
+ ])
+ })
+
+ it('offers no switching outside Claude and Codex', async () => {
+ // View-only engines still SHOW what they run (the ingest paths do that); they just have nothing to
+ // pick and nothing to drive. Both gates are asserted: an empty catalogue, and a refusal to control.
+ const manager = new RuntimeProfileManager()
+ for (const engine of ['cursor', 'commandcode', 'devin', 'pi', 'opencode', 'hermes'] as const) {
+ const value = { ...session('cursor'), engine }
+ expect(supportsNativeRuntimeControl(value)).toBe(false)
+ await expect(manager.modelsForSession(value)).resolves.toEqual([])
+ }
+ })
+
+ it('supports both captured Codex picker generations', () => {
+ const value = session('codex')
+ expect(supportsNativeRuntimeControl(value)).toBe(true)
+ value.cliVersion = '0.145.0'
+ expect(supportsNativeRuntimeControl(value)).toBe(true)
+ value.cliVersion = '0.146.0'
+ expect(supportsNativeRuntimeControl(value)).toBe(false)
+ })
+
+ it('surfaces a Cursor model from the transcript even before any effort is known', () => {
+ // Regression: selectedModel() returns null unless BOTH axes are known, and Cursor's transcript
+ // reports the model while the reasoning level exists only in the pane footer. The model was
+ // therefore discarded whenever the footer had not been read yet, and the device showed no model
+ // at all for a Cursor agent.
+ const manager = new RuntimeProfileManager()
+ const value = session('cursor')
+ manager.hydrate(value, [])
+
+ manager.ingest(value, JSON.stringify({ model: 'gpt-5.6-sol' }))
+
+ expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({
+ engine: 'cursor',
+ model: 'gpt-5.6-sol',
+ effort: 'auto',
+ })
+ })
+
+ it('observes Cursor Auto model and effort from the idle footer with context usage', () => {
+ const manager = new RuntimeProfileManager()
+ const value = session('cursor')
+ manager.hydrate(value, [])
+
+ manager.ingestPane(value, [
+ 'previous output',
+ '→ Add a follow-up',
+ '',
+ 'Auto · 12.7% Run Everything',
+ '~/demo · main',
+ ].join('\n'))
+
+ expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({
+ model: 'auto',
+ effort: 'auto',
+ })
+ })
+
+ it('observes Cursor native-default models from usage and No Thinking footers', () => {
+ const manager = new RuntimeProfileManager()
+ const value = session('cursor')
+ manager.hydrate(value, [])
+
+ manager.ingestPane(value, [
+ '→ Add a follow-up',
+ '',
+ 'Haiku 4.5 · 12.8% Run Everything',
+ '~/demo · main',
+ ].join('\n'))
+ expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({
+ model: 'haiku-4.5',
+ effort: 'auto',
+ })
+
+ manager.ingestPane(value, '→ Add a follow-up\nSonnet 4.5 No Thinking')
+ expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({
+ model: 'sonnet-4.5',
+ effort: 'auto',
+ })
+ })
+
+ it('keeps synthetic Cursor routing details out of the public runtime profile', () => {
+ const manager = new RuntimeProfileManager()
+ const value = session('cursor')
+ manager.hydrate(value, [])
+
+ manager.ingestPane(value, [
+ '→ Add a follow-up',
+ '',
+ 'Composer 2.5 · 15.7% Run Everything',
+ '~/demo · main',
+ ].join('\n'))
+
+ expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({
+ model: 'composer-2.5',
+ effort: 'auto',
+ })
+
+ manager.ingestPane(value, '→ Add a follow-up\nComposer 2.5 1M Thinking Fast High')
+ expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({
+ model: 'composer-2.5-1m-thinking-fast',
+ effort: 'high',
+ })
+ })
+
+ it('observes Claude model from JSONL and effort from the live pane', () => {
+ const manager = new RuntimeProfileManager()
+ const value = session('claude')
+ manager.hydrate(value, [JSON.stringify({ type: 'assistant', message: { model: 'claude-opus-4-8' } })])
+ expect(manager.selectedModel(value)).toBeNull()
+
+ manager.ingestPane(value, 'Opus 4.8 (1M context) with high effort\n❯ ')
+ expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({
+ model: 'opus', effort: 'high',
+ })
+ })
+
+ it('hydrates Claude effort from effective settings and backfills the transcript CLI version', async () => {
+ const cwd = await mkdtemp(join(tmpdir(), 'machine-runtime-'))
+ cleanup.push(cwd)
+ await mkdir(join(cwd, '.claude'))
+ await writeFile(join(cwd, '.claude', 'settings.local.json'), JSON.stringify({ effortLevel: 'low' }))
+ const manager = new RuntimeProfileManager()
+ const value = { ...session('claude'), cwd, cliVersion: null }
+ manager.hydrate(value, [JSON.stringify({
+ type: 'assistant', version: '2.1.212', message: { model: 'claude-opus-4-8' },
+ })])
+
+ await manager.ingestConfig(value, true)
+
+ expect(value.cliVersion).toBe('2.1.212')
+ expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({ model: 'opus', effort: 'low' })
+ })
+
+ it('keeps supported Claude effort on a local model change and falls back to auto otherwise', () => {
+ const manager = new RuntimeProfileManager()
+ const value = session('claude')
+ manager.hydrate(value, [])
+ manager.ingestPane(value, 'Opus 4.8 with high effort\n❯ ', true)
+
+ manager.ingest(value, JSON.stringify({ message: { content: [{ text: 'Set model to Sonnet 5' }] } }))
+ expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({ model: 'sonnet', effort: 'high' })
+
+ manager.ingest(value, JSON.stringify({ message: { content: [{ text: 'Set model to Haiku 4.5' }] } }))
+ expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({ model: 'haiku', effort: 'auto' })
+ })
+
+ // Opus 5 shipped as a new family version AND as a 1M-context variant. Both had to stop resetting the
+ // observed effort: the effort table used to hardcode `opus-4-[78]` and never stripped the `[1m]` suffix,
+ // so `Opus 5 (1M context)` — and even `Opus 4.8 (1M context)` — looked effort-less and fell back to auto.
+ it('keeps Claude effort across a switch to a new family version and to a 1M-context variant', () => {
+ for (const setModel of ['Opus 5', 'Opus 5 (1M context)', 'Opus 4.8 (1M context)', 'Fable 5 (1M context)']) {
+ const manager = new RuntimeProfileManager()
+ const value = session('claude')
+ manager.hydrate(value, [])
+ manager.ingestPane(value, 'Opus 4.8 with high effort\n❯ ', true)
+
+ manager.ingest(value, JSON.stringify({ message: { content: [{ text: `Set model to ${setModel}` }] } }))
+ expect(parseRuntimeProfile(manager.selectedModel(value))?.effort, setModel).toBe('high')
+ }
+ })
+
+ it('observes an Opus 5 pane status line (model + effort)', () => {
+ const manager = new RuntimeProfileManager()
+ const value = session('claude')
+ manager.hydrate(value, [])
+ manager.ingestPane(value, 'Opus 5 (1M context) with high effort\n❯ ')
+ expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({ model: 'opus', effort: 'high' })
+ })
+
+ it('publishes Claude aliases in native picker order without provider-model duplicates', async () => {
+ const manager = new RuntimeProfileManager()
+ const value = session('claude')
+ manager.hydrate(value, [JSON.stringify({
+ type: 'assistant', message: { model: 'claude-opus-4-8' },
+ })])
+ manager.ingestPane(value, 'Opus 4.8 with high effort\n❯ ', true)
+
+ const profiles = (await manager.modelsForSession(value))
+ .map((option) => parseRuntimeProfile(option.id))
+ .filter((profile): profile is NonNullable<typeof profile> => profile !== null)
+ expect([...new Set(profiles.map((profile) => profile.model))]).toEqual([
+ 'default', 'opus', 'fable', 'sonnet', 'haiku',
+ ])
+ expect(profiles.filter((profile) => profile.model === 'sonnet').map((profile) => profile.effort)).toContain('ultracode')
+ expect(profiles.filter((profile) => profile.model === 'haiku').map((profile) => profile.effort)).toEqual(['auto'])
+ expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({ model: 'opus' })
+
+ value.cliVersion = '2.1.208'
+ const olderProfiles = (await manager.modelsForSession(value))
+ .map((option) => parseRuntimeProfile(option.id))
+ .filter((profile): profile is NonNullable<typeof profile> => profile !== null)
+ expect(olderProfiles.map((profile) => profile.effort)).not.toContain('ultracode')
+ })
+
+ it('observes Claude ultracode effort from JSONL and the live footer', () => {
+ const manager = new RuntimeProfileManager()
+ const value = session('claude')
+ manager.hydrate(value, [])
+ manager.ingestPane(value, 'Opus 4.8 with high effort\n❯ ', true)
+
+ manager.ingest(value, JSON.stringify({
+ type: 'user', message: { content: '<local-command-stdout>Set effort level to ultracode (this session only): xhigh + dynamic workflow orchestration</local-command-stdout>' },
+ }))
+ expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({ model: 'opus', effort: 'ultracode' })
+
+ manager.confirmEffort(value.sessionId, 'auto')
+ manager.ingestPane(value, 'old output\n──────────────── ultracode ─\n❯\n────────────────', true)
+ expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({ model: 'opus', effort: 'ultracode' })
+ })
+
+ it('observes Codex model, effort, and plan mode from rollout settings', () => {
+ const manager = new RuntimeProfileManager()
+ const value = session('codex')
+ manager.hydrate(value, [JSON.stringify({ type: 'session_meta', payload: { cli_version: '0.144.5' } })])
+ manager.ingest(value, JSON.stringify({
+ type: 'event_msg',
+ payload: {
+ type: 'thread_settings_applied',
+ thread_settings: { model: 'gpt-5.6-sol', reasoning_effort: 'high', collaboration_mode: { mode: 'plan' } },
+ },
+ }))
+
+ expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({ model: 'gpt-5.6-sol', effort: 'high' })
+ expect(manager.getState(value.sessionId).mode).toBe('plan')
+ expect(value.cliVersion).toBe('0.144.5')
+ })
+
+ it('observes Codex ultra effort from rollout and pane state', () => {
+ const manager = new RuntimeProfileManager()
+ const value = session('codex')
+ manager.hydrate(value, [])
+ manager.ingest(value, JSON.stringify({
+ type: 'turn_context', payload: { model: 'gpt-5.6-sol', reasoning_effort: 'ultra' },
+ }))
+ expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({ effort: 'ultra' })
+
+ manager.ingestPane(value, '› \ngpt-5.6-sol ultra ·', true)
+ expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({ effort: 'ultra' })
+ })
+})
diff --git a/cli/src/lib/runtimeProfile.ts b/cli/src/lib/runtimeProfile.ts
new file mode 100644
index 000000000..a50d88b41
--- /dev/null
+++ b/cli/src/lib/runtimeProfile.ts
@@ -0,0 +1,1496 @@
+import { readFile } from 'fs/promises'
+import { dirname, join } from 'path'
+import { execFile } from 'child_process'
+import { promisify } from 'util'
+import { env } from '../config/env.js'
+import type { AgentEngine } from '../engines/types.js'
+import type { RegisteredSession } from './registry.js'
+import {
+ DEVIN_EFFORTS,
+ devinFooterModel,
+ parseDevinModelsOutput,
+ type DevinModelTarget,
+} from '../engines/devin/runtimeProfile.js'
+import {
+ HERMES_EFFORTS,
+ hermesStatusModel,
+ parseHermesConfig,
+ parseHermesModelsCache,
+ type HermesModelTarget,
+} from '../engines/hermes/runtimeProfile.js'
+import {
+ COMMANDCODE_EFFORTS,
+ commandcodeBannerModel,
+ COMMANDCODE_EFFORT_LEVELS,
+ parseCommandcodeModelsOutput,
+ type CommandcodeModelTarget,
+} from '../engines/commandcode/runtimeProfile.js'
+import {
+ opencodeFooterModelId,
+ parseOpencodeModelsOutput,
+ type OpencodeModelTarget,
+} from '../engines/opencode/runtimeProfile.js'
+import {
+ PI_EFFORTS,
+ PI_THINKING_LEVELS,
+ parsePiFooterProfile,
+ parsePiModelsOutput,
+} from '../engines/pi/runtimeProfile.js'
+
+export interface RuntimeProfile {
+ id: string
+ sessionId: string
+ engine: AgentEngine
+ model: string
+ effort: string
+}
+
+export interface RuntimeModelOption {
+ id: string
+ displayName: string
+}
+
+export interface RuntimeState {
+ model: string | null
+ effort: string | null
+ mode: 'default' | 'plan' | 'unknown'
+ cliVersion: string | null
+ observedAt: number | null
+}
+
+export interface CursorModelTarget {
+ rawId: string
+ modelKey: string
+ familyLabel: string
+ context: string | null
+ reasoning: string | null
+ fast: boolean | null
+ thinking: boolean | null
+ /** Effort text rendered in the idle footer; null means Cursor omits its native default. */
+ footerEffort?: string | null
+}
+
+interface CursorCatalogEntry {
+ target: CursorModelTarget
+ effort: string
+ modelLabel: string
+}
+
+interface RuntimeControl {
+ target: RuntimeProfile
+ before: string | null
+ modelConfirmed: boolean
+ effortConfirmed: boolean
+}
+
+interface StateWaiter {
+ check: () => boolean
+ resolve: (matched: boolean) => void
+ timer: NodeJS.Timeout
+}
+
+interface CodexCacheModel {
+ slug?: unknown
+ display_name?: unknown
+ visibility?: unknown
+ supported_reasoning_levels?: Array<{ effort?: unknown }>
+}
+
+interface CodexCache {
+ models?: CodexCacheModel[]
+}
+
+const PROFILE_RE = /^runtime-v1:([^:]+):(claude|codex|cursor|commandcode|pi|devin|opencode|hermes):([^@]+)@([a-z0-9_-]+)$/i
+const CODEX_EFFORTS = new Set(['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'])
+const CLAUDE_EFFORTS = new Set(['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])
+const CURSOR_EFFORTS = new Set(['auto', 'none', 'low', 'medium', 'high', 'xhigh', 'max'])
+const EFFORTS = new Set([
+ ...CODEX_EFFORTS, ...CLAUDE_EFFORTS, ...CURSOR_EFFORTS, ...PI_EFFORTS, ...DEVIN_EFFORTS,
+ ...COMMANDCODE_EFFORTS, ...HERMES_EFFORTS,
+])
+/**
+ * Versions whose model UI was driven by hand before wiring it up. Open-ended upward: a newer CLI is
+ * assumed compatible (the alternative — refusing to switch after every auto-update — is worse), but a
+ * KNOWN-older one is refused rather than driven blind.
+ */
+const DEVIN_CONTROL_MIN_VERSION: [number, number, number] = [3000, 3, 22]
+const PI_CONTROL_MIN_VERSION: [number, number, number] = [0, 82, 0]
+const OPENCODE_CONTROL_MIN_VERSION: [number, number, number] = [1, 18, 7]
+/**
+ * 1.6.0 is the first Command Code that can be driven at all: it added `--list-models` (a catalog on
+ * stdout) and made `/model <id>` and `/effort <level>` take arguments. On 1.5 and older the only route was
+ * arrow-driving a 49-row picker, which is exactly what got the first attempt reverted — so older builds
+ * are refused rather than driven.
+ */
+const COMMANDCODE_CONTROL_MIN_VERSION: [number, number, number] = [1, 6, 0]
+/**
+ * Hermes ships no version its hook payload exposes, and its `/model` picker has been the same two-level
+ * arrow list throughout — so it is gated on the picker being recognisable rather than on a number. The
+ * driver refuses to move if it cannot read the cursor (see setHermes), which is the real safety net.
+ */
+const HERMES_CONTROL_UNVERSIONED = true
+/**
+ * Cap on how many rows an engine's catalog may contribute. Devin publishes 166 across 72 families, and a
+ * 49-row picker was enough to stall the device's the device UI task into a watchdog reset (see the Command Code
+ * revert, 2026-07-30). The device already truncates at CATALOG_MAX/PICK_MAX, but truncation there is
+ * arbitrary — bounding here keeps the rows we DO send meaningful (see devinModels).
+ */
+const CATALOG_LIMIT = 96
+const BASIC_EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'] as const
+const CLAUDE_ALIASES = ['default', 'opus', 'fable', 'sonnet', 'haiku'] as const
+const CHANGE_DEBOUNCE_MS = 120
+const CLAUDE_ULTRACODE_MIN_VERSION: [number, number, number] = [2, 1, 209]
+const CURSOR_CONTROLLED_BUILD = '2026.07.20-8cc9c0b'
+const CURSOR_CATALOG_TTL_MS = 5 * 60_000
+/** Shared TTL for the stdout catalogs (devin, pi) — same rationale as the cursor one. */
+const CATALOG_TTL_MS = 5 * 60_000
+const execFileAsync = promisify(execFile)
+
+function decode(value: string): string | null {
+ try {
+ const out = decodeURIComponent(value)
+ return out ? out : null
+ } catch {
+ return null
+ }
+}
+
+export function encodeRuntimeProfile(profile: Omit<RuntimeProfile, 'id'>): string {
+ return `runtime-v1:${encodeURIComponent(profile.sessionId)}:${profile.engine}:${encodeURIComponent(profile.model)}@${profile.effort}`
+}
+
+export function parseRuntimeProfile(value: unknown): RuntimeProfile | null {
+ if (typeof value !== 'string') return null
+ const match = PROFILE_RE.exec(value)
+ if (!match) return null
+ const sessionId = decode(match[1])
+ const model = decode(match[3])
+ const effort = match[4].toLowerCase()
+ if (!sessionId || !model || !EFFORTS.has(effort)) return null
+ return {
+ id: value,
+ sessionId,
+ engine: match[2].toLowerCase() as AgentEngine,
+ model,
+ effort,
+ }
+}
+
+function record(value: unknown): Record<string, unknown> | null {
+ return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null
+}
+
+function text(value: unknown): string {
+ return typeof value === 'string' ? value : ''
+}
+
+function stripAnsi(value: string): string {
+ return value.replace(/\u001b\[[0-9;:]*[A-Za-z]/g, '')
+}
+
+function flattenContent(value: unknown): string {
+ if (typeof value === 'string') return value
+ if (!Array.isArray(value)) return ''
+ return value.map((item) => {
+ if (typeof item === 'string') return item
+ const obj = record(item)
+ return text(obj?.text) || text(obj?.content)
+ }).filter(Boolean).join('\n')
+}
+
+function confirmsClaudeAutoEffort(content: string): boolean {
+ return [
+ /\b(?:set|reset)\b.{0,40}\b(?:effort level|effort)\b.{0,40}\b(?:auto|model default)\b/i,
+ /\b(?:effort level|effort)\b.{0,40}\b(?:set|reset)\b.{0,40}\b(?:auto|model default)\b/i,
+ /\busing\b.{0,40}\bauto\b.{0,40}\beffort\b/i,
+ ].some((pattern) => pattern.test(content))
+}
+
+function parseVersion(value: string | null): [number, number, number] | null {
+ const match = /(?:^|\D)(\d+)\.(\d+)\.(\d+)(?:\D|$)/.exec(value ?? '')
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null
+}
+
+function versionAtLeast(value: string | null, wanted: [number, number, number]): boolean {
+ const parsed = parseVersion(value)
+ if (!parsed) return false
+ for (let i = 0; i < wanted.length; i++) {
+ if (parsed[i] !== wanted[i]) return parsed[i] > wanted[i]
+ }
+ return true
+}
+
+export function supportsNativeRuntimeControl(session: RegisteredSession): boolean {
+ // Switching is Claude and Codex only (owner, 2026-07-31); everything else is view-only, so it never gets
+ // here with anything to apply. This is the second gate rather than the only one — modelsForSession
+ // already returns an empty catalogue for those engines — because a stale profile id from an older device
+ // would otherwise still drive a CLI the owner took off the switchable list.
+ if (session.engine === 'claude') return versionAtLeast(session.cliVersion, [2, 1, 153])
+ if (session.engine !== 'codex') return false
+ if (session.engine !== 'codex') return false
+ const version = parseVersion(session.cliVersion)
+ return !!version && version[0] === 0 && (version[1] === 144 || version[1] === 145)
+}
+
+export function codexEffortAllowed(model: string, effort: string): boolean {
+ if (!CODEX_EFFORTS.has(effort)) return false
+ if (effort !== 'max' && effort !== 'ultra') return true
+ return /^gpt-5\.6(?:-|$)/i.test(model) || model.toLowerCase() === 'codex-auto-review'
+}
+
+function titlePart(value: string): string {
+ if (/^gpt$/i.test(value)) return 'GPT'
+ if (/^xhigh$/i.test(value)) return 'XHigh'
+ return value.charAt(0).toUpperCase() + value.slice(1)
+}
+
+export function runtimeModelLabel(model: string): string {
+ const alias = /^(default|best|fable|opus|sonnet|haiku)(\[1m\])?$/i.exec(model)
+ if (alias) return `${titlePart(alias[1].toLowerCase())}${alias[2] ?? ''}`
+ return model.split(/[-_]/).filter(Boolean).map(titlePart).join(' ')
+}
+
+function effortLabel(effort: string): string {
+ return effort === 'xhigh' ? 'XHigh' : titlePart(effort)
+}
+
+function cursorEffortFromId(rawId: string): { effort: string | null; modelKey: string } {
+ const parts = rawId.split('-')
+ let index = -1
+ let width = 1
+ for (let i = 2; i < parts.length; i++) {
+ if (parts[i] === 'extra' && parts[i + 1] === 'high') {
+ index = i
+ width = 2
+ i++
+ } else if (['none', 'low', 'medium', 'high', 'xhigh', 'max'].includes(parts[i])) {
+ index = i
+ width = 1
+ }
+ }
+ if (index < 0) return { effort: null, modelKey: rawId }
+ const rawEffort = parts.slice(index, index + width).join('-')
+ parts.splice(index, width)
+ return {
+ effort: rawEffort === 'extra-high' ? 'xhigh' : rawEffort,
+ modelKey: parts.join('-'),
+ }
+}
+
+function cursorEffortFromDisplay(value: string): string | null {
+ const match = /\b(Extra High|None|Low|Medium|High|Max)\b/i.exec(value)
+ if (!match) return null
+ return match[1].toLowerCase().replace(/\s+/g, '') === 'extrahigh'
+ ? 'xhigh'
+ : match[1].toLowerCase()
+}
+
+function cursorDisplayParts(displayName: string): {
+ familyLabel: string
+ context: string | null
+ fast: boolean
+ thinking: boolean
+} {
+ let value = displayName
+ .replace(/\s+\((?:current|default)(?:,\s*(?:current|default))?\)\s*$/i, '')
+ .replace(/\s+\(NO ZDR\)\s*$/i, '')
+ .replace(/\s*[·│]\s*\d+(?:\.\d+)?%.*$/i, '')
+ .trim()
+ const contextMatch = /\b(\d+(?:\.\d+)?[KM])\b/i.exec(value)
+ const context = contextMatch?.[1].toLowerCase() ?? null
+ const fast = /\bFast\b/i.test(value)
+ const thinking = !/\bNo\s+Thinking\b/i.test(value) && /\bThinking\b/i.test(value)
+ value = value
+ .replace(/\b\d+(?:\.\d+)?[KM]\b/gi, '')
+ .replace(/\bExtra High\b/gi, '')
+ .replace(/\b(?:None|Low|Medium|High|Max)\b/gi, '')
+ .replace(/\bNo\s+Thinking\b/gi, '')
+ .replace(/\b(?:Fast|Thinking)\b/gi, '')
+ .replace(/\s+/g, ' ')
+ .trim()
+ return { familyLabel: value, context, fast, thinking }
+}
+
+/** Strictly parse `agent models`; headings, tips and malformed rows are ignored. */
+export function parseCursorModelsOutput(output: string): CursorCatalogEntry[] {
+ const candidates: Array<CursorCatalogEntry & { explicitEffort: boolean }> = []
+ for (const rawLine of output.split('\n')) {
+ const match = /^([a-z0-9][a-z0-9._-]*) - (.+?)\s*$/i.exec(rawLine)
+ if (!match) continue
+ const rawId = match[1]
+ const displayName = match[2].trim()
+ const display = cursorDisplayParts(displayName)
+ if (!display.familyLabel) continue
+ if (rawId === 'auto') {
+ candidates.push({
+ target: {
+ rawId,
+ modelKey: rawId,
+ familyLabel: 'Auto',
+ context: null,
+ reasoning: null,
+ fast: null,
+ thinking: null,
+ footerEffort: 'auto',
+ },
+ effort: 'auto',
+ modelLabel: 'Auto',
+ explicitEffort: true,
+ })
+ continue
+ }
+ const parsed = cursorEffortFromId(rawId)
+ const effort = parsed.effort
+ const footerEffort = cursorEffortFromDisplay(displayName)
+ candidates.push({
+ target: {
+ rawId,
+ modelKey: parsed.modelKey,
+ familyLabel: display.familyLabel,
+ context: display.context,
+ reasoning: effort,
+ fast: display.fast,
+ thinking: display.thinking,
+ footerEffort,
+ },
+ effort: effort ?? 'auto',
+ modelLabel: [
+ display.familyLabel,
+ display.context ? `(${display.context.toUpperCase()})` : '',
+ display.thinking ? 'Thinking' : '',
+ display.fast ? 'Fast' : '',
+ ].filter(Boolean).join(' '),
+ explicitEffort: effort !== null,
+ })
+ }
+
+ // Some medium/default rows omit the effort segment (for example `gpt-5.3-codex`).
+ // Infer medium only when explicit siblings prove that the same exact model group has efforts.
+ const effortfulGroups = new Set(candidates.filter((item) => item.explicitEffort).map((item) => item.target.modelKey))
+ for (const item of candidates) {
+ if (item.target.rawId === 'auto' || item.effort !== 'auto' || !effortfulGroups.has(item.target.modelKey)) continue
+ item.effort = 'medium'
+ item.target.reasoning = 'medium'
+ }
+ return candidates.map(({ explicitEffort: _explicitEffort, ...item }) => item)
+}
+
+function parseCursorFooter(value: string): {
+ familyLabel: string
+ context: string | null
+ effort: string | null
+ fast: boolean
+ thinking: boolean
+} | null {
+ const line = stripAnsi(value).trim()
+ if (/^Auto(?:\s*$|\s*[·│])/i.test(line)) {
+ return { familyLabel: 'Auto', context: null, effort: 'auto', fast: false, thinking: false }
+ }
+ const effort = cursorEffortFromDisplay(line)
+ const hasUsage = /[·│]\s*\d+(?:\.\d+)?%/i.test(line)
+ const hasThinkingMode = /\b(?:No\s+Thinking|Thinking)\b/i.test(line)
+ if (!effort && !hasUsage && !hasThinkingMode) return null
+ const parts = cursorDisplayParts(line)
+ if (!parts.familyLabel || !/\d/.test(parts.familyLabel)) return null
+ return {
+ ...parts,
+ effort,
+ }
+}
+
+function cursorSyntheticTarget(
+ parsed: NonNullable<ReturnType<typeof parseCursorFooter>>,
+ effort: string,
+): CursorModelTarget {
+ if (parsed.familyLabel.toLowerCase() === 'auto' && parsed.effort === 'auto') {
+ return {
+ rawId: 'auto',
+ modelKey: 'auto',
+ familyLabel: 'Auto',
+ context: null,
+ reasoning: null,
+ fast: null,
+ thinking: null,
+ footerEffort: 'auto',
+ }
+ }
+ const family = parsed.familyLabel.toLowerCase().replace(/[^a-z0-9.]+/g, '-').replace(/^-|-$/g, '') || 'model'
+ // Keep the public runtime-v1 model key compatible with every client formatter. The Cursor routing
+ // details remain on CursorModelTarget (and rawId) for selection/confirmation; they do not belong in
+ // the user-facing profile key as a percent-encoded "[fast=...,thinking=...]" implementation detail.
+ const modelKey = [
+ family,
+ parsed.context?.toLowerCase() ?? '',
+ parsed.thinking ? 'thinking' : '',
+ parsed.fast ? 'fast' : '',
+ ].filter(Boolean).join('-')
+ const parameters = [
+ parsed.context ? `context=${parsed.context}` : '',
+ `fast=${parsed.fast}`,
+ `thinking=${parsed.thinking}`,
+ ].filter(Boolean).join(',')
+ return {
+ rawId: `cursor-${family}[${parameters},effort=${effort}]`,
+ modelKey,
+ familyLabel: parsed.familyLabel,
+ context: parsed.context,
+ reasoning: effort === 'auto' ? null : effort,
+ fast: parsed.fast,
+ thinking: parsed.thinking,
+ footerEffort: parsed.effort,
+ }
+}
+
+function normalizeClaudeDisplay(value: string): string | null {
+ const cleaned = value
+ .replace(/\u001b\[[0-9;]*m/g, '')
+ .replace(/\s+\(default\).*$/i, '')
+ .replace(/\s+and saved.*$/i, '')
+ .replace(/\s+for (?:the )?current session.*$/i, '')
+ .trim()
+ if (!cleaned) return null
+ const alias = /^(default|best|fable|opus|sonnet|haiku)(\[1m\])?$/i.exec(cleaned)
+ if (alias) return `${alias[1].toLowerCase()}${alias[2]?.toLowerCase() ?? ''}`
+ const family = /^(Fable|Opus|Sonnet|Haiku)\s+(\d+(?:\.\d+)*)(?:\s+\(1M context\))?/i.exec(cleaned)
+ if (family) return `claude-${family[1].toLowerCase()}-${family[2].replace(/\./g, '-')}${/1M context/i.test(cleaned) ? '[1m]' : ''}`
+ if (/^claude-[a-z0-9._:-]+(?:\[1m\])?$/i.test(cleaned)) return cleaned.toLowerCase()
+ return null
+}
+
+function claudeAliasForModel(model: string): string | null {
+ const normalized = model.toLowerCase()
+ if ((CLAUDE_ALIASES as readonly string[]).includes(normalized)) return normalized
+ return /^claude-(opus|fable|sonnet|haiku)(?:-|$)/.exec(normalized)?.[1] ?? null
+}
+
+function claudeEfforts(model: string, cliVersion: string | null = null): string[] {
+ // `[1m]` marks the 1M-context variant, not a different model — strip it so `claude-opus-5[1m]` gets
+ // the same efforts as `claude-opus-5` (otherwise a 1M model looked effort-less and a /model switch
+ // reset the observed effort to `auto`). The version match is open-ended (4.7/4.8, then 5+) so a new
+ // release like Opus 5 works without a code change.
+ const normalized = model.toLowerCase().replace(/\[1m\]$/, '')
+ let efforts: string[] = []
+ if (/^claude-(?:opus|fable|sonnet)-(?:4-[78]|[5-9]|\d{2,})(?:-|$)/.test(normalized)) efforts = [...BASIC_EFFORTS]
+ else if (/^claude-(?:opus|sonnet)-4-6(?:-|$)/.test(normalized)) efforts = ['low', 'medium', 'high', 'max']
+ else if (/^(?:fable|opus|sonnet)$/.test(normalized)) efforts = [...BASIC_EFFORTS]
+ if (efforts.length > 0 && versionAtLeast(cliVersion, CLAUDE_ULTRACODE_MIN_VERSION)) efforts.push('ultracode')
+ return efforts
+}
+
+function availableModelMatches(model: string, allowed: string[]): boolean {
+ if (model === 'default') return true
+ if (allowed.length === 0) return true
+ const lower = model.toLowerCase()
+ const family = lower.replace(/\[1m\]$/, '')
+ const wantsLongContext = lower.endsWith('[1m]')
+ return allowed.some((item) => {
+ const candidate = item.toLowerCase()
+ const sameFamily = candidate.includes(`-${family}-`) || candidate.endsWith(`-${family}`)
+ const contextMatches = wantsLongContext === /(?:\[1m\]|1m.context)/i.test(candidate)
+ return lower === candidate || lower.startsWith(`${candidate}-`) || lower.startsWith(`${candidate}[`) || (sameFamily && contextMatches)
+ })
+}
+
+function currentPaneUi(paneText: string): string {
+ const lines = paneText.split('\n')
+ const promptIndex = lines.findLastIndex((line) => {
+ const marker = line.search(/[›❯→]/u)
+ return marker >= 0 && !/^\s*\d+\.\s/.test(line.slice(marker + 1))
+ })
+ return (promptIndex >= 0 ? lines.slice(promptIndex) : lines).join('\n')
+}
+
+async function readJson(file: string): Promise<Record<string, unknown> | null> {
+ try { return record(JSON.parse(await readFile(file, 'utf8'))) } catch { return null }
+}
+
+/** Raw file text, or '' when it cannot be read — hermes' config is YAML, not JSON. */
+async function readText(file: string): Promise<string> {
+ try { return await readFile(file, 'utf8') } catch { return '' }
+}
+
+function claudeSettingsFiles(session: RegisteredSession): string[] {
+ const root = dirname(env.CLAUDE_PROJECTS_DIR)
+ const files = [join(root, 'settings.json')]
+ if (session.cwd) {
+ files.push(join(session.cwd, '.claude', 'settings.json'))
+ files.push(join(session.cwd, '.claude', 'settings.local.json'))
+ }
+ return files
+}
+
+async function claudeAvailableModels(session: RegisteredSession): Promise<string[]> {
+ const merged: string[] = []
+ for (const file of claudeSettingsFiles(session)) {
+ const config = await readJson(file)
+ const values = config?.availableModels
+ if (!Array.isArray(values)) continue
+ for (const value of values) if (typeof value === 'string' && !merged.includes(value)) merged.push(value)
+ }
+ return merged
+}
+
+/** Command Code ids are "vendor/name"; everything we store and show uses the name alone. */
+function shortCommandcodeModel(id: string): string {
+ return id.slice(id.lastIndexOf('/') + 1)
+}
+
+/**
+ * Command Code keeps the reasoning level in its GLOBAL config, keyed by the FULL gateway id:
+ * { "model": "deepseek/deepseek-v4-flash", "reasoningEffort": { "deepseek/deepseek-v4-flash": "high" } }
+ * Nothing in the transcript, the pane footer or the session header carries it, so this file is the only
+ * source. It is per MACHINE rather than per session: two agents on the same model necessarily read the same
+ * level. Matching is done on the short name because that is what the running model is stored as.
+ */
+/** The configured level for `model`, or 'auto' when the model has none set. */
+async function commandcodeConfiguredEffort(model: string | null): Promise<{ effort: string; defaultModel: string }> {
+ const config = await readJson(join(env.COMMANDCODE_HOME, 'config.json'))
+ const defaultModel = shortCommandcodeModel(text(config?.model))
+ const efforts = record(config?.reasoningEffort)
+ const wanted = model || defaultModel
+ if (!efforts || !wanted) return { effort: 'auto', defaultModel }
+ for (const [id, level] of Object.entries(efforts)) {
+ if (shortCommandcodeModel(id) !== wanted) continue
+ const normalized = text(level).toLowerCase()
+ if (normalized && normalized !== 'default' && EFFORTS.has(normalized)) return { effort: normalized, defaultModel }
+ }
+ return { effort: 'auto', defaultModel }
+}
+
+async function claudeConfiguredEffort(session: RegisteredSession): Promise<string> {
+ let configured: string | null = null
+ for (const file of claudeSettingsFiles(session)) {
+ const config = await readJson(file)
+ const raw = text(config?.effortLevel) || text(config?.effort)
+ const normalized = raw.toLowerCase() === 'default' ? 'auto' : raw.toLowerCase()
+ if (CLAUDE_EFFORTS.has(normalized)) configured = normalized
+ }
+ return configured ?? 'auto'
+}
+
+function addOption(
+ output: RuntimeModelOption[],
+ seen: Set<string>,
+ session: RegisteredSession,
+ model: string,
+ effort: string,
+ modelLabel = runtimeModelLabel(model),
+): void {
+ // The id inside a `runtime-v1:` string is what the web/device echoes back on a pick, so it is the
+ // AGENT id — the public one — not the engine session that happens to be bound right now.
+ const id = encodeRuntimeProfile({ sessionId: session.agentId, engine: session.engine, model, effort })
+ if (seen.has(id)) return
+ seen.add(id)
+ output.push({ id, displayName: `${modelLabel} / ${effortLabel(effort)}` })
+}
+
+export class RuntimeProfileManager {
+ private readonly states = new Map<string, RuntimeState>()
+ private readonly controls = new Map<string, RuntimeControl>()
+ private readonly waiters = new Map<string, Set<StateWaiter>>()
+ private readonly changeTimers = new Map<string, NodeJS.Timeout>()
+ private readonly cursorTargets = new Map<string, Map<string, CursorModelTarget>>()
+ /** profile id → the exact `/model` argument, per session (devin ids are not derivable from the key). */
+ private readonly devinTargets = new Map<string, Map<string, DevinModelTarget>>()
+ private devinCatalogCache: { key: string; expiresAt: number; entries: DevinModelTarget[] } | null = null
+ private piCatalogCache: { key: string; expiresAt: number; entries: ReturnType<typeof parsePiModelsOutput> } | null = null
+ private opencodeCatalogCache: { key: string; expiresAt: number; entries: OpencodeModelTarget[] } | null = null
+ private commandcodeCatalogCache: { key: string; expiresAt: number; entries: CommandcodeModelTarget[] } | null = null
+ /** profile id → the full `/model` argument (the profile carries the SHORT name the device labels by). */
+ private readonly commandcodeTargets = new Map<string, Map<string, CommandcodeModelTarget>>()
+ private hermesCatalogCache: { key: string; expiresAt: number; entries: HermesModelTarget[] } | null = null
+ /** profile id → the picker page + row a hermes model sits on. */
+ private readonly hermesTargets = new Map<string, Map<string, HermesModelTarget>>()
+ private cursorCatalogCache: { key: string; expiresAt: number; entries: CursorCatalogEntry[] } | null = null
+ private suppressNotifications = 0
+ onChanged: ((sessionId: string) => void) | null = null
+
+ hydrate(session: RegisteredSession, rawLines: string[]): void {
+ this.states.set(session.sessionId, {
+ // Registries written by older builds can hold a non-string model; treat it as unknown instead of
+ // letting it reach claudeAliasForModel and abort startup.
+ model: typeof session.model === 'string' ? session.model : null,
+ effort: null,
+ mode: 'unknown',
+ cliVersion: session.cliVersion,
+ observedAt: null,
+ })
+ for (const line of rawLines) this.ingest(session, line, true)
+ }
+
+ ingest(session: RegisteredSession, rawLine: string, silent = false): boolean {
+ let raw: Record<string, unknown> | null
+ try { raw = record(JSON.parse(rawLine)) } catch { return false }
+ if (!raw) return false
+ const before = this.selectedModel(session)
+ if (session.engine === 'codex') this.ingestCodex(session, raw)
+ else if (session.engine === 'cursor') this.ingestCursor(session, raw)
+ else if (session.engine === 'commandcode') {
+ const model = this.states.get(session.sessionId)?.model ?? null
+ this.ingestCommandcode(session, raw)
+ // The reasoning level is stored PER MODEL, so a model change makes the level we are holding wrong.
+ // Re-read it now instead of showing the previous model's level until the next poll.
+ if ((this.states.get(session.sessionId)?.model ?? null) !== model) {
+ void this.ingestConfig(session, silent).catch(() => undefined)
+ }
+ }
+ else this.ingestClaude(session, raw)
+ const after = this.selectedModel(session)
+ this.wake(session.sessionId)
+ if (!silent && this.suppressNotifications === 0 && before !== after && !this.controls.has(session.sessionId)) this.scheduleChanged(session.sessionId)
+ return before !== after
+ }
+
+ async ingestConfig(session: RegisteredSession, silent = false): Promise<boolean> {
+ if (session.engine === 'hermes') {
+ // Both axes are scalars in config.yaml and neither is announced, so this poll is the only reader.
+ const before = this.selectedModel(session)
+ const state = this.state(session.sessionId)
+ const parsed = parseHermesConfig(await readText(join(env.HERMES_HOME, 'config.yaml')))
+ if (parsed.model) state.model = parsed.model.slice(parsed.model.lastIndexOf('/') + 1)
+ state.effort = parsed.effort ?? 'auto'
+ state.observedAt = Date.now()
+ const after = this.selectedModel(session)
+ this.wake(session.sessionId)
+ if (!silent && this.suppressNotifications === 0 && before !== after && !this.controls.has(session.sessionId)) {
+ this.scheduleChanged(session.sessionId)
+ }
+ return before !== after
+ }
+ if (session.engine === 'opencode') {
+ // The footer only resolves against the catalog, so warm it here — `ingestPane` is synchronous and
+ // cannot fetch, and without this the chip stays blank until the web happens to ask for models.
+ await this.opencodeCatalog()
+ return false
+ }
+ if (session.engine === 'devin') {
+ // Same shape: devin's model exists only as a DISPLAY name in its pane footer, and only the catalog
+ // maps that back to a model key + effort. Warm it on attach so the first pane read resolves.
+ await this.devinCatalog()
+ return false
+ }
+ if (session.engine !== 'claude' && session.engine !== 'commandcode') return false
+ const before = this.selectedModel(session)
+ const state = this.state(session.sessionId)
+ if (session.engine === 'commandcode') {
+ const config = await commandcodeConfiguredEffort(state.model)
+ state.effort = config.effort
+ // Before the agent has answered once there is no transcript line to read the model from; the config's
+ // own model is what a fresh session starts on, so the chip names it instead of falling back to Auto.
+ if (!state.model && config.defaultModel) state.model = config.defaultModel
+ } else {
+ state.effort = await claudeConfiguredEffort(session)
+ }
+ state.observedAt = Date.now()
+ const after = this.selectedModel(session)
+ this.wake(session.sessionId)
+ if (!silent && this.suppressNotifications === 0 && before !== after && !this.controls.has(session.sessionId)) {
+ this.scheduleChanged(session.sessionId)
+ }
+ return before !== after
+ }
+
+ ingestPane(session: RegisteredSession, paneText: string, silent = false): boolean {
+ const before = this.selectedModel(session)
+ const state = this.state(session.sessionId)
+ paneText = stripAnsi(paneText)
+ const currentUi = currentPaneUi(paneText)
+ if (session.engine === 'codex') {
+ const matches = [...paneText.matchAll(/\b(gpt-[a-z0-9][a-z0-9._-]*)\s+(low|medium|high|xhigh|max|ultra|default)\s*[·│]/gi)]
+ const latest = matches[matches.length - 1]
+ if (latest) {
+ state.model = latest[1].toLowerCase()
+ state.effort = latest[2].toLowerCase() === 'default' ? 'auto' : latest[2].toLowerCase()
+ state.observedAt = Date.now()
+ }
+ if (/\bplan mode\b/i.test(currentUi)) state.mode = 'plan'
+ else if (/\b(?:default|work) mode\b/i.test(currentUi)) state.mode = 'default'
+ } else if (session.engine === 'cursor') {
+ if (/Available models|Models matching|— Edit Parameters|Type to filter.*Tab to edit|Esc to go back/i.test(currentUi)) return false
+ const footerLines = currentUi.split('\n')
+ .filter((line) => stripAnsi(line).trim())
+ .slice(-12)
+ .reverse()
+ const parsed = footerLines.map(parseCursorFooter).find((item) => item !== null)
+ if (parsed) {
+ const targets = this.cursorTargets.get(session.sessionId) ?? new Map<string, CursorModelTarget>()
+ let target = [...targets.values()].find((candidate) =>
+ candidate.familyLabel.toLowerCase() === parsed.familyLabel.toLowerCase()
+ && (parsed.effort
+ ? (candidate.reasoning ?? 'auto') === parsed.effort
+ : candidate.footerEffort === null)
+ && (candidate.fast ?? false) === parsed.fast
+ && (candidate.thinking ?? false) === parsed.thinking
+ && (!candidate.context || candidate.context === parsed.context))
+ const effort = parsed.effort ?? target?.reasoning ?? 'auto'
+ if (!target) {
+ target = cursorSyntheticTarget(parsed, effort)
+ const id = encodeRuntimeProfile({
+ sessionId: session.agentId,
+ engine: 'cursor',
+ model: target.modelKey,
+ effort,
+ })
+ targets.set(id, target)
+ this.cursorTargets.set(session.sessionId, targets)
+ }
+ state.model = target.modelKey
+ state.effort = effort
+ state.observedAt = Date.now()
+ const control = this.controls.get(session.sessionId)
+ if (control && target?.modelKey === control.target.model && effort === control.target.effort) {
+ control.modelConfirmed = true
+ control.effortConfirmed = true
+ }
+ }
+ if (/\bPlan\b/i.test(currentUi)) state.mode = 'plan'
+ else if (/Plan, search, build anything/i.test(currentUi)) state.mode = 'default'
+ } else if (session.engine === 'devin') {
+ // Devin writes no transcript unless the user passes `--export`, so the footer's bottom-left cell is
+ // the only per-session record of the running model. It is a DISPLAY name (`SWE-1.6 Slow`); the
+ // catalog resolves it back to a model key so the chip and the picker agree.
+ const label = devinFooterModel(paneText)
+ const model = label ? this.devinModelKeyForLabel(session.sessionId, label) : null
+ if (model) {
+ state.model = model.modelKey
+ state.effort = model.effort
+ state.observedAt = Date.now()
+ this.confirmObserved(session.sessionId, model.modelKey, model.effort)
+ }
+ } else if (session.engine === 'hermes') {
+ // `⚕ minimax-m3 │ ctx --` — the status line is how a switch is seen immediately; config.yaml is
+ // rewritten too, but the poll that reads it runs on its own schedule.
+ const model = hermesStatusModel(paneText)
+ if (model && model !== state.model) {
+ state.model = model
+ state.observedAt = Date.now()
+ }
+ } else if (session.engine === 'commandcode') {
+ // `/model` reprints the session banner (`# models: kimi-k2.6 · taste-1`) with the new model. The
+ // transcript would say the same thing, but only after the NEXT turn runs — too late to confirm a
+ // switch, and long enough for the chip to look stuck.
+ const model = commandcodeBannerModel(paneText)
+ if (model && model !== state.model) {
+ state.model = model
+ state.observedAt = Date.now()
+ // Effort is stored per model in the CLI's global config, so the level we hold belongs to the old
+ // one. Re-read rather than carry it across.
+ void this.ingestConfig(session, true).catch(() => undefined)
+ }
+ } else if (session.engine === 'opencode') {
+ // OpenCode names the model in its composer footer (`Build · MiniMax M3 (vibe) Vibe Gateway …`), which
+ // only resolves against the catalog — hence the cached entries rather than a fresh (async) fetch.
+ const id = opencodeFooterModelId(paneText, this.opencodeCatalogCache?.entries ?? [])
+ if (id) {
+ state.model = id
+ state.effort = 'auto'
+ state.observedAt = Date.now()
+ this.confirmObserved(session.sessionId, id, 'auto')
+ }
+ } else if (session.engine === 'pi') {
+ // Pi puts both axes in one footer cell: `minimax/minimax-m3 • high`.
+ const footer = parsePiFooterProfile(paneText)
+ if (footer) {
+ state.model = footer.model
+ state.effort = footer.effort
+ state.observedAt = Date.now()
+ this.confirmObserved(session.sessionId, footer.model, footer.effort)
+ }
+ } else {
+ const header = /(Fable|Opus|Sonnet|Haiku)\s+(\d+(?:\.\d+)*)(\s+\(1M context\))?\s+with\s+(low|medium|high|xhigh|max|ultracode)\s+effort/gi
+ const matches = [...paneText.matchAll(header)]
+ const latest = matches[matches.length - 1]
+ if (latest) {
+ state.model = `claude-${latest[1].toLowerCase()}-${latest[2].replace(/\./g, '-')}${latest[3] ? '[1m]' : ''}`
+ state.effort = latest[4].toLowerCase()
+ state.observedAt = Date.now()
+ }
+ const footer = paneText.split('\n').slice(-8).join('\n')
+ if (/─+\s*ultracode\s*─+/i.test(footer)) {
+ state.effort = 'ultracode'
+ state.observedAt = Date.now()
+ }
+ if (/\bplan mode on\b/i.test(currentUi)) state.mode = 'plan'
+ else if (/\b(?:auto|default) mode on\b/i.test(currentUi)) state.mode = 'default'
+ }
+ const after = this.selectedModel(session)
+ this.wake(session.sessionId)
+ if (!silent && this.suppressNotifications === 0 && before !== after && !this.controls.has(session.sessionId)) this.scheduleChanged(session.sessionId)
+ return before !== after
+ }
+
+ getState(sessionId: string): RuntimeState {
+ return { ...this.state(sessionId) }
+ }
+
+ async withoutChangeEvents<T>(operation: () => Promise<T>): Promise<T> {
+ this.suppressNotifications++
+ try { return await operation() } finally { this.suppressNotifications-- }
+ }
+
+ selectedModel(session: RegisteredSession): string | null {
+ const state = this.states.get(session.sessionId)
+ if (!state?.model) return null
+ const model = session.engine === 'claude' ? claudeAliasForModel(state.model) ?? state.model : state.model
+ const effort = state.effort ?? (session.engine === 'claude' && claudeEfforts(model).length === 0 ? 'auto' : null)
+ if (!effort) return null
+ return encodeRuntimeProfile({
+ sessionId: session.agentId,
+ engine: session.engine,
+ model,
+ effort,
+ })
+ }
+
+ beginControl(session: RegisteredSession, target: RuntimeProfile): boolean {
+ if (this.controls.has(session.sessionId)) return false
+ const before = this.selectedModel(session)
+ const current = parseRuntimeProfile(before)
+ this.controls.set(session.sessionId, {
+ target,
+ before,
+ modelConfirmed: current?.model === target.model,
+ effortConfirmed: current?.effort === target.effort,
+ })
+ return true
+ }
+
+ cancelControl(sessionId: string): void {
+ const control = this.controls.get(sessionId)
+ this.controls.delete(sessionId)
+ this.wake(sessionId)
+ if (control) this.scheduleChanged(sessionId)
+ }
+
+ finishControl(session: RegisteredSession): void {
+ const control = this.controls.get(session.sessionId)
+ this.controls.delete(session.sessionId)
+ this.wake(session.sessionId)
+ this.scheduleChanged(session.sessionId)
+ }
+
+ confirmEffort(sessionId: string, effort: string): void {
+ if (!EFFORTS.has(effort)) return
+ const state = this.state(sessionId)
+ state.effort = effort
+ state.observedAt = Date.now()
+ const control = this.controls.get(sessionId)
+ if (control) control.effortConfirmed = control.target.effort === effort
+ this.wake(sessionId)
+ }
+
+ confirmControlProfile(target: RuntimeProfile): void {
+ const state = this.state(target.sessionId)
+ state.model = target.model
+ state.effort = target.effort
+ state.observedAt = Date.now()
+ const control = this.controls.get(target.sessionId)
+ if (control?.target.id === target.id) {
+ control.modelConfirmed = true
+ control.effortConfirmed = true
+ }
+ this.wake(target.sessionId)
+ }
+
+ waitForModel(sessionId: string, timeoutMs: number): Promise<boolean> {
+ return this.waitFor(sessionId, () => this.controls.get(sessionId)?.modelConfirmed === true, timeoutMs)
+ }
+
+ waitForProfile(sessionId: string, timeoutMs: number): Promise<boolean> {
+ return this.waitFor(sessionId, () => {
+ const control = this.controls.get(sessionId)
+ return control?.modelConfirmed === true && control.effortConfirmed === true
+ }, timeoutMs)
+ }
+
+ forget(sessionId: string): void {
+ this.states.delete(sessionId)
+ this.controls.delete(sessionId)
+ const timer = this.changeTimers.get(sessionId)
+ if (timer) clearTimeout(timer)
+ this.changeTimers.delete(sessionId)
+ this.cursorTargets.delete(sessionId)
+ for (const waiter of this.waiters.get(sessionId) ?? []) {
+ clearTimeout(waiter.timer)
+ waiter.resolve(false)
+ }
+ this.waiters.delete(sessionId)
+ }
+
+ async modelsForSessions(sessions: RegisteredSession[]): Promise<RuntimeModelOption[]> {
+ const groups = await Promise.all(sessions.map((session) => this.modelsForSession(session)))
+ return groups.flat()
+ }
+
+ /**
+ * Only Claude and Codex can be SWITCHED from the device (owner, 2026-07-31). Every other engine is
+ * view-only: its chip still names the model and effort it is running — that comes from the ingest paths,
+ * not from here — but it offers nothing to pick.
+ *
+ * An empty catalogue is the whole mechanism: the device's picker returns to the projects screen when the
+ * list comes back empty, so this policy lives in one place and needs no firmware change to revise.
+ * The per-engine builders (cursor/opencode/pi/hermes/commandcode/devin) are kept, unused by this path,
+ * because the catalogues they fetch are what the ingest paths resolve pane footers against.
+ */
+ async modelsForSession(session: RegisteredSession): Promise<RuntimeModelOption[]> {
+ if (session.engine === 'codex') return this.codexModels(session)
+ if (session.engine === 'claude') return this.claudeModels(session)
+ return []
+ }
+
+ cursorTarget(sessionId: string, profileId: string): CursorModelTarget | null {
+ return this.cursorTargets.get(sessionId)?.get(profileId) ?? null
+ }
+
+ /** The `/model` argument for a devin profile id — devin's ids do not follow from the model key. */
+ devinTarget(sessionId: string, profileId: string): DevinModelTarget | null {
+ return this.devinTargets.get(sessionId)?.get(profileId) ?? null
+ }
+
+ /** Mark an in-flight control confirmed once the pane shows the profile it asked for. */
+ private confirmObserved(sessionId: string, model: string, effort: string): void {
+ const control = this.controls.get(sessionId)
+ if (!control || control.target.model !== model || control.target.effort !== effort) return
+ control.modelConfirmed = true
+ control.effortConfirmed = true
+ }
+
+ /** Resolve devin's footer display name (`SWE-1.6 Slow`) back to the catalog row it names. */
+ private devinModelKeyForLabel(sessionId: string, label: string): DevinModelTarget | null {
+ // Resolve against the CATALOG, not the per-session id map. That map is only built when something opens
+ // the model picker, so a session nobody had picked on could not read its own footer and the chip stayed
+ // blank. The catalog is the same data minus the per-session ids, and ingestConfig warms it on attach.
+ // The session map stays first: its rows are the ones the picker will offer.
+ const targets = this.devinTargets.get(sessionId)
+ const pool: Iterable<DevinModelTarget> = targets?.size
+ ? targets.values()
+ : this.devinCatalogCache?.entries ?? []
+ const wanted = label.trim().toLowerCase()
+ for (const target of pool) {
+ // A row whose id carries no effort keeps the effort word in its label ("GLM-5.2 High"), so an exact
+ // label match is what identifies it; anything looser would tie the footer to the wrong sibling.
+ if (target.label.toLowerCase() === wanted) return target
+ if (target.effort !== 'auto' && `${target.label} ${effortLabel(target.effort)}`.toLowerCase() === wanted) {
+ return target
+ }
+ }
+ return null
+ }
+
+ private state(sessionId: string): RuntimeState {
+ let state = this.states.get(sessionId)
+ if (!state) {
+ state = { model: null, effort: null, mode: 'unknown', cliVersion: null, observedAt: null }
+ this.states.set(sessionId, state)
+ }
+ return state
+ }
+
+ private ingestCodex(session: RegisteredSession, raw: Record<string, unknown>): void {
+ const state = this.state(session.sessionId)
+ const payload = record(raw.payload)
+ const cliVersion = raw.type === 'session_meta' ? text(payload?.cli_version) : ''
+ if (parseVersion(cliVersion)) {
+ session.cliVersion = cliVersion
+ state.cliVersion = cliVersion
+ }
+ let source: Record<string, unknown> | null = null
+ if (raw.type === 'event_msg' && payload?.type === 'thread_settings_applied') source = record(payload.thread_settings)
+ else if (raw.type === 'turn_context') source = payload
+ if (!source) return
+ const model = text(source.model)
+ const effort = text(source.reasoning_effort) || text(source.effort)
+ const collaboration = record(source.collaboration_mode)
+ const mode = text(collaboration?.mode)
+ if (model) state.model = model
+ if (CODEX_EFFORTS.has(effort.toLowerCase())) state.effort = effort.toLowerCase()
+ if (mode === 'plan' || mode === 'default') state.mode = mode
+ if (model || effort || mode) state.observedAt = Date.now()
+ const control = this.controls.get(session.sessionId)
+ if (control && state.model === control.target.model) {
+ control.modelConfirmed = true
+ if (control.target.effort === 'auto' || state.effort === control.target.effort) control.effortConfirmed = true
+ }
+ }
+
+ private ingestCursor(session: RegisteredSession, raw: Record<string, unknown>): void {
+ const state = this.state(session.sessionId)
+ const version = text(raw.version) || text(raw.cursor_version)
+ if (version) {
+ session.cliVersion = version
+ state.cliVersion = version
+ }
+ const model = text(raw.model)
+ if (model) {
+ state.model = model
+ // Default the effort to 'auto' when we do not have one yet. selectedModel() returns null unless BOTH
+ // axes are known, so without this a Cursor session whose model we DO know shows nothing at all on
+ // the device — the model is thrown away because the effort is missing.
+ //
+ // Cursor reports its model in the transcript but its reasoning level only in the pane footer, so
+ // the effort arrives later (ingestPane) or not at all for a model that has no reasoning levels.
+ // 'auto' is not a guess about Cursor's behaviour: it is exactly how the device renders "not
+ // specified", and the pane path overwrites it with the real value the moment one is read.
+ state.effort ??= 'auto'
+ state.observedAt = Date.now()
+ }
+ }
+
+ private ingestClaude(session: RegisteredSession, raw: Record<string, unknown>): void {
+ const state = this.state(session.sessionId)
+ const cliVersion = text(raw.version)
+ if (parseVersion(cliVersion)) {
+ session.cliVersion = cliVersion
+ state.cliVersion = cliVersion
+ }
+ const message = record(raw.message)
+ const assistantModel = raw.type === 'assistant' ? text(message?.model) : ''
+ if (assistantModel) {
+ state.model = assistantModel
+ state.observedAt = Date.now()
+ }
+ const content = `${flattenContent(message?.content)}\n${flattenContent(raw.content)}`
+ const control = this.controls.get(session.sessionId)
+ const modelMatch = /Set model to\s+(.+?)(?:\n|$)/i.exec(content)
+ if (modelMatch) {
+ const nextModel = control?.target.model ?? normalizeClaudeDisplay(modelMatch[1]) ?? state.model
+ state.model = nextModel
+ if (!control && nextModel && state.effort && !claudeEfforts(nextModel, session.cliVersion).includes(state.effort)) {
+ state.effort = 'auto'
+ }
+ state.observedAt = Date.now()
+ if (control) control.modelConfirmed = true
+ }
+ const effortMatch = /Set effort level to\s+(low|medium|high|xhigh|max|ultracode)/i.exec(content)
+ const effortAuto = confirmsClaudeAutoEffort(content)
+ if (effortMatch || effortAuto) {
+ state.effort = effortMatch?.[1].toLowerCase() ?? 'auto'
+ state.observedAt = Date.now()
+ if (control) control.effortConfirmed = control.target.effort === 'auto' || state.effort === control.target.effort
+ }
+ }
+
+ private async claudeModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {
+ const output: RuntimeModelOption[] = []
+ const seen = new Set<string>()
+ const allowed = await claudeAvailableModels(session)
+ for (const model of CLAUDE_ALIASES) {
+ if (model === 'fable' && !versionAtLeast(session.cliVersion, [2, 1, 170])) continue
+ if (!availableModelMatches(model, allowed)) continue
+ addOption(output, seen, session, model, 'auto')
+ for (const effort of claudeEfforts(model, session.cliVersion)) addOption(output, seen, session, model, effort)
+ }
+ const state = this.states.get(session.sessionId)
+ if (state?.model) {
+ const model = claudeAliasForModel(state.model) ?? state.model
+ addOption(output, seen, session, model, 'auto')
+ for (const effort of claudeEfforts(model, session.cliVersion)) addOption(output, seen, session, model, effort)
+ if (state.effort) addOption(output, seen, session, model, state.effort)
+ }
+ return output
+ }
+
+ private async codexModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {
+ const output: RuntimeModelOption[] = []
+ const seen = new Set<string>()
+ let cache: CodexCache = {}
+ try { cache = JSON.parse(await readFile(join(env.CODEX_HOME, 'models_cache.json'), 'utf8')) as CodexCache } catch { /* current state fallback below */ }
+ for (const item of Array.isArray(cache.models) ? cache.models : []) {
+ const model = text(item.slug)
+ if (!model || item.visibility === 'hide') continue
+ const label = text(item.display_name) || runtimeModelLabel(model)
+ addOption(output, seen, session, model, 'auto', label)
+ for (const level of Array.isArray(item.supported_reasoning_levels) ? item.supported_reasoning_levels : []) {
+ const effort = text(level.effort).toLowerCase()
+ if (CODEX_EFFORTS.has(effort) && effort !== 'auto' && codexEffortAllowed(model, effort)) {
+ addOption(output, seen, session, model, effort, label)
+ }
+ }
+ }
+ const state = this.states.get(session.sessionId)
+ if (state?.model) {
+ addOption(output, seen, session, state.model, 'auto')
+ if (state.effort && codexEffortAllowed(state.model, state.effort)) {
+ addOption(output, seen, session, state.model, state.effort)
+ }
+ }
+ return output
+ }
+
+ /** Command Code stamps the model on every assistant line as the full gateway id
+ * ("deepseek/deepseek-v4-flash"). Store the short name so it matches the catalogue and the chip label.
+ * `raw.version` here is the transcript SCHEMA version (3), not a CLI version — never read it as one. */
+ private ingestCommandcode(session: RegisteredSession, raw: Record<string, unknown>): void {
+ const model = text(raw.model)
+ if (!model) return
+ const state = this.state(session.sessionId)
+ state.model = shortCommandcodeModel(model)
+ // Effort is NOT touched here: it comes from the CLI config (ingestConfig), and stamping 'auto' on every
+ // assistant line would wipe a configured level a second after it was read.
+ state.observedAt = Date.now()
+ }
+
+ private async cursorModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {
+ const key = `${session.cliVersion ?? 'unknown'}\0${process.env.HOME ?? ''}`
+ let entries = this.cursorCatalogCache?.key === key && this.cursorCatalogCache.expiresAt > Date.now()
+ ? this.cursorCatalogCache.entries
+ : null
+ if (!entries) {
+ try {
+ const result = await execFileAsync('agent', ['models'], {
+ env: process.env,
+ timeout: 5_000,
+ maxBuffer: 1024 * 1024,
+ })
+ entries = parseCursorModelsOutput(result.stdout)
+ this.cursorCatalogCache = { key, entries, expiresAt: Date.now() + CURSOR_CATALOG_TTL_MS }
+ } catch (err) {
+ console.warn('[runtime-profile] Cursor model catalog failed:', err instanceof Error ? err.message : err)
+ entries = []
+ }
+ }
+
+ const output: RuntimeModelOption[] = []
+ const previousTargets = this.cursorTargets.get(session.sessionId) ?? new Map<string, CursorModelTarget>()
+ const targets = new Map<string, CursorModelTarget>()
+ const seen = new Set<string>()
+ for (const entry of entries) {
+ if (!CURSOR_EFFORTS.has(entry.effort)) continue
+ const id = encodeRuntimeProfile({
+ sessionId: session.agentId,
+ engine: 'cursor',
+ model: entry.target.modelKey,
+ effort: entry.effort,
+ })
+ if (seen.has(id)) continue
+ seen.add(id)
+ targets.set(id, entry.target)
+ output.push({ id, displayName: `${entry.modelLabel} / ${effortLabel(entry.effort)}` })
+ }
+ const state = this.states.get(session.sessionId)
+ const current = state?.model && state.effort
+ ? encodeRuntimeProfile({
+ sessionId: session.agentId,
+ engine: 'cursor',
+ model: state.model,
+ effort: state.effort,
+ })
+ : null
+ const observed = current ? previousTargets.get(current) : null
+ if (observed) {
+ const familyEfforts = [...new Set(entries
+ .filter((entry) => entry.target.familyLabel.toLowerCase() === observed.familyLabel.toLowerCase())
+ .map((entry) => entry.effort)
+ .filter((effort) => effort !== 'auto'))]
+ const efforts = familyEfforts.length ? familyEfforts : [state!.effort!]
+ for (const effort of efforts) {
+ const id = encodeRuntimeProfile({
+ sessionId: session.agentId,
+ engine: 'cursor',
+ model: observed.modelKey,
+ effort,
+ })
+ if (seen.has(id)) continue
+ seen.add(id)
+ targets.set(id, { ...observed, reasoning: effort, footerEffort: effort })
+ const label = [
+ observed.familyLabel,
+ observed.context ? `(${observed.context.toUpperCase()})` : '',
+ observed.thinking ? 'Thinking' : '',
+ observed.fast ? 'Fast' : '',
+ ].filter(Boolean).join(' ')
+ output.push({ id, displayName: `${label} / ${effortLabel(effort)}` })
+ }
+ }
+ this.cursorTargets.set(session.sessionId, targets)
+ return output
+ }
+
+ /**
+ * Devin's catalog comes from `devin models list` on stdout — no picker to scrape. It is big (166 rows
+ * across 72 models on this account), so it is trimmed to CATALOG_LIMIT, and the model the session is
+ * ACTUALLY running is pinned to the front so trimming can never hide it.
+ */
+ private async devinModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {
+ const entries = await this.devinCatalog()
+ const targets = new Map<string, DevinModelTarget>()
+ const state = this.states.get(session.sessionId)
+ // Keep every row of the running model together with it, so its effort list stays complete.
+ const ordered = state?.model
+ ? [...entries].sort((a, b) => Number(b.modelKey === state.model) - Number(a.modelKey === state.model))
+ : entries
+
+ const output: RuntimeModelOption[] = []
+ const seen = new Set<string>()
+ for (const entry of ordered) {
+ if (output.length >= CATALOG_LIMIT) break
+ if (!DEVIN_EFFORTS.has(entry.effort)) continue
+ const id = encodeRuntimeProfile({
+ sessionId: session.agentId,
+ engine: 'devin',
+ model: entry.modelKey,
+ effort: entry.effort,
+ })
+ if (seen.has(id)) continue
+ seen.add(id)
+ targets.set(id, entry)
+ output.push({ id, displayName: `${entry.label} / ${effortLabel(entry.effort)}` })
+ }
+ this.devinTargets.set(session.sessionId, targets)
+ return output
+ }
+
+ private async devinCatalog(): Promise<DevinModelTarget[]> {
+ const key = env.DEVIN_HOME
+ if (this.devinCatalogCache?.key === key && this.devinCatalogCache.expiresAt > Date.now()) {
+ return this.devinCatalogCache.entries
+ }
+ let entries: DevinModelTarget[] = []
+ try {
+ const result = await execFileAsync('devin', ['models', 'list'], {
+ env: process.env,
+ timeout: 10_000,
+ maxBuffer: 1024 * 1024,
+ })
+ entries = parseDevinModelsOutput(result.stdout)
+ } catch (err) {
+ console.warn('[runtime-profile] Devin model catalog failed:', err instanceof Error ? err.message : err)
+ }
+ this.devinCatalogCache = { key, entries, expiresAt: Date.now() + CATALOG_TTL_MS }
+ return entries
+ }
+
+ /**
+ * Pi lists models on stdout too, and its `thinking` column says which of them accept a reasoning depth —
+ * so effort rows are attached per model instead of assumed. A model that is configured but absent from
+ * the table (the state fallback) still gets its own row so the chip never goes blank.
+ */
+ private async piModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {
+ const entries = await this.piCatalog()
+ const output: RuntimeModelOption[] = []
+ const seen = new Set<string>()
+ for (const entry of entries) {
+ addOption(output, seen, session, entry.model, 'auto', entry.model)
+ if (!entry.thinking) continue
+ for (const level of PI_THINKING_LEVELS) addOption(output, seen, session, entry.model, level, entry.model)
+ }
+ const state = this.states.get(session.sessionId)
+ if (entries.length && state?.model) {
+ addOption(output, seen, session, state.model, 'auto', state.model)
+ if (state.effort && PI_EFFORTS.has(state.effort)) {
+ addOption(output, seen, session, state.model, state.effort, state.model)
+ }
+ }
+ return output
+ }
+
+ /** The picker page + row a hermes profile id points at. */
+ hermesTarget(sessionId: string, profileId: string): HermesModelTarget | null {
+ return this.hermesTargets.get(sessionId)?.get(profileId) ?? null
+ }
+
+ /**
+ * Hermes offers MODELS only. Its reasoning effort lives in `agent.reasoning_effort` in config.yaml with
+ * no in-session command to change it (`/config` only prints), and a running session does not re-read the
+ * file — so an effort row would be a control that silently does nothing. The level is still OBSERVED, so
+ * the chip names it truthfully; it just cannot be picked.
+ */
+ private async hermesModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {
+ const entries = await this.hermesCatalog()
+ const state = this.states.get(session.sessionId)
+ const targets = new Map<string, HermesModelTarget>()
+ const output: RuntimeModelOption[] = []
+ const seen = new Set<string>()
+ const effort = state?.effort && HERMES_EFFORTS.has(state.effort) ? state.effort : 'auto'
+ const add = (entry: HermesModelTarget): void => {
+ const short = entry.id.slice(entry.id.lastIndexOf('/') + 1)
+ const id = encodeRuntimeProfile({
+ sessionId: session.agentId, engine: 'hermes', model: short, effort,
+ })
+ if (seen.has(id)) return
+ seen.add(id)
+ targets.set(id, entry)
+ output.push({ id, displayName: runtimeModelLabel(short) })
+ }
+ for (const entry of entries) add(entry)
+ // The provider in use is often absent from the picker cache (a `custom` gateway is its own one-model
+ // page), so the configured model is always offered — otherwise the running model is missing from its
+ // own list.
+ if (state?.model && !seen.size) add({ id: state.model, provider: '' })
+ else if (state?.model && ![...targets.values()].some((t) => t.id.endsWith(state.model!))) {
+ add({ id: state.model, provider: '' })
+ }
+ this.hermesTargets.set(session.sessionId, targets)
+ return output
+ }
+
+ private async hermesCatalog(): Promise<HermesModelTarget[]> {
+ const key = env.HERMES_HOME
+ if (this.hermesCatalogCache?.key === key && this.hermesCatalogCache.expiresAt > Date.now()) {
+ return this.hermesCatalogCache.entries
+ }
+ const cache = await readJson(join(env.HERMES_HOME, 'provider_models_cache.json'))
+ const entries = parseHermesModelsCache(cache)
+ this.hermesCatalogCache = { key, entries, expiresAt: Date.now() + CATALOG_TTL_MS }
+ return entries
+ }
+
+ /** The full `/model` argument for a Command Code profile id — the profile itself holds the short name. */
+ commandcodeTarget(sessionId: string, profileId: string): CommandcodeModelTarget | null {
+ return this.commandcodeTargets.get(sessionId)?.get(profileId) ?? null
+ }
+
+ /**
+ * Command Code's catalog comes from `--list-models`. Effort rows are attached to every model because the
+ * CLI does not publish which models take one; an unsupported pick is refused in words at apply time
+ * (see COMMANDCODE_EFFORT_LEVELS).
+ */
+ private async commandcodeModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {
+ const entries = await this.commandcodeCatalog()
+ const targets = new Map<string, CommandcodeModelTarget>()
+ const output: RuntimeModelOption[] = []
+ const seen = new Set<string>()
+ const add = (entry: CommandcodeModelTarget, effort: string): void => {
+ const id = encodeRuntimeProfile({
+ sessionId: session.agentId, engine: 'commandcode', model: entry.shortId, effort,
+ })
+ if (seen.has(id)) return
+ seen.add(id)
+ targets.set(id, entry)
+ output.push({ id, displayName: `${runtimeModelLabel(entry.shortId)} / ${effortLabel(effort)}` })
+ }
+ for (const entry of entries) {
+ add(entry, 'auto')
+ for (const level of COMMANDCODE_EFFORT_LEVELS) add(entry, level)
+ }
+ const state = this.states.get(session.sessionId)
+ // `entries.length` guards the fallback: a model row is worth adding when the catalogue is readable but
+ // does not list what the session runs (a pinned build, a just-removed model). When the catalogue could
+ // not be read at all, one lone row is a picker that cannot pick anything — better to offer none.
+ if (entries.length && state?.model && !entries.some((entry) => entry.shortId === state.model)) {
+ const own: CommandcodeModelTarget = { id: state.model, shortId: state.model, section: '', isDefault: false }
+ add(own, 'auto')
+ if (state.effort && COMMANDCODE_EFFORTS.has(state.effort)) add(own, state.effort)
+ }
+ this.commandcodeTargets.set(session.sessionId, targets)
+ return output
+ }
+
+ private async commandcodeCatalog(): Promise<CommandcodeModelTarget[]> {
+ const key = env.COMMANDCODE_HOME
+ if (this.commandcodeCatalogCache?.key === key && this.commandcodeCatalogCache.expiresAt > Date.now()) {
+ return this.commandcodeCatalogCache.entries
+ }
+ let entries: CommandcodeModelTarget[] = []
+ try {
+ const result = await execFileAsync('commandcode', ['--list-models'], {
+ env: process.env, timeout: 15_000, maxBuffer: 1024 * 1024,
+ })
+ entries = parseCommandcodeModelsOutput(result.stdout)
+ } catch (err) {
+ console.warn('[runtime-profile] Command Code model catalog failed:', err instanceof Error ? err.message : err)
+ }
+ this.commandcodeCatalogCache = { key, entries, expiresAt: Date.now() + CATALOG_TTL_MS }
+ return entries
+ }
+
+ /** OpenCode has no effort axis, so every model is one `auto` row and the label carries no effort. */
+ private async opencodeModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {
+ const entries = await this.opencodeCatalog()
+ const output: RuntimeModelOption[] = []
+ const seen = new Set<string>()
+ for (const entry of entries) {
+ const id = encodeRuntimeProfile({
+ sessionId: session.agentId, engine: 'opencode', model: entry.id, effort: 'auto',
+ })
+ if (seen.has(id)) continue
+ seen.add(id)
+ output.push({ id, displayName: entry.id })
+ }
+ const state = this.states.get(session.sessionId)
+ // See commandcodeModels: only worth a row when the catalogue itself came back.
+ if (entries.length && state?.model && !entries.some((entry) => entry.id === state.model)) {
+ const id = encodeRuntimeProfile({
+ sessionId: session.agentId, engine: 'opencode', model: state.model, effort: 'auto',
+ })
+ if (!seen.has(id)) output.push({ id, displayName: state.model })
+ }
+ return output
+ }
+
+ async opencodeCatalog(): Promise<OpencodeModelTarget[]> {
+ const key = env.OPENCODE_DATA_DIR
+ if (this.opencodeCatalogCache?.key === key && this.opencodeCatalogCache.expiresAt > Date.now()) {
+ return this.opencodeCatalogCache.entries
+ }
+ let entries: OpencodeModelTarget[] = []
+ try {
+ const result = await execFileAsync('opencode', ['models'], {
+ env: process.env, timeout: 10_000, maxBuffer: 1024 * 1024,
+ })
+ entries = parseOpencodeModelsOutput(result.stdout)
+ } catch (err) {
+ console.warn('[runtime-profile] OpenCode model catalog failed:', err instanceof Error ? err.message : err)
+ }
+ this.opencodeCatalogCache = { key, entries, expiresAt: Date.now() + CATALOG_TTL_MS }
+ return entries
+ }
+
+ private async piCatalog(): Promise<ReturnType<typeof parsePiModelsOutput>> {
+ const key = env.PI_HOME
+ if (this.piCatalogCache?.key === key && this.piCatalogCache.expiresAt > Date.now()) {
+ return this.piCatalogCache.entries
+ }
+ let entries: ReturnType<typeof parsePiModelsOutput> = []
+ try {
+ const result = await execFileAsync('pi', ['--list-models'], {
+ env: process.env,
+ timeout: 10_000,
+ maxBuffer: 1024 * 1024,
+ })
+ entries = parsePiModelsOutput(result.stdout)
+ } catch (err) {
+ console.warn('[runtime-profile] Pi model catalog failed:', err instanceof Error ? err.message : err)
+ }
+ this.piCatalogCache = { key, entries, expiresAt: Date.now() + CATALOG_TTL_MS }
+ return entries
+ }
+
+ private scheduleChanged(sessionId: string): void {
+ const previous = this.changeTimers.get(sessionId)
+ if (previous) clearTimeout(previous)
+ this.changeTimers.set(sessionId, setTimeout(() => {
+ this.changeTimers.delete(sessionId)
+ if (!this.controls.has(sessionId)) this.onChanged?.(sessionId)
+ }, CHANGE_DEBOUNCE_MS))
+ }
+
+ private waitFor(sessionId: string, check: () => boolean, timeoutMs: number): Promise<boolean> {
+ if (check()) return Promise.resolve(true)
+ return new Promise((resolve) => {
+ const waiter: StateWaiter = {
+ check,
+ resolve,
+ timer: setTimeout(() => {
+ this.waiters.get(sessionId)?.delete(waiter)
+ resolve(false)
+ }, timeoutMs),
+ }
+ const set = this.waiters.get(sessionId) ?? new Set<StateWaiter>()
+ set.add(waiter)
+ this.waiters.set(sessionId, set)
+ })
+ }
+
+ private wake(sessionId: string): void {
+ const set = this.waiters.get(sessionId)
+ if (!set) return
+ for (const waiter of [...set]) {
+ if (!waiter.check()) continue
+ clearTimeout(waiter.timer)
+ set.delete(waiter)
+ waiter.resolve(true)
+ }
+ if (set.size === 0) this.waiters.delete(sessionId)
+ }
+}
diff --git a/cli/src/lib/runtimeProfileController.spec.ts b/cli/src/lib/runtimeProfileController.spec.ts
new file mode 100644
index 000000000..885ddaf76
--- /dev/null
+++ b/cli/src/lib/runtimeProfileController.spec.ts
@@ -0,0 +1,461 @@
+import { describe, expect, it, vi } from 'vitest'
+import type { RegisteredSession } from './registry.js'
+import { encodeRuntimeProfile, parseRuntimeProfile, RuntimeProfileManager } from './runtimeProfile.js'
+import {
+ inspectRuntimePane,
+ parseCodexAdvancedRows,
+ parseCodexEffortRows,
+ parseCodexModelMenuRows,
+ parseCodexModelRows,
+ parseCursorModelPicker,
+ parseCursorParameterRows,
+ RuntimeProfileController,
+} from './runtimeProfileController.js'
+
+// The id inside a `runtime-v1:` string is the AGENT id ('h1' here) — a client only ever echoes back an id
+// the catalog minted, and the catalog is agent-scoped. `setProfile` is still addressed with either id.
+function session(engine: 'claude' | 'codex' | 'cursor'): RegisteredSession {
+ return {
+ 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: engine === 'codex' ? '0.144.5' : engine === 'cursor' ? '2026.07.20-8cc9c0b' : '2.1.212', processIdentity: null,
+ registeredAt: 1, updatedAt: 1, lastHookAt: 1, lastTranscriptAt: 1,
+ }
+}
+
+describe('runtime pane parsing', () => {
+ it('distinguishes dim placeholders from real drafts', () => {
+ expect(inspectRuntimePane('codex', '\u001b[1m›\u001b[0m \u001b[2mWrite tests\u001b[0m')).toMatchObject({ idle: true, draft: false })
+ expect(inspectRuntimePane('codex', '\u001b[1m›\u001b[0m write tests')).toMatchObject({ idle: false, draft: true })
+ expect(inspectRuntimePane('claude', '\u001b[39m❯\u00a0\u001b[2mAsk about the codebase\u001b[0m')).toMatchObject({ idle: true, draft: false })
+ expect(inspectRuntimePane('claude', '\u001b[39m❯\u00a0Ask about the codebase')).toMatchObject({ idle: false, draft: true })
+ expect(inspectRuntimePane(
+ 'cursor',
+ '\u001b[48;2;21;21;21m \u001b[2m→ \u001b[0;7mP\u001b[0;2mlan, search, build anything\u001b[0m',
+ )).toMatchObject({ idle: true, draft: false })
+ })
+
+ it('reads devin and pi panes, whose composers look nothing like the others', () => {
+ // Devin's marker is ❭ (U+276D), not claude's ❯ (U+276F) — reading it as claude's found no prompt at
+ // all, and a pane with no prompt is never idle, so every switch would have been refused as BUSY.
+ const devinPane = (composer: string) => [
+ composer,
+ '────────────────────────────',
+ 'SWE-1.6 Slow See all keyboard shortcuts: /shortcuts',
+ ].join('\n')
+ // Devin dims its placeholder the way claude does, so the same SGR rule separates it from a draft.
+ expect(inspectRuntimePane('devin', devinPane('\u001b[39m❭ \u001b[2mAsk Devin to build features\u001b[0m')))
+ .toMatchObject({ idle: true, draft: false })
+ expect(inspectRuntimePane('devin', devinPane('\u001b[39m❭ fix the parser')))
+ .toMatchObject({ idle: false, draft: true })
+
+ // Pi draws no marker: its composer is the band between the last two rules, and the footer only
+ // exists in the normal view.
+ const piIdle = [
+ '────────────────────────────',
+ '',
+ '────────────────────────────',
+ '/private/tmp/rp-probe/pi',
+ '0.0%/500k (auto) minimax/minimax-m3 • high',
+ ].join('\n')
+ expect(inspectRuntimePane('pi', piIdle)).toMatchObject({ idle: true, draft: false, dialog: false })
+ expect(inspectRuntimePane('pi', piIdle.replace('\n\n', '\n/model something\n')))
+ .toMatchObject({ idle: false, draft: true })
+ expect(inspectRuntimePane('pi', [
+ 'Thinking Level',
+ 'Select reasoning depth for thinking-capable models',
+ '→ medium Moderate reasoning (~8k tokens)',
+ ' Enter to select · Esc to go back',
+ ].join('\n'))).toMatchObject({ idle: false, dialog: true })
+ })
+
+ it('ignores picker and Plan mode text left above the latest prompt', () => {
+ const capture = 'Select Model and Effort\nPlan mode\n› old\ncompleted\n› \ngpt-5.6-sol high ·'
+ expect(inspectRuntimePane('codex', capture)).toMatchObject({ idle: true, dialog: false, plan: false })
+ })
+
+ it('parses the version-gated Codex picker rows', () => {
+ const menu = parseCodexModelMenuRows([
+ 'Select Model',
+ 'Pick a quick auto mode or browse all models.',
+ ' 1. codex-auto-review Balanced agentic coding model for everyday work.',
+ '› 2. All models (current) Choose a specific model and reasoning level',
+ ].join('\n'))
+ expect(menu?.quickModels.get('codex-auto-review')).toBe('1')
+ expect(menu?.allModelsRow).toBe('2')
+
+ const models = parseCodexModelRows('Select Model and Effort\n 1. gpt-5.6-sol (default) Latest frontier model.\n 2. gpt-5.6-terra\n› 3. gpt-5.6-luna (current) Fast model.')
+ expect(models?.get('gpt-5.6-sol')).toBe('1')
+ expect(models?.get('gpt-5.6-terra')).toBe('2')
+ expect(models?.get('gpt-5.6-luna')).toBe('3')
+ const efforts = parseCodexEffortRows('Select Reasoning Level for gpt-5.6-sol\n 1. Low\n 2. High (default)\n 3. Extra high\n 4. More reasoning options')
+ expect(efforts?.efforts.get('xhigh')).toBe('3')
+ expect(efforts?.defaultRow).toBe('2')
+ expect(efforts?.advancedRow).toBe('4')
+ const advanced = parseCodexAdvancedRows('Advanced Reasoning\n› 1. Max (current) Higher usage\n 2. Ultra Highest usage')
+ expect(advanced?.get('max')).toBe('1')
+ expect(advanced?.get('ultra')).toBe('2')
+ })
+
+ it('treats both Codex model picker generations as active dialogs', () => {
+ expect(inspectRuntimePane(
+ 'codex',
+ 'Select Model\nPick a quick auto mode or browse all models.\n› 2. All models (current)',
+ )).toMatchObject({ idle: false, dialog: true })
+ expect(inspectRuntimePane(
+ 'codex',
+ 'Select Model and Effort\n› 1. gpt-5.6-sol (current)',
+ )).toMatchObject({ idle: false, dialog: true })
+ })
+
+ it('does not reuse picker rows left before a newer composer prompt', () => {
+ const stale = 'Select Model and Effort\n 1. gpt-old\n› 1. gpt-old\n› \ngpt-current high ·'
+ expect(parseCodexModelRows(stale)).toBeNull()
+ })
+
+ it('parses the gated Cursor picker and parameter rows by meaning', () => {
+ const picker = [
+ ' Available models Max mode: OFF',
+ ' Filter:',
+ ' Auto',
+ ' → GPT-5.6 Sol 272K Medium (Tab to modify)',
+ ' Type to filter • Enter to select • Tab to edit',
+ ].join('\n')
+ expect(parseCursorModelPicker(picker)).toEqual({ selectedFamily: 'GPT-5.6 Sol' })
+
+ const parameters = [
+ ' GPT-5.6 Sol — Edit Parameters',
+ ' Context',
+ ' → ● 272K ✓',
+ ' ○ 1M',
+ ' Reasoning',
+ ' ○ None',
+ ' ● Medium ✓',
+ ' ○ Extra High',
+ ' ◯ Fast',
+ ].join('\n')
+ expect(parseCursorParameterRows(parameters)).toEqual([
+ { kind: 'context', value: '272k', selected: true, cursor: true, index: 0 },
+ { kind: 'context', value: '1m', selected: false, cursor: false, index: 1 },
+ { kind: 'reasoning', value: 'none', selected: false, cursor: false, index: 2 },
+ { kind: 'reasoning', value: 'medium', selected: true, cursor: false, index: 3 },
+ { kind: 'reasoning', value: 'xhigh', selected: false, cursor: false, index: 4 },
+ { kind: 'fast', value: 'true', selected: false, cursor: false, index: 5 },
+ ])
+ })
+})
+
+describe('RuntimeProfileController', () => {
+ it('sets Claude model and effort only after transcript confirmations', async () => {
+ const value = session('claude')
+ const manager = new RuntimeProfileManager()
+ manager.hydrate(value, [])
+ manager.ingestPane(value, 'Sonnet 5 with low effort\n❯ ', true)
+ value.cliVersion = null // simulate an old persisted registry entry after manager hydration
+ const commands: string[] = []
+ const release = vi.fn()
+ const controller = new RuntimeProfileController({
+ manager,
+ getSession: () => value,
+ validateRuntime: async () => true,
+ capture: async () => 'Opus 4.8 with high effort\n❯ ',
+ sendText: async (_pane, command) => {
+ commands.push(command)
+ if (command.startsWith('/model ')) {
+ manager.ingest(value, JSON.stringify({ type: 'assistant', message: { content: [{ type: 'text', text: 'Set model to Opus 4.8' }] } }))
+ } else {
+ manager.ingest(value, JSON.stringify({ type: 'assistant', message: { content: [{ type: 'text', text: 'Set effort level to high' }] } }))
+ }
+ return true
+ },
+ sendLiteral: async () => true,
+ sendKey: async () => true,
+ acquireInput: () => release,
+ })
+ const target = encodeRuntimeProfile({ sessionId: 'h1', engine: 'claude', model: 'opus', effort: 'high' })
+
+ await controller.setProfile('s1', target)
+
+ expect(commands).toEqual(['/model opus', '/effort high'])
+ expect(manager.selectedModel(value)).toBe(target)
+ expect(release).toHaveBeenCalledOnce()
+ })
+
+ it('does not reset unchanged auto effort after switching from Haiku to Sonnet', async () => {
+ const value = session('claude')
+ const manager = new RuntimeProfileManager()
+ manager.hydrate(value, [JSON.stringify({
+ type: 'user', message: { content: '<local-command-stdout>Set model to Haiku 4.5</local-command-stdout>' },
+ })])
+ expect(manager.selectedModel(value)).toBe(encodeRuntimeProfile({
+ sessionId: 'h1', engine: 'claude', model: 'haiku', effort: 'auto',
+ }))
+ const commands: string[] = []
+ const controller = new RuntimeProfileController({
+ manager,
+ getSession: () => value,
+ validateRuntime: async () => true,
+ capture: async () => '\u001b[39m\u276f\u00a0\u001b[2mAsk about the codebase\u001b[0m',
+ sendText: async (_pane, command) => {
+ commands.push(command)
+ const output = command.startsWith('/model ')
+ ? 'Set model to \u001b[1mSonnet 5\u001b[22m and saved as your default for new sessions'
+ : 'Effort level set to auto'
+ manager.ingest(value, JSON.stringify({
+ type: 'user', message: { content: `<local-command-stdout>${output}</local-command-stdout>` },
+ }))
+ return true
+ },
+ sendLiteral: async () => true,
+ sendKey: async () => true,
+ acquireInput: () => () => undefined,
+ })
+ const target = encodeRuntimeProfile({ sessionId: 'h1', engine: 'claude', model: 'sonnet', effort: 'auto' })
+
+ await controller.setProfile('s1', target)
+
+ expect(commands).toEqual(['/model sonnet'])
+ expect(manager.selectedModel(value)).toBe(target)
+ })
+
+ it('sets Claude ultracode effort through its native command value', async () => {
+ const value = session('claude')
+ const manager = new RuntimeProfileManager()
+ manager.hydrate(value, [])
+ manager.ingestPane(value, 'Sonnet 5 with high effort\n❯ ', true)
+ const commands: string[] = []
+ const controller = new RuntimeProfileController({
+ manager,
+ getSession: () => value,
+ validateRuntime: async () => true,
+ capture: async () => '\u001b[39m\u276f\u00a0\u001b[2mAsk about the codebase\u001b[0m',
+ sendText: async (_pane, command) => {
+ commands.push(command)
+ const output = command.startsWith('/model ')
+ ? 'Set model to Sonnet 5 and saved as your default for new sessions'
+ : 'Set effort level to ultracode (this session only): xhigh + dynamic workflow orchestration'
+ manager.ingest(value, JSON.stringify({
+ type: 'user', message: { content: `<local-command-stdout>${output}</local-command-stdout>` },
+ }))
+ return true
+ },
+ sendLiteral: async () => true,
+ sendKey: async () => true,
+ acquireInput: () => () => undefined,
+ })
+ const target = encodeRuntimeProfile({ sessionId: 'h1', engine: 'claude', model: 'sonnet', effort: 'ultracode' })
+
+ await controller.setProfile('s1', target)
+
+ expect(commands).toEqual(['/effort ultracode'])
+ expect(manager.selectedModel(value)).toBe(target)
+ })
+
+ it('does not touch tmux when the requested profile is already current', async () => {
+ const value = session('claude')
+ const manager = new RuntimeProfileManager()
+ manager.hydrate(value, [])
+ manager.ingestPane(value, 'Sonnet 5 with high effort\n❯ ', true)
+ const validateRuntime = vi.fn(async () => true)
+ const sendText = vi.fn(async () => true)
+ const acquireInput = vi.fn(() => () => undefined)
+ const controller = new RuntimeProfileController({
+ manager,
+ getSession: () => value,
+ validateRuntime,
+ capture: async () => '\u001b[39m\u276f\u00a0\u001b[2mAsk about the codebase\u001b[0m',
+ sendText,
+ sendLiteral: async () => true,
+ sendKey: async () => true,
+ acquireInput,
+ })
+ const current = encodeRuntimeProfile({ sessionId: 'h1', engine: 'claude', model: 'sonnet', effort: 'high' })
+
+ await controller.setProfile('s1', current)
+
+ expect(validateRuntime).not.toHaveBeenCalled()
+ expect(acquireInput).not.toHaveBeenCalled()
+ expect(sendText).not.toHaveBeenCalled()
+ })
+
+ it('rejects remote Codex changes while the native session is in Plan mode', async () => {
+ const value = session('codex')
+ const manager = new RuntimeProfileManager()
+ manager.hydrate(value, [JSON.stringify({
+ type: 'turn_context', payload: { model: 'gpt-5.6-sol', reasoning_effort: 'high', collaboration_mode: { mode: 'plan' } },
+ })])
+ const target = encodeRuntimeProfile({ sessionId: 'h1', engine: 'codex', model: 'gpt-5.6-sol', effort: 'low' })
+ vi.spyOn(manager, 'modelsForSession').mockResolvedValue([{ id: target, displayName: 'GPT-5.6-Sol / Low' }])
+ const controller = new RuntimeProfileController({
+ manager, getSession: () => value, validateRuntime: async () => true,
+ capture: async () => '› \ngpt-5.6-sol high ·', sendText: vi.fn(), sendLiteral: vi.fn(), sendKey: vi.fn(), acquireInput: vi.fn(),
+ })
+
+ await expect(controller.setProfile('s1', target)).rejects.toMatchObject({ code: 'PLAN_SCOPE_AMBIGUOUS' })
+ })
+
+ it('selects Codex Ultra through the Advanced Reasoning submenu', async () => {
+ const value = session('codex')
+ const manager = new RuntimeProfileManager()
+ manager.hydrate(value, [JSON.stringify({
+ type: 'turn_context', payload: { model: 'gpt-5.6-sol', reasoning_effort: 'high' },
+ })])
+ const target = encodeRuntimeProfile({ sessionId: 'h1', engine: 'codex', model: 'gpt-5.6-sol', effort: 'ultra' })
+ vi.spyOn(manager, 'modelsForSession').mockResolvedValue([{ id: target, displayName: 'GPT-5.6-Sol / Ultra' }])
+ let phase: 'idle' | 'models' | 'efforts' | 'advanced' = 'idle'
+ const keys: string[] = []
+ const controller = new RuntimeProfileController({
+ manager,
+ getSession: () => value,
+ validateRuntime: async () => true,
+ capture: async () => {
+ if (phase === 'models') return 'Select Model and Effort\n 1. gpt-5.6-sol (current)'
+ if (phase === 'efforts') return 'Select Reasoning Level for gpt-5.6-sol\n 5. More reasoning options'
+ if (phase === 'advanced') return 'Advanced Reasoning\n 1. Max\n 2. Ultra'
+ return '› \ngpt-5.6-sol high ·'
+ },
+ sendText: async () => { phase = 'models'; return true },
+ sendLiteral: async () => true,
+ sendKey: async (_pane, key) => {
+ keys.push(key)
+ if (phase === 'models' && key === '1') phase = 'efforts'
+ else if (phase === 'efforts' && key === '5') phase = 'advanced'
+ else if (phase === 'advanced' && key === '2') {
+ phase = 'idle'
+ manager.ingest(value, JSON.stringify({
+ type: 'turn_context', payload: { model: 'gpt-5.6-sol', reasoning_effort: 'ultra' },
+ }))
+ }
+ return true
+ },
+ acquireInput: () => () => undefined,
+ })
+
+ await controller.setProfile('s1', target)
+
+ expect(keys).toEqual(['1', '5', '2'])
+ expect(manager.selectedModel(value)).toBe(target)
+ })
+
+ it('selects an explicit Codex model through the 0.145 All models pre-menu', async () => {
+ const value = session('codex')
+ value.cliVersion = '0.145.0'
+ const manager = new RuntimeProfileManager()
+ manager.hydrate(value, [JSON.stringify({
+ type: 'turn_context', payload: { model: 'gpt-5.6-sol', reasoning_effort: 'high' },
+ })])
+ const target = encodeRuntimeProfile({ sessionId: 'h1', engine: 'codex', model: 'gpt-5.6-terra', effort: 'low' })
+ vi.spyOn(manager, 'modelsForSession').mockResolvedValue([{ id: target, displayName: 'GPT-5.6-Terra / Low' }])
+ let phase: 'idle' | 'menu' | 'models' | 'efforts' = 'idle'
+ const keys: string[] = []
+ const controller = new RuntimeProfileController({
+ manager,
+ getSession: () => value,
+ validateRuntime: async () => true,
+ capture: async () => {
+ if (phase === 'menu') {
+ return 'Select Model\nPick a quick auto mode or browse all models.\n 1. codex-auto-review\n› 2. All models (current)'
+ }
+ if (phase === 'models') {
+ return 'Select Model and Effort\n 1. gpt-5.6-sol (current)\n 2. gpt-5.6-terra'
+ }
+ if (phase === 'efforts') return 'Select Reasoning Level for gpt-5.6-terra\n 1. Low\n 2. High (default)'
+ return '› \ngpt-5.6-sol high ·'
+ },
+ sendText: async () => { phase = 'menu'; return true },
+ sendLiteral: async () => true,
+ sendKey: async (_pane, key) => {
+ keys.push(key)
+ if (phase === 'menu' && key === '2') phase = 'models'
+ else if (phase === 'models' && key === '2') phase = 'efforts'
+ else if (phase === 'efforts' && key === '1') {
+ phase = 'idle'
+ manager.ingest(value, JSON.stringify({
+ type: 'turn_context', payload: { model: 'gpt-5.6-terra', reasoning_effort: 'low' },
+ }))
+ }
+ return true
+ },
+ acquireInput: () => () => undefined,
+ })
+
+ await controller.setProfile('s1', target)
+
+ expect(keys).toEqual(['2', '2', '1'])
+ expect(manager.selectedModel(value)).toBe(target)
+ })
+
+ it('selects a Codex quick profile directly from the 0.145 pre-menu', async () => {
+ const value = session('codex')
+ value.cliVersion = '0.145.0'
+ const manager = new RuntimeProfileManager()
+ manager.hydrate(value, [JSON.stringify({
+ type: 'turn_context', payload: { model: 'gpt-5.6-sol', reasoning_effort: 'high' },
+ })])
+ const target = encodeRuntimeProfile({ sessionId: 'h1', engine: 'codex', model: 'codex-auto-review', effort: 'high' })
+ vi.spyOn(manager, 'modelsForSession').mockResolvedValue([{ id: target, displayName: 'GPT-5.6-Terra / High' }])
+ let phase: 'idle' | 'menu' | 'efforts' = 'idle'
+ const keys: string[] = []
+ const controller = new RuntimeProfileController({
+ manager,
+ getSession: () => value,
+ validateRuntime: async () => true,
+ capture: async () => {
+ if (phase === 'menu') {
+ return 'Select Model\nPick a quick auto mode or browse all models.\n 1. codex-auto-review\n› 2. All models (current)'
+ }
+ if (phase === 'efforts') {
+ return 'Select Reasoning Level for codex-auto-review\n 1. Low\n 2. Medium (default)\n 3. High'
+ }
+ return '› \ngpt-5.6-sol high ·'
+ },
+ sendText: async () => { phase = 'menu'; return true },
+ sendLiteral: async () => true,
+ sendKey: async (_pane, key) => {
+ keys.push(key)
+ if (phase === 'menu' && key === '1') phase = 'efforts'
+ else if (phase === 'efforts' && key === '3') {
+ phase = 'idle'
+ manager.ingest(value, JSON.stringify({
+ type: 'turn_context', payload: { model: 'codex-auto-review', reasoning_effort: 'high' },
+ }))
+ }
+ return true
+ },
+ acquireInput: () => () => undefined,
+ })
+
+ await controller.setProfile('s1', target)
+
+ expect(keys).toEqual(['1', '3'])
+ expect(manager.selectedModel(value)).toBe(target)
+ })
+
+ it('refuses to drive an engine the owner made view-only', async () => {
+ // Switching is Claude and Codex only (owner, 2026-07-31). This replaces two tests that drove Cursor's
+ // picker end to end: setCursor and the other per-engine drivers are still in the code, deliberately —
+ // this policy has already flipped twice — but nothing can reach them while the gate is shut, so what
+ // is worth asserting now is the refusal, and that it costs the user's pane nothing.
+ const value = session('cursor')
+ const manager = new RuntimeProfileManager()
+ manager.hydrate(value, [])
+ const target = encodeRuntimeProfile({ sessionId: 'h1', engine: 'cursor', model: 'claude-4.5-sonnet', effort: 'auto' })
+ vi.spyOn(manager, 'modelsForSession').mockResolvedValue([{ id: target, displayName: 'Sonnet 4.5 / Auto' }])
+ const sendKey = vi.fn().mockResolvedValue(true)
+ const sendText = vi.fn().mockResolvedValue(true)
+ const controller = new RuntimeProfileController({
+ manager,
+ getSession: () => value,
+ validateRuntime: async () => true,
+ capture: async () => '→ Add a follow-up',
+ sendText,
+ sendKey,
+ sendLiteral: vi.fn().mockResolvedValue(true),
+ acquireInput: () => () => undefined,
+ })
+
+ await expect(controller.setProfile('s1', target)).rejects.toMatchObject({ code: 'UNSUPPORTED_CLI_VERSION' })
+ expect(sendKey).not.toHaveBeenCalled()
+ expect(sendText).not.toHaveBeenCalled()
+ })
+})
diff --git a/cli/src/lib/runtimeProfileController.ts b/cli/src/lib/runtimeProfileController.ts
new file mode 100644
index 000000000..4d1f74005
--- /dev/null
+++ b/cli/src/lib/runtimeProfileController.ts
@@ -0,0 +1,919 @@
+import type { RegisteredSession } from './registry.js'
+import { devinModelCommandResult } from '../engines/devin/runtimeProfile.js'
+import { countCommandcodeRefusals } from '../engines/commandcode/runtimeProfile.js'
+import { parseHermesPickerPage } from '../engines/hermes/runtimeProfile.js'
+import { parsePiFooterProfile, parsePiThinkingSelection, piThinkingSteps } from '../engines/pi/runtimeProfile.js'
+import {
+ countOpencodePickers,
+ opencodeRowMatches,
+ parseOpencodePickerRows,
+} from '../engines/opencode/runtimeProfile.js'
+import {
+ codexEffortAllowed,
+ parseRuntimeProfile,
+ supportsNativeRuntimeControl,
+ type CursorModelTarget,
+ type RuntimeProfile,
+ type RuntimeProfileManager,
+} from './runtimeProfile.js'
+
+const COMMAND_CONFIRM_MS = 8_000
+const PICKER_OPEN_MS = 3_000
+const PICKER_STEP_MS = 2_000
+/** Hard bound on ladder keystrokes — twice pi's seven levels, so a desynchronised walk still terminates. */
+const PI_LADDER_MAX_STEPS = 14
+/** Hermes' longest picker page is a provider's model list; twice its size still terminates. */
+const HERMES_PAGE_MAX_STEPS = 60
+
+/** "Anthropic (13 models)" names provider key `anthropic`; "GitHub Copilot (17 models)" names `copilot`. */
+function hermesProviderMatches(row: string, provider: string): boolean {
+ const name = row.replace(/\s*\([^)]*\)\s*$/, '').trim().toLowerCase()
+ const key = provider.toLowerCase()
+ return name === key || name.replace(/[^a-z0-9]/g, '').includes(key.replace(/[^a-z0-9]/g, ''))
+}
+
+export type RuntimeProfileErrorCode =
+ | 'AGENT_NOT_FOUND'
+ | 'INVALID_RUNTIME_PROFILE'
+ | 'BUSY'
+ | 'UNSUPPORTED_CLI_VERSION'
+ | 'MODEL_UNAVAILABLE'
+ | 'EFFORT_UNSUPPORTED'
+ | 'PLAN_SCOPE_AMBIGUOUS'
+ | 'CONFIRM_TIMEOUT'
+ | 'TMUX_FAILED'
+
+export class RuntimeProfileControlError extends Error {
+ constructor(readonly code: RuntimeProfileErrorCode) {
+ super(code)
+ }
+}
+
+export interface PaneInspection {
+ idle: boolean
+ plan: boolean
+ dialog: boolean
+ draft: boolean
+}
+
+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>
+ acquireInput: (sessionId: string) => (() => void) | null
+}
+
+function stripAnsi(value: string): string {
+ return value.replace(/\u001b\[[0-9;:]*[A-Za-z]/g, '')
+}
+
+function hasDimSgr(value: string): boolean {
+ return [...value.matchAll(/\u001b\[([0-9;:]*)m/g)]
+ .some((match) => match[1].split(/[;:]/).includes('2'))
+}
+
+function interactionText(capture: string): string {
+ const lines = capture.split('\n')
+ const promptIndex = lines.findLastIndex((line) => {
+ const visible = stripAnsi(line)
+ const marker = visible.search(/[›❯]/u)
+ if (marker < 0) return false
+ // Picker selection rows also use ›, but numbered rows are not composer prompts.
+ return !/^\s*\d+\.\s/.test(visible.slice(marker + 1))
+ })
+ return (promptIndex >= 0 ? lines.slice(promptIndex) : lines).join('\n')
+}
+
+/**
+ * The glyph each CLI puts in front of its composer. They do not share one: cursor uses `→`, devin `❭`
+ * (U+276D — close to, but not, claude's `❯` U+276F), and pi draws no marker at all. Getting this wrong is
+ * not cosmetic — with no prompt found the pane never reads idle, and every switch is refused as BUSY.
+ */
+function promptMarker(engine: RegisteredSession['engine']): RegExp {
+ if (engine === 'cursor') return /→/u
+ if (engine === 'devin') return /[❭›❯]/u
+ if (engine === 'opencode') return /┃/u
+ return /[›❯]/u
+}
+
+export function inspectRuntimePane(engine: RegisteredSession['engine'], capture: string): PaneInspection {
+ if (engine === 'pi') return inspectPiPane(capture)
+ const rawLines = capture.split('\n')
+ const marks = promptMarker(engine)
+ const promptIndex = rawLines.findLastIndex((line) => {
+ const visible = stripAnsi(line)
+ const marker = visible.search(marks)
+ return marker >= 0 && !/^\s*\d+\.\s/.test(visible.slice(marker + 1))
+ })
+ const prompt = promptIndex >= 0 ? rawLines[promptIndex] : ''
+ // Old picker/plan text can remain in tmux history. Only UI below the latest prompt belongs to the
+ // current interaction; if no prompt is visible, inspect the whole capture as a conservative fallback.
+ const currentUi = stripAnsi((promptIndex >= 0 ? rawLines.slice(promptIndex) : rawLines).join('\n')).replace(/\u00a0/g, ' ')
+ const dialog = /Select Model(?: and Effort)?|Select Reasoning Level|Advanced Reasoning|Available models|Models matching|Edit Parameters|Type to filter.*Tab to edit|Esc to go back|Press enter to confirm|Do you want to proceed|Allow this action|permission required|Starting MCP servers?/i.test(currentUi)
+ const plan = engine === 'codex' ? /\bplan mode\b/i.test(currentUi) : /\bplan mode on\b/i.test(currentUi)
+ const marker = stripAnsi(prompt).search(marks)
+ let visible = marker >= 0 ? stripAnsi(prompt).slice(marker + 1).replace(/\u00a0/g, ' ').trim() : ''
+ const rawMarker = prompt.search(marks)
+ const rawTail = rawMarker >= 0 ? prompt.slice(rawMarker + 1) : ''
+ const placeholder = hasDimSgr(rawTail)
+ if (placeholder) visible = ''
+ const draft = visible.length > 0
+ return { idle: !!prompt && !dialog && !draft, plan, dialog, draft }
+}
+
+/**
+ * Pi draws no composer marker, so idleness is read from its layout instead: the composer is the band
+ * between the last two `───` rules, and the footer (`minimax/minimax-m3 • high`) is only rendered by the
+ * normal view. A non-empty band is a draft the user is still typing — injecting there would splice a
+ * slash command into their sentence.
+ */
+function inspectPiPane(capture: string): PaneInspection {
+ const lines = stripAnsi(capture).split('\n').map((line) => line.replace(/\s+$/, ''))
+ // Reuse the reader rather than restating its regex: the footer has two shapes (`• high` and, once off,
+ // `• thinking off`), and a second copy of the pattern missed the second one — leaving the pane forever
+ // "not idle" and every switch refused as BUSY.
+ const footer = parsePiFooterProfile(lines.join('\n')) !== null
+ const rules: number[] = []
+ lines.forEach((line, index) => { if (/^\s*─{8,}\s*$/.test(line)) rules.push(index) })
+ const dialog = /Thinking Level|Select reasoning depth|Type to search|Enter to select|Only showing models from/i
+ .test(lines.join('\n'))
+ if (rules.length < 2) return { idle: false, plan: false, dialog, draft: false }
+ const band = lines.slice(rules[rules.length - 2] + 1, rules[rules.length - 1]).join('').trim()
+ const draft = band.length > 0
+ return { idle: footer && !dialog && !draft, plan: false, dialog, draft }
+}
+
+interface NumberedRow {
+ number: string
+ label: string
+ raw: string
+}
+
+function numberedRows(capture: string): NumberedRow[] {
+ const rows: NumberedRow[] = []
+ for (const raw of stripAnsi(capture).split('\n')) {
+ const match = /^\s*[›>]?[ ]*(\d+)\.\s+(.+?)\s*$/.exec(raw)
+ if (match) rows.push({ number: match[1], label: match[2], raw })
+ }
+ return rows
+}
+
+export interface CodexModelMenuRows {
+ quickModels: Map<string, string>
+ allModelsRow: string | null
+}
+
+/** Codex 0.145+ adds a quick-mode menu before the existing model and effort pickers. */
+export function parseCodexModelMenuRows(capture: string): CodexModelMenuRows | null {
+ capture = interactionText(capture)
+ const visible = stripAnsi(capture)
+ if (!/Pick a quick auto mode or browse all models/i.test(visible)) return null
+ const quickModels = new Map<string, string>()
+ let allModelsRow: string | null = null
+ for (const row of numberedRows(capture)) {
+ if (/^All models\b/i.test(row.label)) {
+ allModelsRow = row.number
+ continue
+ }
+ const model = /^([a-z0-9][a-z0-9._-]*)(?:\s+\((?:current|default)\))?(?:\s{2,}|$)/i.exec(row.label)?.[1]
+ if (model) quickModels.set(model, row.number)
+ }
+ return { quickModels, allModelsRow }
+}
+
+export function parseCodexModelRows(capture: string): Map<string, string> | null {
+ capture = interactionText(capture)
+ if (!/Select Model and Effort/i.test(stripAnsi(capture))) return null
+ const result = new Map<string, string>()
+ for (const row of numberedRows(capture)) {
+ const model = /^([a-z0-9][a-z0-9._-]*)(?:\s+\((?:current|default)\))?(?:\s{2,}|$)/i.exec(row.label)?.[1]
+ if (model) result.set(model, row.number)
+ }
+ return result
+}
+
+export interface CodexEffortRows {
+ efforts: Map<string, string>
+ defaultRow: string | null
+ advancedRow: string | null
+}
+
+export function parseCodexEffortRows(capture: string): CodexEffortRows | null {
+ capture = interactionText(capture)
+ if (!/Select Reasoning Level for\s+/i.test(stripAnsi(capture))) return null
+ const efforts = new Map<string, string>()
+ let defaultRow: string | null = null
+ let advancedRow: string | null = null
+ for (const row of numberedRows(capture)) {
+ const label = row.label.toLowerCase()
+ if (label.startsWith('low')) efforts.set('low', row.number)
+ else if (label.startsWith('medium')) efforts.set('medium', row.number)
+ else if (label.startsWith('high')) efforts.set('high', row.number)
+ else if (label.startsWith('extra high')) efforts.set('xhigh', row.number)
+ else if (label.startsWith('max')) efforts.set('max', row.number)
+ else if (label.startsWith('more reasoning')) advancedRow = row.number
+ if (/\(default\)/i.test(row.label)) defaultRow = row.number
+ }
+ return { efforts, defaultRow, advancedRow }
+}
+
+export function parseCodexAdvancedRows(capture: string): Map<string, string> | null {
+ capture = interactionText(capture)
+ if (!/Advanced Reasoning/i.test(stripAnsi(capture))) return null
+ const efforts = new Map<string, string>()
+ for (const row of numberedRows(capture)) {
+ if (/^max\b/i.test(row.label)) efforts.set('max', row.number)
+ else if (/^ultra\b/i.test(row.label)) efforts.set('ultra', row.number)
+ }
+ return efforts
+}
+
+export interface CursorParameterRow {
+ kind: 'context' | 'reasoning' | 'fast' | 'thinking'
+ value: string
+ selected: boolean
+ cursor: boolean
+ index: number
+}
+
+export function parseCursorModelPicker(capture: string): { selectedFamily: string | null } | null {
+ const lines = stripAnsi(capture).split('\n')
+ if (!lines.some((line) => /Available models|Models matching/i.test(line)) || !lines.some((line) => /Tab to edit/i.test(line))) {
+ return null
+ }
+ const selected = lines.findLast((line) => /^\s*→\s+/.test(line))
+ if (!selected) return { selectedFamily: null }
+ const value = selected.replace(/^\s*→\s+/, '').replace(/\s+\(Tab to modify\)\s*$/i, '')
+ return { selectedFamily: value.split(/\s{2,}/)[0]?.trim() || null }
+}
+
+export function parseCursorParameterRows(capture: string): CursorParameterRow[] | null {
+ const lines = stripAnsi(capture).split('\n')
+ if (!lines.some((line) => /— Edit Parameters/i.test(line))) return null
+ const rows: CursorParameterRow[] = []
+ let section: 'context' | 'reasoning' | null = null
+ for (const raw of lines) {
+ const line = raw.replace(/\u00a0/g, ' ')
+ if (/^\s*Context\s*$/.test(line)) { section = 'context'; continue }
+ if (/^\s*Reasoning\s*$/.test(line)) { section = 'reasoning'; continue }
+ const choice = /^\s*(→)?\s*([●○◉◯])\s+(.+?)(?:\s+✓)?\s*$/.exec(line)
+ if (!choice) continue
+ const label = choice[3].trim()
+ let kind: CursorParameterRow['kind']
+ let value: string
+ if (/^Fast$/i.test(label)) {
+ kind = 'fast'
+ value = 'true'
+ } else if (/^Thinking$/i.test(label)) {
+ kind = 'thinking'
+ value = 'true'
+ } else if (section === 'context') {
+ kind = 'context'
+ value = label.toLowerCase()
+ } else if (section === 'reasoning') {
+ kind = 'reasoning'
+ value = label.toLowerCase().replace(/\s+/g, '') === 'extrahigh'
+ ? 'xhigh'
+ : label.toLowerCase()
+ } else {
+ continue
+ }
+ rows.push({
+ kind,
+ value,
+ selected: choice[2] === '●' || choice[2] === '◉' || /✓\s*$/.test(line),
+ cursor: !!choice[1],
+ index: rows.length,
+ })
+ }
+ return rows.length ? rows : null
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms))
+}
+
+export class RuntimeProfileController {
+ constructor(private readonly deps: RuntimeProfileControllerDeps) {}
+
+ async setProfile(sessionId: string, encoded: unknown): Promise<void> {
+ const registeredSession = this.deps.getSession(sessionId)
+ if (!registeredSession) throw new RuntimeProfileControlError('AGENT_NOT_FOUND')
+ const observed = this.deps.manager.getState(registeredSession.sessionId)
+ const session: RegisteredSession = registeredSession.cliVersion || !observed.cliVersion
+ ? registeredSession
+ : { ...registeredSession, cliVersion: observed.cliVersion }
+ const target = parseRuntimeProfile(encoded)
+ // Either id identifies the agent: the encoded profile now carries the agent id, but one minted
+ // before the id cutover (or by a client that still knows the session) must keep working.
+ if (!target || (target.sessionId !== session.agentId && target.sessionId !== session.sessionId) || target.engine !== session.engine) {
+ throw new RuntimeProfileControlError('INVALID_RUNTIME_PROFILE')
+ }
+ const current = parseRuntimeProfile(this.deps.manager.selectedModel(session))
+ if (current?.id === target.id) return
+ if (!supportsNativeRuntimeControl(session)) {
+ console.warn(`[runtime-profile] unsupported ${session.engine} CLI version ${session.cliVersion ?? 'unknown'} for ${sessionId.slice(0, 8)}`)
+ throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
+ }
+ if (session.engine === 'codex' && !codexEffortAllowed(target.model, target.effort)) {
+ throw new RuntimeProfileControlError('EFFORT_UNSUPPORTED')
+ }
+ const options = await this.deps.manager.modelsForSession(session)
+ if (!options.some((option) => option.id === target.id)) {
+ const sameModel = options.some((option) => parseRuntimeProfile(option.id)?.model === target.model)
+ throw new RuntimeProfileControlError(sameModel ? 'EFFORT_UNSUPPORTED' : 'MODEL_UNAVAILABLE')
+ }
+ if (session.engine === 'codex' && observed.mode === 'plan') throw new RuntimeProfileControlError('PLAN_SCOPE_AMBIGUOUS')
+ const release = this.deps.acquireInput(session.agentId)
+ if (!release) throw new RuntimeProfileControlError('BUSY')
+ let controlStarted = false
+ let pickerOpen = false
+ try {
+ if (!await this.deps.validateRuntime(session)) throw new RuntimeProfileControlError('TMUX_FAILED')
+ const capture = await this.deps.capture(session.tmuxPane, 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')
+ if (!inspection.idle) throw new RuntimeProfileControlError('BUSY')
+ if (!this.deps.manager.beginControl(session, target)) throw new RuntimeProfileControlError('BUSY')
+ controlStarted = true
+ if (session.engine === 'claude') {
+ await this.setClaude(session, target, current, options)
+ } else if (session.engine === 'codex') {
+ pickerOpen = true
+ await this.setCodex(session, target)
+ pickerOpen = false
+ } else if (session.engine === 'devin') {
+ // No picker is ever opened — `/model <id>` is a single command — so there is nothing to Escape out
+ // of if this throws.
+ await this.setDevin(session, target)
+ } else if (session.engine === 'pi') {
+ pickerOpen = true
+ await this.setPi(session, target, current)
+ pickerOpen = false
+ } else if (session.engine === 'opencode') {
+ pickerOpen = true
+ await this.setOpencode(session, target)
+ pickerOpen = false
+ } else if (session.engine === 'hermes') {
+ pickerOpen = true
+ await this.setHermes(session, target)
+ pickerOpen = false
+ } else if (session.engine === 'commandcode') {
+ // Two plain commands, no dialog — nothing to Escape out of if either throws.
+ await this.setCommandcode(session, target, current)
+ } else {
+ pickerOpen = true
+ await this.setCursor(session, target)
+ pickerOpen = false
+ }
+ this.deps.manager.finishControl(session)
+ controlStarted = false
+ } catch (error) {
+ if (pickerOpen) {
+ for (let attempt = 0; attempt < 3; attempt++) {
+ await this.deps.sendKey(session.tmuxPane, 'Escape').catch(() => false)
+ await sleep(100)
+ const next = await this.deps.capture(session.tmuxPane, 100).catch(() => null)
+ if (!next || !inspectRuntimePane(session.engine, next).dialog) break
+ }
+ }
+ if (controlStarted) this.deps.manager.cancelControl(sessionId)
+ // A failed switch used to leave NOTHING in the log — the picker just flashed open and shut on the
+ // user's terminal and the device said nothing useful. Name the session, engine and reason.
+ const code = error instanceof RuntimeProfileControlError ? error.code : 'TMUX_FAILED'
+ console.warn(`[runtime-profile] ${sessionId.slice(0, 8)} ${session.engine} set ${target.model}@${target.effort} failed: ${code}`)
+ if (error instanceof RuntimeProfileControlError) throw error
+ throw new RuntimeProfileControlError('TMUX_FAILED')
+ } finally {
+ release()
+ }
+ }
+
+ private async setClaude(
+ session: RegisteredSession,
+ target: RuntimeProfile,
+ current: RuntimeProfile | null,
+ options: Array<{ id: string }>,
+ ): Promise<void> {
+ if (current?.model !== target.model) {
+ if (!await this.deps.sendText(session.tmuxPane, `/model ${target.model}`)) {
+ throw new RuntimeProfileControlError('TMUX_FAILED')
+ }
+ if (!await this.waitClaudeModel(session)) throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
+ }
+
+ if (current?.effort === target.effort) {
+ this.deps.manager.confirmEffort(session.sessionId, target.effort)
+ return
+ }
+
+ const hasExplicitEffort = options.some((option) => {
+ const profile = parseRuntimeProfile(option.id)
+ return profile?.model === target.model && profile.effort !== 'auto'
+ })
+ if (!hasExplicitEffort && target.effort === 'auto') {
+ this.deps.manager.confirmEffort(session.sessionId, 'auto')
+ return
+ }
+ if (!await this.deps.sendText(session.tmuxPane, `/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')
+ if (!await this.deps.manager.waitForProfile(session.sessionId, 2_000)) {
+ throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
+ }
+ }
+ }
+
+ 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)
+ if (capture && /switch model|change model|continue.*model|re-read.*history/i.test(stripAnsi(capture))) {
+ await this.deps.sendKey(session.tmuxPane, 'Enter')
+ } else {
+ // Claude and Codex can swallow the first Enter immediately after a tmux literal write.
+ await this.deps.sendKey(session.tmuxPane, 'Enter')
+ }
+ return this.deps.manager.waitForModel(session.sessionId, COMMAND_CONFIRM_MS)
+ }
+
+ /**
+ * Devin takes the whole profile in one command: `/model <id>` accepts the exact id from
+ * `devin models list` (effort included), and answers in the pane — `✓ Model set to <name>` or
+ * `✗ Model not available`. That explicit answer is why devin needs no picker driving at all, and why an
+ * unavailable model (most of them, on a free plan) fails fast instead of timing out.
+ */
+ 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}`)) {
+ throw new RuntimeProfileControlError('TMUX_FAILED')
+ }
+ const answered = await this.waitPane(
+ session.tmuxPane,
+ (value) => devinModelCommandResult(stripAnsi(value)) !== null,
+ COMMAND_CONFIRM_MS,
+ )
+ if (!answered) throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
+ if (devinModelCommandResult(stripAnsi(answered)) === 'unavailable') {
+ throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
+ }
+ // The acknowledgement line is not the state — the footer is, and only `ingestPane` reads it. Nothing
+ // else feeds the manager during a control, so the wait has to do the feeding itself (same shape as
+ // setCursor); waiting on `waitForProfile` alone timed out on a switch that had already landed.
+ if (!await this.waitObservedProfile(session, target)) {
+ throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
+ }
+ }
+
+ /**
+ * Pi splits the axes: `/model <provider/model>` takes a target directly, while the thinking level lives
+ * only in `/settings` → "Thinking Level", a fixed ladder walked with the arrow keys. Both were driven by
+ * hand first; the ladder's order is what makes the arrow count deterministic (see PI_THINKING_LEVELS).
+ */
+ private async setPi(
+ session: RegisteredSession,
+ target: RuntimeProfile,
+ current: RuntimeProfile | null,
+ ): Promise<void> {
+ if (current?.model !== target.model) {
+ if (!await this.deps.sendText(session.tmuxPane, `/model ${target.model}`)) {
+ throw new RuntimeProfileControlError('TMUX_FAILED')
+ }
+ if (!await this.deps.manager.waitForModel(session.sessionId, COMMAND_CONFIRM_MS)) {
+ throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
+ }
+ }
+ if (target.effort === 'auto' || current?.effort === target.effort) {
+ this.deps.manager.confirmEffort(session.sessionId, target.effort)
+ return
+ }
+ await this.setPiThinking(session, target)
+ }
+
+ private async setPiThinking(session: RegisteredSession, target: RuntimeProfile): Promise<void> {
+ const effort = target.effort
+ if (!await this.deps.sendText(session.tmuxPane, '/settings')) {
+ throw new RuntimeProfileControlError('TMUX_FAILED')
+ }
+ if (!await this.waitPane(session.tmuxPane, (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')) {
+ throw new RuntimeProfileControlError('TMUX_FAILED')
+ }
+ const ladder = await this.waitPane(
+ session.tmuxPane,
+ (v) => /Select reasoning depth/i.test(stripAnsi(v)),
+ PICKER_OPEN_MS,
+ )
+ if (!ladder) throw new RuntimeProfileControlError('EFFORT_UNSUPPORTED')
+
+ // Walk the ladder ONE key at a time, re-reading the cursor after each. Counting the steps up front and
+ // firing them blind is what an open-loop drive looks like, and it is exactly how this went wrong: a
+ // stale first read sent the cursor to `off` and committed it. Re-reading also means a ladder that
+ // scrolls, clamps at an end, or gains a level cannot desynchronise the walk.
+ let selection = parsePiThinkingSelection(stripAnsi(ladder))
+ if (!selection || piThinkingSteps(selection, effort) === null) {
+ throw new RuntimeProfileControlError('EFFORT_UNSUPPORTED')
+ }
+ 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')) {
+ throw new RuntimeProfileControlError('TMUX_FAILED')
+ }
+ const moved = await this.waitPane(
+ session.tmuxPane,
+ (value) => {
+ const next = parsePiThinkingSelection(stripAnsi(value))
+ return !!next && next !== selection
+ },
+ PICKER_STEP_MS,
+ )
+ // No movement means the cursor is pinned at an end of the ladder — pressing on cannot reach it.
+ if (!moved) throw new RuntimeProfileControlError('EFFORT_UNSUPPORTED')
+ selection = parsePiThinkingSelection(stripAnsi(moved))
+ }
+ if (selection !== effort) throw new RuntimeProfileControlError('EFFORT_UNSUPPORTED')
+ await this.deps.sendKey(session.tmuxPane, 'Enter')
+ // The ladder returns to the settings list; Escape closes it so the pane is idle again.
+ await this.deps.sendKey(session.tmuxPane, 'Escape')
+ if (!await this.waitObservedProfile(session, target)) {
+ throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
+ }
+ }
+
+ /** 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) => {
+ this.deps.manager.ingestPane(session, value, true)
+ return this.deps.manager.selectedModel(session) === target.id
+ }, COMMAND_CONFIRM_MS)
+ return !!confirmed
+ }
+
+ /**
+ * OpenCode switches through `/models`, a picker with a typed filter. It is driven by NARROWING, never by
+ * arrowing: type the model's words plus its provider's, and press Enter only once exactly one row is
+ * left and that row is the requested model. If the filter leaves two rows (two providers can carry the
+ * same model name) the switch is refused rather than guessed — picking the wrong model silently is worse
+ * than not switching, and blind arrow-driving is what sank the Command Code attempt.
+ */
+ private async setOpencode(session: RegisteredSession, target: RuntimeProfile): Promise<void> {
+ const entry = (await this.deps.manager.opencodeCatalog()).find((item) => item.id === target.model)
+ if (!entry) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
+ // "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')) {
+ throw new RuntimeProfileControlError('TMUX_FAILED')
+ }
+ if (!await this.waitPane(
+ session.tmuxPane,
+ (v) => countOpencodePickers(stripAnsi(v)) > before,
+ PICKER_OPEN_MS,
+ )) {
+ throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
+ }
+ if (!await this.deps.sendLiteral(session.tmuxPane, entry.filter)) {
+ throw new RuntimeProfileControlError('TMUX_FAILED')
+ }
+ const narrowed = await this.waitPane(
+ session.tmuxPane,
+ (v) => (parseOpencodePickerRows(stripAnsi(v)) ?? []).length === 1,
+ PICKER_STEP_MS,
+ )
+ const rows = narrowed ? parseOpencodePickerRows(stripAnsi(narrowed)) ?? [] : []
+ if (rows.length !== 1 || !opencodeRowMatches(entry, rows[0])) {
+ throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
+ }
+ if (!await this.deps.sendKey(session.tmuxPane, 'Enter')) {
+ throw new RuntimeProfileControlError('TMUX_FAILED')
+ }
+ if (!await this.waitObservedProfile(session, target)) {
+ throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
+ }
+ }
+
+ /**
+ * Command Code 1.6.0 takes both axes as arguments: `/model <vendor/id>` and `/effort <level>`. Neither
+ * opens a dialog, which is the whole reason switching is back after the 2026-07-30 revert — the version
+ * gate in supportsNativeRuntimeControl keeps older builds, where only an arrow-driven picker existed,
+ * out of this path.
+ *
+ * Effort is per model and the catalog does not say which models have one, so a refusal is expected
+ * traffic: the CLI answers "Reasoning effort not supported for X." and that becomes EFFORT_UNSUPPORTED.
+ */
+ private async setCommandcode(
+ session: RegisteredSession,
+ target: RuntimeProfile,
+ current: RuntimeProfile | null,
+ ): Promise<void> {
+ const entry = this.deps.manager.commandcodeTarget(session.sessionId, target.id)
+ if (!entry) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
+
+ if (current?.model !== target.model) {
+ if (!await this.deps.sendText(session.tmuxPane, `/model ${entry.id}`)) {
+ throw new RuntimeProfileControlError('TMUX_FAILED')
+ }
+ if (!await this.waitObservedModel(session, target)) {
+ throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
+ }
+ }
+
+ if (target.effort === 'auto' || current?.effort === target.effort) {
+ this.deps.manager.confirmEffort(session.sessionId, target.effort)
+ return
+ }
+ // 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}`)) {
+ throw new RuntimeProfileControlError('TMUX_FAILED')
+ }
+ const deadline = Date.now() + COMMAND_CONFIRM_MS
+ while (Date.now() < deadline) {
+ // 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) ?? '')
+ if (countCommandcodeRefusals(capture) > refusalsBefore) {
+ throw new RuntimeProfileControlError('EFFORT_UNSUPPORTED')
+ }
+ await sleep(150)
+ }
+ throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
+ }
+
+ /**
+ * Hermes' `/model` is a two-level picker — provider page, then that provider's models — with no way to
+ * type or jump. It is walked one arrow at a time, re-reading the `❯` cursor after every key, so a page
+ * that scrolls or reorders cannot desynchronise the walk. If the cursor stops moving before it reaches
+ * the target, the target is not on the page and the switch is refused rather than committed blind.
+ *
+ * Only MODELS are switchable; hermes keeps its reasoning effort in config.yaml with no in-session
+ * command, so hermesModels never offers an effort row to get here (see hermesModels).
+ */
+ 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')) {
+ throw new RuntimeProfileControlError('TMUX_FAILED')
+ }
+ const opened = await this.waitPane(
+ session.tmuxPane,
+ (v) => !!parseHermesPickerPage(stripAnsi(v)),
+ PICKER_OPEN_MS,
+ )
+ if (!opened) throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
+
+ // Page 1: the provider. Its row reads "Anthropic (13 models)", so match on the leading name.
+ if (entry.provider) {
+ await this.walkHermesPage(session, (row) => hermesProviderMatches(row, entry.provider))
+ if (!await this.waitPane(
+ session.tmuxPane,
+ (v) => (parseHermesPickerPage(stripAnsi(v))?.rows ?? []).some((row) => row === entry.id),
+ PICKER_OPEN_MS,
+ )) {
+ throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
+ }
+ }
+ // Page 2: the model itself, listed by exact id.
+ await this.walkHermesPage(session, (row) => row === entry.id)
+ if (!await this.waitObservedModel(session, target)) {
+ throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
+ }
+ }
+
+ /** Move the `❯` cursor onto the row `wanted` selects, then commit it with Enter. */
+ private async walkHermesPage(
+ session: RegisteredSession,
+ 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 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')) {
+ throw new RuntimeProfileControlError('TMUX_FAILED')
+ }
+ return
+ }
+ 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')) {
+ throw new RuntimeProfileControlError('TMUX_FAILED')
+ }
+ const moved = await this.waitPane(session.tmuxPane, (v) => {
+ const next = parseHermesPickerPage(stripAnsi(v))
+ return !!next?.selected && next.selected !== page.selected
+ }, PICKER_STEP_MS)
+ if (!moved) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
+ }
+ throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
+ }
+
+ /** 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) => {
+ this.deps.manager.ingestPane(session, value, true)
+ return parseRuntimeProfile(this.deps.manager.selectedModel(session))?.model === target.model
+ }, COMMAND_CONFIRM_MS)
+ return !!confirmed
+ }
+
+ private async setCodex(session: RegisteredSession, target: RuntimeProfile): Promise<void> {
+ if (!await this.deps.sendText(session.tmuxPane, '/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)
+ if (!capture) {
+ await this.deps.sendKey(session.tmuxPane, 'Enter')
+ capture = await this.waitPane(session.tmuxPane, 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')) {
+ throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
+ }
+ capture = await this.waitPane(
+ session.tmuxPane,
+ (value) => !!parseCodexModelMenuRows(value) || !!parseCodexModelRows(value),
+ PICKER_STEP_MS,
+ )
+ if (!capture) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
+ efforts = null
+ }
+
+ const menu = parseCodexModelMenuRows(capture)
+ if (menu) {
+ 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')
+ capture = await this.waitPane(
+ session.tmuxPane,
+ quickRow
+ ? (value) => !!parseCodexEffortRows(value)
+ : (value) => !!parseCodexModelRows(value),
+ PICKER_STEP_MS,
+ )
+ if (!capture) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
+ efforts = parseCodexEffortRows(capture)
+ }
+
+ if (!efforts) {
+ 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)
+ 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)
+ 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.manager.waitForProfile(session.sessionId, COMMAND_CONFIRM_MS)) {
+ throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
+ }
+ }
+
+ 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}`)) {
+ throw new RuntimeProfileControlError('TMUX_FAILED')
+ }
+ let capture = await this.waitPane(session.tmuxPane, (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)
+ }
+ const picker = capture ? parseCursorModelPicker(capture) : null
+ if (!picker || picker.selectedFamily?.toLowerCase() !== cursorTarget.familyLabel.toLowerCase()) {
+ throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
+ }
+
+ 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 (!capture) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
+
+ if (cursorTarget.context) {
+ await this.setCursorParameter(session, 'context', cursorTarget.context, true)
+ }
+ if (cursorTarget.reasoning) {
+ await this.setCursorParameter(session, 'reasoning', cursorTarget.reasoning, true)
+ }
+ 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)) {
+ throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
+ }
+ if (!await this.deps.sendKey(session.tmuxPane, 'Enter')) throw new RuntimeProfileControlError('TMUX_FAILED')
+ } else {
+ if (!await this.deps.sendKey(session.tmuxPane, 'Enter')) throw new RuntimeProfileControlError('TMUX_FAILED')
+ }
+
+ const confirmed = await this.waitPane(session.tmuxPane, (value) => {
+ this.deps.manager.ingestPane(session, value, true)
+ return this.deps.manager.selectedModel(session) === target.id
+ || this.cursorFooterMatches(value, cursorTarget, target.effort)
+ }, COMMAND_CONFIRM_MS)
+ if (!confirmed) throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
+ if (this.deps.manager.selectedModel(session) !== target.id) {
+ this.deps.manager.confirmControlProfile(target)
+ }
+ }
+
+ private async setCursorParameter(
+ session: RegisteredSession,
+ kind: CursorParameterRow['kind'],
+ value: string,
+ selected: boolean,
+ ): Promise<void> {
+ const capture = await this.deps.capture(session.tmuxPane, 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)
+ if (!target) {
+ if (!selected && (kind === 'fast' || kind === 'thinking')) return
+ throw new RuntimeProfileControlError('EFFORT_UNSUPPORTED')
+ }
+ if (target.selected === selected) return
+ const current = rows.find((row) => row.cursor)
+ 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')
+ await sleep(120)
+ }
+ if (!await this.deps.sendKey(session.tmuxPane, 'Enter')) throw new RuntimeProfileControlError('TMUX_FAILED')
+ const updated = await this.waitPane(session.tmuxPane, (next) => {
+ const nextRows = parseCursorParameterRows(next)
+ return nextRows?.some((row) => row.kind === kind && row.value === value && row.selected === selected) ?? false
+ }, PICKER_STEP_MS)
+ if (!updated) throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
+ }
+
+ private cursorFooterMatches(
+ capture: string,
+ target: CursorModelTarget,
+ effort: string | null,
+ ): boolean {
+ const lines = stripAnsi(capture).split('\n').filter((line) => line.trim()).slice(-15)
+ if (target.rawId === 'auto') return lines.some((line) => /^\s*Auto(?:\s*$|\s*[·│])/i.test(line))
+ return lines.some((line) => {
+ const normalized = line.trim().toLowerCase()
+ if (!normalized.startsWith(target.familyLabel.toLowerCase())) return false
+ const actualFast = /\bfast\b/i.test(line)
+ const actualThinking = !/\bno\s+thinking\b/i.test(line) && /\bthinking\b/i.test(line)
+ if (target.fast != null && actualFast !== target.fast) return false
+ if (target.thinking != null && actualThinking !== target.thinking) return false
+ if (target.context && !normalized.includes(target.context)) return false
+
+ const effortMatch = /\b(extra high|none|low|medium|high|max)\b/i.exec(line)
+ const actualEffort = effortMatch?.[1].toLowerCase().replace(/\s+/g, '') === 'extrahigh'
+ ? 'xhigh'
+ : effortMatch?.[1].toLowerCase() ?? null
+ const footerEffort = target.footerEffort === undefined ? effort : target.footerEffort
+ return footerEffort == null ? actualEffort == null : actualEffort === footerEffort
+ })
+ }
+
+ private async waitPane(pane: 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)
+ if (capture && predicate(capture)) return capture
+ await sleep(100)
+ }
+ return null
+ }
+}
diff --git a/cli/src/lib/selfUpdate.spec.ts b/cli/src/lib/selfUpdate.spec.ts
new file mode 100644
index 000000000..5424afde1
--- /dev/null
+++ b/cli/src/lib/selfUpdate.spec.ts
@@ -0,0 +1,35 @@
+import { mkdtempSync, readFileSync, rmSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { canary, stage } from './selfUpdate.js'
+
+let dirs: string[] = []
+
+function tempDir(): string {
+ const dir = mkdtempSync(join(tmpdir(), 'machine-adapter-self-update-'))
+ dirs.push(dir)
+ return dir
+}
+
+describe('selfUpdate packaging', () => {
+ afterEach(() => {
+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true })
+ dirs = []
+ })
+
+ it('canary runs installed cli.js as ESM', () => {
+ const dir = tempDir()
+ const cli = Buffer.from('#!/usr/bin/env node\nimport { createRequire } from "module";\nconsole.log(createRequire(import.meta.url) ? "1.2.3" : "nope")\n')
+
+ expect(canary(cli, dir)).toBe(true)
+ })
+
+ it('stages the module package metadata next to cli.js', () => {
+ const dir = tempDir()
+
+ stage(dir, Buffer.from('console.log("cli")\n'), Buffer.from('console.log("notify")\n'))
+
+ expect(JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'))).toEqual({ type: 'module' })
+ })
+})
diff --git a/cli/src/lib/selfUpdate.ts b/cli/src/lib/selfUpdate.ts
new file mode 100644
index 000000000..109db20d4
--- /dev/null
+++ b/cli/src/lib/selfUpdate.ts
@@ -0,0 +1,172 @@
+/**
+ * Self-update mechanics — PURE (no process-control; the daemon decides when to restart).
+ *
+ * The daemon polls a GCS `metadata.json` (same shape as the device OTA manifest), and when a strictly
+ * newer build is published it downloads `cli.js` + `notify.mjs`, verifies sha256 IN MEMORY (so a bad
+ * download never touches disk), canary-runs the new bundle, then atomically swaps them into the install
+ * dir (keeping a `.prev` for rollback). Firing the restart, supervising the new process, and rolling
+ * back are all the CALLER's job (`restartForUpdate` in cli.ts) — this module only stages.
+ *
+ * Manifest entry shape (key = ADAPTER_UPDATE_KEY, coexists with the device `commander` key):
+ * { "adapter": { "version": "0.0.2",
+ * "cli": { "url": "…/cli.js", "sha256": "…", "size": N },
+ * "notify": { "url": "…/notify.mjs","sha256": "…", "size": M } } }
+ */
+
+import { createHash } from 'crypto'
+import { copyFileSync, existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from 'fs'
+import { spawnSync } from 'child_process'
+import { join } from 'path'
+
+export interface FileRef {
+ url: string
+ sha256: string
+ size?: number
+}
+export interface UpdateEntry {
+ version: string
+ cli: FileRef
+ notify: FileRef
+}
+
+const CLI = 'cli.js'
+const NOTIFY = 'notify.mjs'
+const PACKAGE = 'package.json'
+const RUNTIME_PACKAGE = `${JSON.stringify({ type: 'module' })}\n`
+
+/** Strict semver-greater on the `X.Y.Z` core (ignores pre-release/build). Unparseable → false, so a
+ * malformed manifest or the `0.0.0-dev` dev sentinel never triggers a downgrade/oscillation. */
+export function semverGt(a: string, b: string): boolean {
+ const parse = (v: string): number[] | null => {
+ const m = /^(\d+)\.(\d+)\.(\d+)/.exec(v)
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null
+ }
+ const x = parse(a)
+ const y = parse(b)
+ if (!x || !y) return false
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i]
+ return false
+}
+
+/** Fetch + parse the manifest; return this adapter's entry, or null (unreachable / malformed / absent). */
+export async function fetchManifest(url: string, key: string): Promise<UpdateEntry | null> {
+ // No `cache` option needed: undici doesn't HTTP-cache by default and GCS serves the manifest no-cache.
+ const res = await fetch(url)
+ if (!res.ok) return null
+ const json = (await res.json()) as Record<string, unknown>
+ const entry = json?.[key] as Partial<UpdateEntry> | undefined
+ const okFile = (f: unknown): f is FileRef =>
+ !!f && typeof (f as FileRef).url === 'string' && typeof (f as FileRef).sha256 === 'string'
+ if (!entry || typeof entry.version !== 'string' || !okFile(entry.cli) || !okFile(entry.notify)) return null
+ return { version: entry.version, cli: entry.cli, notify: entry.notify }
+}
+
+/** Download one file and verify its sha256 in memory; throws on a non-2xx or a digest mismatch. */
+export async function downloadVerified(ref: FileRef): Promise<Buffer> {
+ const res = await fetch(ref.url)
+ if (!res.ok) throw new Error(`download ${ref.url} → HTTP ${res.status}`)
+ const buf = Buffer.from(await res.arrayBuffer())
+ const got = createHash('sha256').update(buf).digest('hex')
+ if (got.toLowerCase() !== ref.sha256.toLowerCase()) {
+ throw new Error(`sha256 mismatch for ${ref.url}: expected ${ref.sha256}, got ${got}`)
+ }
+ return buf
+}
+
+/** Cheap runnability check: write the new bundle into a temp install-shaped dir and run
+ * `node cli.js version`. This catches broken ESM/CJS packaging before the live install is touched. */
+export function canary(cliBuf: Buffer, dir: string): boolean {
+ const tmpDir = join(dir, `.canary-${process.pid}-${Date.now()}`)
+ const tmpCli = join(tmpDir, CLI)
+ try {
+ mkdirSync(tmpDir, { recursive: true })
+ writeFileSync(join(tmpDir, PACKAGE), RUNTIME_PACKAGE)
+ writeFileSync(tmpCli, cliBuf)
+ const r = spawnSync(process.execPath, [tmpCli, 'version'], { timeout: 15_000, stdio: 'ignore' })
+ return r.status === 0
+ } catch {
+ return false
+ } finally {
+ try { rmSync(tmpDir, { recursive: true, force: true }) } catch { /* ignore */ }
+ }
+}
+
+/** Atomically swap the new bytes into `dir`, backing up the current files to `.prev` for rollback.
+ * (Verify-in-memory first ⇒ we only ever write bytes we already trust; write-tmp+rename ⇒ no torn file.) */
+export function stage(dir: string, cliBuf: Buffer, notifyBuf: Buffer): void {
+ mkdirSync(dir, { recursive: true })
+ writeFileSync(join(dir, PACKAGE), RUNTIME_PACKAGE)
+ const swap = (name: string, buf: Buffer): void => {
+ const target = join(dir, name)
+ if (existsSync(target)) copyFileSync(target, `${target}.prev`)
+ const tmp = `${target}.tmp`
+ writeFileSync(tmp, buf)
+ renameSync(tmp, target) // atomic within the same filesystem
+ }
+ swap(CLI, cliBuf)
+ swap(NOTIFY, notifyBuf)
+}
+
+/** Roll a failed update back to the `.prev` bytes (called by the supervisor when the new build crashes). */
+export function restore(dir: string): void {
+ for (const name of [CLI, NOTIFY]) {
+ const prev = join(dir, `${name}.prev`)
+ if (existsSync(prev)) { try { renameSync(prev, join(dir, name)) } catch { /* ignore */ } }
+ }
+}
+
+/** Drop the `.prev` backups once the new build is confirmed healthy. */
+export function confirm(dir: string): void {
+ for (const name of [CLI, NOTIFY]) {
+ try { rmSync(join(dir, `${name}.prev`), { force: true }) } catch { /* ignore */ }
+ }
+}
+
+export interface Poller { stop(): void }
+
+/**
+ * Poll on an interval; on the first strictly-newer, verified, canary-passed build, STAGE it and call
+ * `onStaged(version)` exactly once, then stop polling (the caller restarts immediately). Every failure
+ * (fetch/parse/sha/canary/disk) is swallowed and simply retried next tick — the daemon never crashes
+ * on a bad update.
+ */
+export function startSelfUpdater(opts: {
+ currentVersion: string
+ url: string
+ key: string
+ dir: string
+ intervalMs: number
+ onStaged: (version: string) => void
+}): Poller {
+ let checking = false
+ let done = false
+ let timer: NodeJS.Timeout | null = null
+
+ const stop = (): void => { if (timer) { clearInterval(timer); timer = null } }
+
+ const tick = async (): Promise<void> => {
+ if (checking || done) return
+ checking = true
+ try {
+ const entry = await fetchManifest(opts.url, opts.key)
+ if (!entry || !semverGt(entry.version, opts.currentVersion)) return
+ console.log(`[update] newer build available: ${opts.currentVersion} → ${entry.version}`)
+ const cliBuf = await downloadVerified(entry.cli)
+ const notifyBuf = await downloadVerified(entry.notify)
+ if (!canary(cliBuf, opts.dir)) { console.error('[update] canary failed for the new build — skipping'); return }
+ stage(opts.dir, cliBuf, notifyBuf)
+ done = true
+ stop()
+ console.log(`[update] staged ${entry.version} — restarting now`)
+ opts.onStaged(entry.version)
+ } catch (err) {
+ console.error('[update] check failed (will retry):', err instanceof Error ? err.message : err)
+ } finally {
+ checking = false
+ }
+ }
+
+ timer = setInterval(() => void tick(), opts.intervalMs)
+ void tick() // also check immediately on start
+ return { stop }
+}
diff --git a/cli/src/lib/sessionInput.spec.ts b/cli/src/lib/sessionInput.spec.ts
new file mode 100644
index 000000000..c596827fa
--- /dev/null
+++ b/cli/src/lib/sessionInput.spec.ts
@@ -0,0 +1,324 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { SessionInputController } from './sessionInput.js'
+import type { RegisteredSession } from './registry.js'
+
+function session(engine: 'claude' | 'codex' | 'cursor' | 'commandcode' = 'codex'): RegisteredSession {
+ return {
+ 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,
+ registeredAt: 1, updatedAt: 1, lastHookAt: 1, lastTranscriptAt: 1,
+ }
+}
+
+describe('SessionInputController', () => {
+ afterEach(() => vi.useRealTimers())
+
+ it('queues Codex prompts while busy and drains exactly one after turn end', async () => {
+ const injected: string[] = []
+ const controller = new SessionInputController({
+ getSession: () => session(), validateRuntime: async () => true,
+ inject: async (_pane, content) => { injected.push(content); return true },
+ sendKey: async () => true, onError: vi.fn(),
+ })
+ controller.setTurnOpen('s1', true)
+ controller.submit('s1', 'second')
+ controller.submit('s1', 'third')
+ expect(injected).toEqual([])
+ controller.onTurnEnded('s1')
+ await vi.waitFor(() => expect(injected).toEqual(['second']))
+ controller.onTurnStarted('s1', 'second')
+ controller.onTurnEnded('s1')
+ await vi.waitFor(() => expect(injected).toEqual(['second', 'third']))
+ controller.forget('s1')
+ })
+
+ it('clears the echoed prompt from the Cursor composer once the turn starts', async () => {
+ const sendKey = vi.fn(async (_pane: string, _key: string) => true)
+ const controller = new SessionInputController({
+ getSession: () => session('cursor'), validateRuntime: async () => true,
+ inject: async () => true, sendKey,
+ capture: async () => '⠰ Working\n\n→ hello\nAuto', // the submitted prompt is still on screen
+ onError: vi.fn(),
+ })
+
+ controller.onTurnStarted('s1', 'hello')
+ await vi.waitFor(() => expect(sendKey.mock.calls.filter(([, k]) => k === 'C-u')).toHaveLength(1))
+ controller.forget('s1')
+ })
+
+ it('leaves a fresh terminal draft alone when the Cursor composer no longer echoes our prompt', async () => {
+ const sendKey = vi.fn(async (_pane: string, _key: string) => true)
+ const controller = new SessionInputController({
+ getSession: () => session('cursor'), validateRuntime: async () => true,
+ inject: async () => true, sendKey,
+ capture: async () => '⠰ Working\n\n→ something the user just typed\nAuto',
+ onError: vi.fn(),
+ })
+
+ controller.onTurnStarted('s1', 'hello')
+ await new Promise((r) => setTimeout(r, 20))
+ expect(sendKey.mock.calls.filter(([, k]) => k === 'C-u')).toHaveLength(0)
+ controller.forget('s1')
+ })
+
+ it('clears the Cursor composer before pasting so a stale prompt cannot be appended to', async () => {
+ // Cursor keeps the previous prompt on its "→" line after the turn finishes. Without a clear, the next
+ // message is typed onto the end of it and the two are submitted as one run-on prompt — observed as a
+ // turn starting with the PREVIOUS message's text.
+ const order: string[] = []
+ const controller = new SessionInputController({
+ getSession: () => session('cursor'), validateRuntime: async () => true,
+ inject: async (_pane, content) => { order.push(`inject:${content}`); return true },
+ sendKey: async (_pane, key) => { order.push(`key:${key}`); return true },
+ onError: vi.fn(),
+ })
+ controller.submit('s1', 'second question')
+ await vi.waitFor(() => expect(order).toContain('inject:second question'))
+ expect(order[0]).toBe('key:C-u')
+ expect(order[1]).toBe('inject:second question')
+ controller.forget('s1')
+ })
+
+ it('retries Enter without reinjecting the prompt body', async () => {
+ vi.useFakeTimers()
+ const inject = vi.fn(async () => true)
+ const sendKey = vi.fn(async () => true)
+ const controller = new SessionInputController({
+ getSession: () => session(), validateRuntime: async () => true, inject, sendKey, onError: vi.fn(),
+ })
+ controller.submit('s1', 'hello')
+ await vi.advanceTimersByTimeAsync(3_100)
+ expect(inject).toHaveBeenCalledTimes(1)
+ expect(sendKey).toHaveBeenCalledTimes(2)
+ controller.forget('s1')
+ })
+
+ it('waits longer before retrying Claude submit verification', async () => {
+ vi.useFakeTimers()
+ const inject = vi.fn(async () => true)
+ const sendKey = vi.fn(async () => true)
+ const controller = new SessionInputController({
+ getSession: () => session('claude'), validateRuntime: async () => true, inject, sendKey, onError: vi.fn(),
+ })
+ controller.submit('s1', 'hello')
+ await vi.advanceTimersByTimeAsync(2_900)
+ expect(sendKey).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(200)
+ expect(sendKey).toHaveBeenCalledTimes(1)
+ controller.forget('s1')
+ })
+
+ it('does not retry Enter for Cursor after the TUI is already working', async () => {
+ vi.useFakeTimers()
+ const inject = vi.fn(async () => true)
+ const sendKey = vi.fn(async (_pane: string, _key: string) => true)
+ const onError = vi.fn()
+ const controller = new SessionInputController({
+ getSession: () => session('cursor'),
+ validateRuntime: async () => true,
+ inject,
+ sendKey,
+ capture: async () => '⠰ Working\n\n→ hello\nAuto',
+ onError,
+ })
+
+ controller.submit('s1', 'hello')
+ await vi.advanceTimersByTimeAsync(5_100)
+
+ expect(inject).toHaveBeenCalledTimes(1)
+ // Assert on ENTER specifically, not on the total key count: every Cursor injection also sends a
+ // C-u first to clear a stale composer, and that is not a retry.
+ expect(sendKey.mock.calls.filter(([, key]) => key === 'Enter')).toHaveLength(0)
+ expect(onError).not.toHaveBeenCalled()
+ controller.forget('s1')
+ })
+
+ it('retries Enter for Cursor only while the exact draft remains in an idle composer', async () => {
+ vi.useFakeTimers()
+ const sendKey = vi.fn(async (_pane: string, _key: string) => true)
+ const controller = new SessionInputController({
+ getSession: () => session('cursor'),
+ validateRuntime: async () => true,
+ inject: async () => true,
+ sendKey,
+ capture: async () => '→ hello\n\nAuto',
+ onError: vi.fn(),
+ })
+
+ controller.submit('s1', 'hello')
+ await vi.advanceTimersByTimeAsync(1_600)
+
+ // One retry ENTER. The C-u that precedes every Cursor paste is not counted here.
+ expect(sendKey.mock.calls.filter(([, key]) => key === 'Enter')).toHaveLength(1)
+ controller.forget('s1')
+ })
+
+ it('waits for the Cursor composer to settle before draining the next prompt', async () => {
+ vi.useFakeTimers()
+ const injected: string[] = []
+ const controller = new SessionInputController({
+ getSession: () => session('cursor'),
+ validateRuntime: async () => true,
+ inject: async (_pane, content) => { injected.push(content); return true },
+ sendKey: async () => true,
+ onError: vi.fn(),
+ })
+
+ controller.onTurnStarted('s1', 'first')
+ controller.onTurnEnded('s1')
+ controller.submit('s1', 'second')
+ await vi.advanceTimersByTimeAsync(700)
+ expect(injected).toEqual([])
+ await vi.advanceTimersByTimeAsync(100)
+ expect(injected).toEqual(['second'])
+ controller.forget('s1')
+ })
+
+ it('does not error or press Enter for Claude once the prompt has left the composer', async () => {
+ vi.useFakeTimers()
+ const sendKey = vi.fn(async () => true)
+ const onError = vi.fn()
+ const controller = new SessionInputController({
+ getSession: () => session('claude'),
+ validateRuntime: async () => true,
+ inject: async () => true,
+ sendKey,
+ capture: async () => '❯ \n✻ Working (esc to interrupt)',
+ onError,
+ })
+
+ controller.submit('s1', 'hello')
+ await vi.advanceTimersByTimeAsync(3_100 * 4)
+
+ expect(sendKey).not.toHaveBeenCalled()
+ expect(onError).not.toHaveBeenCalled()
+ controller.forget('s1')
+ })
+
+ it('accepts a Command Code prompt the moment its pane says the agent is working', async () => {
+ // Command Code writes the user line to its transcript only after the model finishes thinking — 30s on
+ // a real task — so waiting for turn_started declared "the agent did not accept this message" while the
+ // terminal plainly showed the message accepted and the work under way.
+ vi.useFakeTimers()
+ const sendKey = vi.fn(async () => true)
+ const onError = vi.fn()
+ const controller = new SessionInputController({
+ getSession: () => session('commandcode'),
+ validateRuntime: async () => true,
+ inject: async () => true,
+ sendKey,
+ // Its real pane: the composer back to its placeholder, the turn running above it.
+ capture: async () => '❯ build me a game\n✧ Sculpting… esc to interrupt • 59s\n────\n❯ Ask your question...',
+ onError,
+ })
+
+ controller.submit('s1', 'build me a game')
+ await vi.advanceTimersByTimeAsync(6_100 * 6)
+
+ expect(onError).not.toHaveBeenCalled()
+ expect(sendKey).not.toHaveBeenCalled() // and no stray Enter into a live composer
+ controller.forget('s1')
+ })
+
+ it('retries Enter then errors for Claude while the prompt stays in the composer', async () => {
+ vi.useFakeTimers()
+ const sendKey = vi.fn(async () => true)
+ const onError = vi.fn()
+ const controller = new SessionInputController({
+ getSession: () => session('claude'),
+ validateRuntime: async () => true,
+ inject: async () => true,
+ sendKey,
+ capture: async () => '❯ hello',
+ onError,
+ })
+
+ controller.submit('s1', 'hello')
+ await vi.advanceTimersByTimeAsync(3_100 * 3)
+
+ expect(sendKey).toHaveBeenCalledTimes(2)
+ expect(onError).toHaveBeenCalledWith('s1', expect.stringContaining('did not accept'))
+ controller.forget('s1')
+ })
+
+ it('does not error or press Enter for Codex once the prompt has left the composer', async () => {
+ vi.useFakeTimers()
+ const sendKey = vi.fn(async () => true)
+ const onError = vi.fn()
+ const controller = new SessionInputController({
+ getSession: () => session('codex'),
+ validateRuntime: async () => true,
+ inject: async () => true,
+ sendKey,
+ capture: async () => '› Find and fix a bug in @filename\n gpt-5.5 medium ·',
+ onError,
+ })
+
+ controller.submit('s1', 'hello')
+ await vi.advanceTimersByTimeAsync(1_600 * 4)
+
+ expect(sendKey).not.toHaveBeenCalled()
+ expect(onError).not.toHaveBeenCalled()
+ controller.forget('s1')
+ })
+
+ it('retries Enter then errors for Codex while the prompt stays in the composer', async () => {
+ vi.useFakeTimers()
+ const sendKey = vi.fn(async () => true)
+ const onError = vi.fn()
+ const controller = new SessionInputController({
+ getSession: () => session('codex'),
+ validateRuntime: async () => true,
+ inject: async () => true,
+ sendKey,
+ capture: async () => '› hello',
+ onError,
+ })
+
+ controller.submit('s1', 'hello')
+ await vi.advanceTimersByTimeAsync(1_600 * 3)
+
+ expect(sendKey).toHaveBeenCalledTimes(2)
+ expect(onError).toHaveBeenCalledWith('s1', expect.stringContaining('did not accept'))
+ controller.forget('s1')
+ })
+
+ it('falls back to blind retry/error when no pane capture is available', async () => {
+ vi.useFakeTimers()
+ const sendKey = vi.fn(async () => true)
+ const onError = vi.fn()
+ const controller = new SessionInputController({
+ getSession: () => session('codex'),
+ validateRuntime: async () => true,
+ inject: async () => true,
+ sendKey,
+ onError,
+ })
+
+ controller.submit('s1', 'hello')
+ await vi.advanceTimersByTimeAsync(1_600 * 3)
+
+ expect(sendKey).toHaveBeenCalledTimes(2)
+ expect(onError).toHaveBeenCalledWith('s1', expect.stringContaining('did not accept'))
+ controller.forget('s1')
+ })
+
+ it('serializes chat input behind a native runtime control lock', async () => {
+ const injected: string[] = []
+ const controller = new SessionInputController({
+ getSession: () => session('claude'), validateRuntime: async () => true,
+ inject: async (_pane, content) => { injected.push(content); return true },
+ sendKey: async () => true, onError: vi.fn(),
+ })
+
+ const release = controller.acquireControl('s1')
+ expect(release).toBeTypeOf('function')
+ expect(controller.acquireControl('s1')).toBeNull()
+ controller.submit('s1', 'wait behind control')
+ expect(injected).toEqual([])
+
+ release?.()
+ await vi.waitFor(() => expect(injected).toEqual(['wait behind control']))
+ controller.forget('s1')
+ })
+})
diff --git a/cli/src/lib/sessionInput.ts b/cli/src/lib/sessionInput.ts
new file mode 100644
index 000000000..01930d2f6
--- /dev/null
+++ b/cli/src/lib/sessionInput.ts
@@ -0,0 +1,421 @@
+import { createHash } from 'crypto'
+import type { RegisteredSession } from './registry.js'
+import { sid } from './log.js'
+
+const MAX_QUEUE_ITEMS = 8
+const MAX_QUEUE_BYTES = 24 * 1024
+const ITEM_TTL_MS = 5 * 60_000
+const SUBMIT_VERIFY_MS = 1_500
+const CLAUDE_SUBMIT_VERIFY_MS = 3_000
+// OpenCode's accept signal is the reader's DB poll (~1s) surfacing a new user row → turn_started, so
+// give it a slightly longer window than the file-based engines before a retry-Enter.
+const OPENCODE_SUBMIT_VERIFY_MS = 2_500
+// Pi has no composer glyph either, and its JSONL is written per completed message — give the derived
+// turn_started a comparable window before re-pressing Enter.
+const PI_SUBMIT_VERIFY_MS = 2_500
+// Hermes' composer glyph (`❯`) is user-skinnable, so it is verified from the DB like opencode/pi. Its
+// user row lands at turn start, so the window matches theirs.
+const HERMES_SUBMIT_VERIFY_MS = 2_500
+// Command Code's composer is a bare `>` (and `/`+`@` open autocompletes that swallow Enter), so it is
+// verified from the transcript like opencode/pi/hermes. Unlike them it does not write the user record on
+// Enter: the file is flushed per model round-trip, so the record only lands once the first response comes
+// back (measured 3.2s on its fastest model). A shorter window fires a spurious retry-Enter on every
+// injection and can raise a false "did not accept" — so this window covers model TTFT, not terminal echo.
+const COMMANDCODE_SUBMIT_VERIFY_MS = 6_000
+// Devin's accept signal is its sessions.db poll (~1s) surfacing the new user row. Unlike Command Code it
+// writes that row on Enter rather than when the model round-trip commits (measured: turn_started 1.1s
+// after paste), so it needs only the same poll-sized window as opencode/pi/hermes.
+const DEVIN_SUBMIT_VERIFY_MS = 2_500
+const CURSOR_TURN_SETTLE_MS = 750
+const SUBMIT_MAX_RETRIES = 2
+// Non-cursor engines re-observe the pane (instead of erroring) while an accepted-but-not-yet-started
+// prompt is in flight. Bounded so a truly wedged session eventually reverts to the retry/error path.
+const SUBMIT_MAX_OBSERVES = 5
+
+interface QueuedInput {
+ content: string
+ bytes: number
+ expiresAt: number
+}
+
+interface InputState {
+ turnOpen: boolean
+ awaitingFingerprint: string | null
+ awaitingContent: string | null
+ controlLocked: boolean
+ settling: boolean
+ queue: QueuedInput[]
+ timer: NodeJS.Timeout | null
+ settleTimer: NodeJS.Timeout | null
+ retries: number
+ observes: number
+}
+
+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>
+ onError: (sessionId: string, message: string) => void
+}
+
+function fingerprint(content: string): string {
+ return createHash('sha256').update(content.replace(/\r\n/g, '\n').trim()).digest('hex')
+}
+
+/** Engine-aware prompt injection. Terminal TUIs get a bounded per-session FIFO while a turn is busy. */
+export class SessionInputController {
+ private states = new Map<string, InputState>()
+
+ constructor(private readonly deps: SessionInputDeps) {}
+
+ private state(sessionId: string): InputState {
+ let value = this.states.get(sessionId)
+ if (!value) {
+ value = {
+ turnOpen: false,
+ awaitingFingerprint: null,
+ awaitingContent: null,
+ controlLocked: false,
+ settling: false,
+ queue: [],
+ timer: null,
+ settleTimer: null,
+ retries: 0,
+ observes: 0,
+ }
+ this.states.set(sessionId, value)
+ }
+ return value
+ }
+
+ setTurnOpen(sessionId: string, open: boolean): void {
+ this.state(sessionId).turnOpen = open
+ }
+
+ submit(sessionId: string, content: string): void {
+ const session = this.deps.getSession(sessionId)
+ if (!session) { this.deps.onError(sessionId, 'This agent is no longer available.'); return }
+ const state = this.state(sessionId)
+ this.dropExpired(sessionId, state)
+ if (state.controlLocked
+ || (session.engine !== 'claude' && (state.turnOpen || state.awaitingFingerprint || state.settling))) {
+ console.log(`[inject] ${sid(sessionId)} queued · engine=${session.engine} · depth=${state.queue.length + 1}`)
+ this.enqueue(sessionId, state, content)
+ return
+ }
+ void this.inject(sessionId, session, content)
+ }
+
+ /** Reserve this pane for a short native control interaction such as `/model`. */
+ acquireControl(sessionId: string): (() => void) | null {
+ const session = this.deps.getSession(sessionId)
+ if (!session) return null
+ const state = this.state(sessionId)
+ this.dropExpired(sessionId, state)
+ if (state.controlLocked || state.turnOpen || state.awaitingFingerprint || state.settling || state.queue.length > 0) return null
+ state.controlLocked = true
+ let released = false
+ return () => {
+ if (released) return
+ released = true
+ const current = this.states.get(sessionId)
+ if (!current) return
+ current.controlLocked = false
+ this.drainOne(sessionId, current)
+ }
+ }
+
+ onTurnStarted(sessionId: string, userMessage: string): void {
+ const state = this.state(sessionId)
+ if (state.settleTimer) clearTimeout(state.settleTimer)
+ state.settleTimer = null
+ state.settling = false
+ state.turnOpen = true
+ // Cursor does not clear its composer when it accepts a prompt: the submitted text stays on the "→"
+ // line for the whole turn and long after it, so the terminal reads as if the question is still
+ // waiting to be sent. Clearing before the NEXT paste (see inject) stops the two from running
+ // together, but leaves that stale copy on screen in the meantime. Drop it as soon as the turn is
+ // confirmed started.
+ void this.clearCursorEcho(sessionId, userMessage)
+ if (state.awaitingFingerprint) {
+ const matched = state.awaitingFingerprint === fingerprint(userMessage)
+ if (!matched) console.warn(`[inject] ${sessionId.slice(0, 8)} observed a different terminal prompt while awaiting submit`)
+ state.awaitingFingerprint = null
+ state.awaitingContent = null
+ state.retries = 0
+ state.observes = 0
+ if (state.timer) clearTimeout(state.timer)
+ state.timer = null
+ }
+ }
+
+ /**
+ * Remove Cursor's leftover copy of a just-submitted prompt from its composer.
+ *
+ * Guarded by a pane read on purpose: it only sends the clear when the composer still holds the exact
+ * text we submitted. A blind C-u here would delete a follow-up the user had already started typing in
+ * 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)
+ if (session?.engine !== 'cursor' || !this.deps.capture) return
+ try {
+ const capture = await this.deps.capture(session.tmuxPane)
+ if (!capture || !cursorComposerContains(capture, userMessage)) return
+ await this.deps.sendKey(session.tmuxPane, '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 */
+ }
+ }
+
+ onTurnEnded(sessionId: string): void {
+ const state = this.state(sessionId)
+ state.turnOpen = false
+ state.awaitingFingerprint = null
+ state.awaitingContent = null
+ state.retries = 0
+ state.observes = 0
+ if (state.timer) clearTimeout(state.timer)
+ state.timer = null
+ const session = this.deps.getSession(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.
+ state.settling = true
+ if (state.settleTimer) clearTimeout(state.settleTimer)
+ state.settleTimer = setTimeout(() => {
+ state.settleTimer = null
+ state.settling = false
+ this.drainOne(sessionId, state)
+ }, CURSOR_TURN_SETTLE_MS)
+ return
+ }
+ this.drainOne(sessionId, state)
+ }
+
+ cancel(sessionId: string): void {
+ const session = this.deps.getSession(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')
+ const state = this.state(sessionId)
+ state.turnOpen = false
+ state.awaitingFingerprint = null
+ state.awaitingContent = null
+ if (state.timer) clearTimeout(state.timer)
+ state.timer = null
+ setTimeout(() => this.drainOne(sessionId, state), 250)
+ })
+ }
+
+ forget(sessionId: string): void {
+ const state = this.states.get(sessionId)
+ if (state?.timer) clearTimeout(state.timer)
+ if (state?.settleTimer) clearTimeout(state.settleTimer)
+ this.states.delete(sessionId)
+ }
+
+ private async inject(sessionId: string, session: RegisteredSession, content: string): Promise<void> {
+ const state = this.state(sessionId)
+ if (!(await this.deps.validateRuntime(session))) {
+ console.warn(`[inject] ${sid(sessionId)} abort · engine=${session.engine} · process not running`)
+ this.deps.onError(sessionId, 'This agent process is no longer running.')
+ return
+ }
+ if (session.engine === 'cursor') {
+ // Cursor leaves the previous prompt sitting in its composer after the turn completes — the text is
+ // still on the "→" line long after the answer and its recap have arrived. sendToTmux() types into
+ // whatever is already there, so the next message is APPENDED to the last one and the pair is
+ // submitted as a single run-on prompt:
+ // "…đầu tư dài hạn" + "Có nên mua thêm eth không…"
+ // The agent then answers a question nobody asked, and the device shows a recap for it.
+ //
+ // The adapter already NOTICED this — onTurnStarted logs "observed a different terminal prompt while
+ // awaiting submit" when the fingerprint of the started turn does not match what we sent — but it
+ // only warned and carried on. Clear the line first so the composer is ours alone.
+ //
+ // 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')
+ }
+ if (!(await this.deps.inject(session.tmuxPane, content))) {
+ console.warn(`[inject] ${sid(sessionId)} paste failed · engine=${session.engine} · pane=${session.tmuxPane}`)
+ 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}`)
+ state.awaitingFingerprint = fingerprint(content)
+ state.awaitingContent = content
+ state.retries = 0
+ state.observes = 0
+ this.armSubmitCheck(sessionId, session, state)
+ }
+
+ private armSubmitCheck(sessionId: string, session: RegisteredSession, state: InputState): void {
+ if (state.timer) clearTimeout(state.timer)
+ state.timer = setTimeout(() => {
+ state.timer = null
+ if (!state.awaitingFingerprint || state.turnOpen) return
+ void this.retrySubmit(sessionId, session, state)
+ }, session.engine === 'claude'
+ ? CLAUDE_SUBMIT_VERIFY_MS
+ : session.engine === 'opencode'
+ ? OPENCODE_SUBMIT_VERIFY_MS
+ : session.engine === 'pi'
+ ? PI_SUBMIT_VERIFY_MS
+ : session.engine === 'hermes'
+ ? HERMES_SUBMIT_VERIFY_MS
+ : session.engine === 'commandcode'
+ ? COMMANDCODE_SUBMIT_VERIFY_MS
+ : session.engine === 'devin'
+ ? DEVIN_SUBMIT_VERIFY_MS
+ : SUBMIT_VERIFY_MS)
+ }
+
+ private async retrySubmit(sessionId: string, session: RegisteredSession, state: InputState): Promise<void> {
+ if (session.engine === 'cursor') {
+ const capture = await this.deps.capture?.(session.tmuxPane)
+ if (!state.awaitingFingerprint || state.turnOpen) 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 ?? '')) {
+ console.warn(`[inject] ${sid(sessionId)} not accepted · engine=cursor · composer clear of draft`)
+ state.awaitingFingerprint = null
+ state.awaitingContent = null
+ this.deps.onError(sessionId, 'The agent did not accept the message. Please try again.')
+ return
+ }
+ } else if (session.engine === 'opencode' || session.engine === 'pi' || session.engine === 'hermes') {
+ // OpenCode has no composer glyph, and the submitted text stays visible in the message area, so a
+ // pane scrape can't tell "still in the composer" from "already sent". Rely purely on the reader-
+ // 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
+ } else {
+ // claude/codex/commandcode: verify against the pane before pressing Enter again or declaring failure.
+ const capture = await this.deps.capture?.(session.tmuxPane)
+ 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
+ // watched the terminal accept the message and start working while the device claimed it had been
+ // refused. The pane says so immediately: a running turn shows "esc to interrupt". Treat that as the
+ // acceptance it is, rather than timing out into an error the user can see is false.
+ if (capture && session.engine === 'commandcode' && /esc to interrupt/i.test(visibleTerminal(capture))) {
+ console.log(`[inject] ${sid(sessionId)} accepted (agent working) · engine=commandcode`)
+ state.awaitingFingerprint = null
+ state.awaitingContent = null
+ state.observes = 0
+ return
+ }
+ if (capture && !terminalComposerContains(capture, state.awaitingContent ?? '')) {
+ // Submitted, or queued by the TUI as a follow-up while busy. A real turn_started will confirm
+ // and clear this; keep observing (bounded) WITHOUT pressing Enter — a second Enter could
+ // double-submit a queued follow-up — and WITHOUT a spurious error.
+ if (state.observes < SUBMIT_MAX_OBSERVES) {
+ state.observes++
+ console.log(`[inject] ${sid(sessionId)} accepted (queued/submitted) · engine=${session.engine} · observe=${state.observes}/${SUBMIT_MAX_OBSERVES}`)
+ this.armSubmitCheck(sessionId, session, 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 (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
+ this.deps.onError(sessionId, 'The agent did not accept the message. Please try again.')
+ return
+ }
+ state.retries++
+ console.log(`[inject] ${sid(sessionId)} resubmit Enter · engine=${session.engine} · retry=${state.retries}/${SUBMIT_MAX_RETRIES}`)
+ const valid = await this.deps.validateRuntime(session)
+ if (!valid) {
+ state.awaitingFingerprint = null
+ state.awaitingContent = null
+ 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')
+ this.armSubmitCheck(sessionId, session, state)
+ }
+
+ 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)
+ if (!session) { this.deps.onError(sessionId, 'This agent is no longer available.'); return }
+ void this.inject(sessionId, session, next.content)
+ }
+
+ private enqueue(sessionId: string, state: InputState, content: string): void {
+ const bytes = Buffer.byteLength(content, 'utf8')
+ const queuedBytes = state.queue.reduce((sum, item) => sum + item.bytes, 0)
+ if (state.queue.length >= MAX_QUEUE_ITEMS || queuedBytes + bytes > MAX_QUEUE_BYTES) {
+ this.deps.onError(sessionId, 'This agent already has too many queued messages. Try again after the current operation finishes.')
+ return
+ }
+ state.queue.push({ content, bytes, expiresAt: Date.now() + ITEM_TTL_MS })
+ }
+
+ private dropExpired(sessionId: string, state: InputState): void {
+ const before = state.queue.length
+ const now = Date.now()
+ state.queue = state.queue.filter((item) => item.expiresAt > now)
+ if (state.queue.length < before) this.deps.onError(sessionId, 'A queued message expired before the agent became available.')
+ }
+}
+
+function visibleTerminal(value: string): string {
+ return value.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
+}
+
+function normalizedTerminalText(value: string): string {
+ return visibleTerminal(value).replace(/\s+/g, ' ').trim()
+}
+
+// Composer region = from the last prompt-marker line to the end (mirrors runtimeProfile.currentPaneUi,
+// kept local so sessionInput stays decoupled). Marker set covers claude ❯, codex ›, cursor →.
+function composerRegion(capture: string): string {
+ const lines = visibleTerminal(capture).split('\n')
+ const idx = lines.findLastIndex((line) => {
+ const marker = line.search(/[›❯→]/u)
+ return marker >= 0 && !/^\s*\d+\.\s/.test(line.slice(marker + 1))
+ })
+ return (idx >= 0 ? lines.slice(idx) : lines).join('\n') // no marker → whole pane (safe fallback)
+}
+
+/** True while the injected prompt is still sitting un-submitted in the terminal composer. */
+function terminalComposerContains(capture: string, content: string): boolean {
+ const expected = normalizedTerminalText(content)
+ return !!expected && normalizedTerminalText(composerRegion(capture)).includes(expected)
+}
+
+function cursorComposerContains(capture: string, content: string): boolean {
+ const visible = visibleTerminal(capture)
+ const marker = visible.lastIndexOf('→')
+ if (marker < 0) return false
+ const expected = normalizedTerminalText(content)
+ return !!expected && normalizedTerminalText(visible.slice(marker + 1)).includes(expected)
+}
+
+function cursorSubmissionAccepted(capture: string, content: string): boolean {
+ const visible = visibleTerminal(capture)
+ if (/\bfollow-ups\b/i.test(visible)) return true
+ if (/\b(?:Working|Running subagent|Thinking)\b/i.test(visible)) return true
+ return !cursorComposerContains(visible, content)
+}
diff --git a/cli/src/lib/sessionRepair.spec.ts b/cli/src/lib/sessionRepair.spec.ts
new file mode 100644
index 000000000..d6b8e28fc
--- /dev/null
+++ b/cli/src/lib/sessionRepair.spec.ts
@@ -0,0 +1,171 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+
+/**
+ * Repair binds a live launcher back to a session the daemon lost track of. The danger is not failing to
+ * find one — that only costs a tile until the next turn — it is finding the WRONG one and pointing an
+ * agent at another agent's transcript. So these tests are mostly about when it must refuse.
+ */
+
+const dirs: string[] = []
+afterEach(() => {
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
+ vi.resetModules()
+})
+
+function tempRoot(): string {
+ const dir = mkdtempSync(join(tmpdir(), 'repair-'))
+ dirs.push(dir)
+ return dir
+}
+
+/** A claude-shaped transcript: `<id>.jsonl` under a project dir, first line carrying its cwd. */
+function writeTranscript(root: string, project: string, id: string, cwd: string, mtimeMs: number): void {
+ const dir = join(root, project)
+ mkdirSync(dir, { recursive: true })
+ const file = join(dir, `${id}.jsonl`)
+ writeFileSync(file, `${JSON.stringify({ type: 'session', cwd, id })}\n`)
+ utimesSync(file, new Date(mtimeMs), new Date(mtimeMs))
+}
+
+async function load(claudeProjectsDir: string) {
+ vi.resetModules()
+ process.env.CLAUDE_PROJECTS_DIR = claudeProjectsDir
+ return import('./sessionRepair.js')
+}
+
+const STARTED_AT = Date.parse('2026-08-03T09:00:00Z')
+const CWD = '/Users/demo/work/project'
+
+describe('session repair', () => {
+ it('finds the session the running engine started in this directory', async () => {
+ const root = tempRoot()
+ writeTranscript(root, 'proj', 'sess-live', CWD, STARTED_AT + 5_000)
+ const { findLiveSession } = await load(root)
+
+ await expect(findLiveSession('claude', CWD, STARTED_AT))
+ .resolves.toMatchObject({ sessionId: 'sess-live' })
+ })
+
+ it('finds the cwd even when the transcript opens with bookkeeping lines', async () => {
+ // Claude's first records are `leafUuid` / `mode` with no cwd anywhere in them. A first-line-only read
+ // therefore matched NO claude session on a real machine — the repair returned null for a pane whose
+ // transcript was sitting right there.
+ const root = tempRoot()
+ const dir = join(root, 'proj')
+ mkdirSync(dir, { recursive: true })
+ const file = join(dir, 'sess-meta-first.jsonl')
+ writeFileSync(file, [
+ JSON.stringify({ type: 'summary', leafUuid: 'x', sessionId: 'sess-meta-first' }),
+ JSON.stringify({ type: 'x-mode', mode: 'default', sessionId: 'sess-meta-first' }),
+ JSON.stringify({ type: 'user', cwd: CWD, sessionId: 'sess-meta-first' }),
+ '',
+ ].join('\n'))
+ utimesSync(file, new Date(STARTED_AT + 5_000), new Date(STARTED_AT + 5_000))
+ const { findLiveSession } = await load(root)
+
+ await expect(findLiveSession('claude', CWD, STARTED_AT))
+ .resolves.toMatchObject({ sessionId: 'sess-meta-first' })
+ })
+
+ it('ignores a session that predates the process now running the pane', async () => {
+ // A transcript older than the engine cannot be what it is running — that would be a resume, and
+ // resumes name their id on the command line (discoverTmuxResumes handles those).
+ const root = tempRoot()
+ writeTranscript(root, 'proj', 'sess-yesterday', CWD, STARTED_AT - 24 * 3_600_000)
+ const { findLiveSession } = await load(root)
+
+ await expect(findLiveSession('claude', CWD, STARTED_AT)).resolves.toBeNull()
+ })
+
+ it('ignores a session belonging to a different directory', async () => {
+ const root = tempRoot()
+ writeTranscript(root, 'other', 'sess-elsewhere', '/Users/demo/other', STARTED_AT + 5_000)
+ const { findLiveSession } = await load(root)
+
+ await expect(findLiveSession('claude', CWD, STARTED_AT)).resolves.toBeNull()
+ })
+
+ it('does not hand a just-exited session to the engine that replaced it', async () => {
+ // Real sequence: `/exit`, then relaunch in the same pane seconds later. The dead transcript's last
+ // write is still fresh, so a mtime-only rule with a generous slack bound the NEW agent to the OLD
+ // session id (measured on a live pane). Its file was created before this process and has not been
+ // written to since it started — neither tier may accept it.
+ const root = tempRoot()
+ const dir = join(root, 'proj')
+ mkdirSync(dir, { recursive: true })
+ const file = join(dir, 'sess-just-exited.jsonl')
+ writeFileSync(file, `${JSON.stringify({ type: 'user', cwd: CWD })}\n`)
+ const born = Date.now() // the temp file's real birthtime
+ const lastWrite = born + 20_000 // it wrote, then the user exited…
+ utimesSync(file, new Date(lastWrite), new Date(lastWrite))
+ const { findLiveSession } = await load(root)
+
+ // …and the replacement process started AFTER that last write.
+ await expect(findLiveSession('claude', CWD, born + 40_000)).resolves.toBeNull()
+ })
+
+ it('still finds a RESUMED session, whose file is old but freshly written', async () => {
+ // The other side of the same coin: `claude --resume` writes to a transcript created earlier. A write
+ // that lands after the process started is what marks it as the one being run right now.
+ const root = tempRoot()
+ const dir = join(root, 'proj')
+ mkdirSync(dir, { recursive: true })
+ const file = join(dir, 'sess-resumed.jsonl')
+ writeFileSync(file, `${JSON.stringify({ type: 'user', cwd: CWD })}\n`)
+ const born = Date.now()
+ const startedAt = born + 30_000 // the engine started well after the file was created…
+ utimesSync(file, new Date(startedAt + 10_000), new Date(startedAt + 10_000)) // …and wrote after that
+ const { findLiveSession } = await load(root)
+
+ await expect(findLiveSession('claude', CWD, startedAt))
+ .resolves.toMatchObject({ sessionId: 'sess-resumed' })
+ })
+
+ it('refuses to choose when two agents are running in the same directory', async () => {
+ // The whole point: a wrong guess wires one agent's tile to the other's transcript, and nothing
+ // downstream could tell. Staying invisible for one more turn is the cheaper failure.
+ const root = tempRoot()
+ writeTranscript(root, 'proj', 'sess-a', CWD, STARTED_AT + 5_000)
+ writeTranscript(root, 'proj', 'sess-b', CWD, STARTED_AT + 9_000)
+ const { findLiveSession } = await load(root)
+
+ await expect(findLiveSession('claude', CWD, STARTED_AT)).resolves.toBeNull()
+ })
+
+ it('picks the transcript path along with the id, so the session can actually be tailed', async () => {
+ const root = tempRoot()
+ writeTranscript(root, 'proj', 'sess-live', CWD, STARTED_AT + 1_000)
+ const { findLiveSession } = await load(root)
+
+ const found = await findLiveSession('claude', CWD, STARTED_AT)
+ expect(found?.transcriptPath).toBe(join(root, 'proj', 'sess-live.jsonl'))
+ })
+
+ it('skips sidecar files that are not transcripts', async () => {
+ // Command Code writes `<id>.checkpoints.jsonl` next to the real transcript; adopting one would
+ // register a session id that no reader can follow.
+ const root = tempRoot()
+ const dir = join(root, 'proj')
+ mkdirSync(dir, { recursive: true })
+ const sidecar = join(dir, 'sess-live.checkpoints.jsonl')
+ writeFileSync(sidecar, `${JSON.stringify({ cwd: CWD })}\n`)
+ utimesSync(sidecar, new Date(STARTED_AT + 5_000), new Date(STARTED_AT + 5_000))
+ const { findLiveSession } = await load(root)
+
+ await expect(findLiveSession('claude', CWD, STARTED_AT)).resolves.toBeNull()
+ })
+
+ it('says nothing rather than throwing when the engine store is missing', async () => {
+ const { findLiveSession } = await load(join(tempRoot(), 'does-not-exist'))
+ await expect(findLiveSession('claude', CWD, STARTED_AT)).resolves.toBeNull()
+ })
+
+ it('has no answer for cursor, and says so instead of guessing', async () => {
+ // Cursor transcripts are located by id, not listed by directory; its resumes have their own path.
+ const { findLiveSession } = await load(tempRoot())
+ await expect(findLiveSession('cursor', CWD, STARTED_AT)).resolves.toBeNull()
+ })
+})
diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.ts
new file mode 100644
index 000000000..c202dd93b
--- /dev/null
+++ b/cli/src/lib/sessionRepair.ts
@@ -0,0 +1,249 @@
+/**
+ * Find the session a live launcher is running, when the daemon has lost track of it.
+ *
+ * The rule the design rests on is that an agent exists as long as its launcher's socket is open. The
+ * launcher upholds its half — it reconnects forever, with the same machine id. But the frame it sends
+ * carries no SESSION id, because the launcher genuinely does not know one: the engine picks it, and the
+ * only path that ever told the daemon was the engine's own hook, which fires once and never again. So a
+ * daemon that lost the mapping (a cleared registry, a crash, a `harness reset`) kept a connected launcher
+ * with no agent behind it — invisible until the user happened to type. Observed on 2026-08-03: three
+ * launchers reconnected with their original ids and none of the three came back.
+ *
+ * This is the missing half. Ask the ENGINE's own store which session belongs to that pane's directory,
+ * started after the engine did.
+ *
+ * Two rules keep it honest:
+ * - **Started after the engine process did.** A session older than the process cannot be the one it is
+ * running now. (Resumed agents name their id on the command line and are adopted from argv instead —
+ * see discoverTmuxResumes.)
+ * - **Unique or nothing.** Two candidate sessions in one directory means two agents there, and guessing
+ * would hand one agent's transcript to the other's tile. Ambiguity returns null; the agent stays
+ * invisible until its next turn, which is recoverable — mis-binding is not.
+ */
+
+import { execFile } from 'child_process'
+import { readdir, readFile, realpath, stat } from 'fs/promises'
+import { join } from 'path'
+import { promisify } from 'util'
+import { env } from '../config/env.js'
+import type { AgentEngine } from '../engines/types.js'
+import { readCodexRolloutMeta } from '../engines/codex/rollout.js'
+
+const execFileAsync = promisify(execFile)
+
+/**
+ * Clock granularity only. `ps` reports start time to the second, so a file created in the same second
+ * must still count as "after".
+ *
+ * Deliberately small. It was 60s, and that let a session the user had JUST exited be handed to the engine
+ * they started seconds later in the same pane: the old transcript's last write fell inside the window, so
+ * the new agent came up wearing the dead session's id (measured — `/exit`, relaunch, and repair re-bound
+ * `6899ff76`). Whatever is picked here must belong to the process running NOW.
+ */
+const START_SLACK_MS = 5_000
+/** Directories to walk per engine root. Deep enough for codex's <year>/<month>/<day> layout. */
+const MAX_DEPTH = 4
+const MAX_FILES = 400
+
+export interface RepairedSession {
+ sessionId: string
+ /** File-backed engines only; the DB-backed ones are read by session id. */
+ transcriptPath?: string
+}
+
+interface TranscriptFile { path: string; mtimeMs: number; birthMs: number }
+
+/** Every `.jsonl` under `root`, newest first, capped. Checkpoint/sidecar files are not transcripts. */
+async function transcripts(root: string, depth = 0): Promise<TranscriptFile[]> {
+ if (depth > MAX_DEPTH) return []
+ let entries
+ try { entries = await readdir(root, { withFileTypes: true }) } catch { return [] }
+ const out: TranscriptFile[] = []
+ for (const entry of entries) {
+ const full = join(root, entry.name)
+ if (entry.isDirectory()) { out.push(...await transcripts(full, depth + 1)); continue }
+ if (!entry.name.endsWith('.jsonl') || entry.name.includes('.checkpoints.')) continue
+ try {
+ const info = await stat(full)
+ out.push({ path: full, mtimeMs: info.mtimeMs, birthMs: info.birthtimeMs || info.mtimeMs })
+ } catch { /* vanished mid-scan */ }
+ }
+ return out.sort((a, b) => b.mtimeMs - a.mtimeMs).slice(0, MAX_FILES)
+}
+
+/**
+ * The `cwd` a transcript declares, from its opening lines.
+ *
+ * Not just line one: claude opens with bookkeeping records (`leafUuid`, `mode`) that carry no cwd, so a
+ * first-line-only read found nothing for every claude session on the computer — caught when a live repair
+ * returned null for a pane whose transcript was sitting right there. pi and Command Code do put it on
+ * line one; scanning a few lines covers all three without knowing which is which.
+ */
+const CWD_SCAN_LINES = 20
+
+async function readTranscriptMeta(path: string): Promise<TranscriptMeta | null> {
+ try {
+ const head = (await readFile(path, 'utf-8')).slice(0, 256 * 1024)
+ for (const line of head.split('\n', CWD_SCAN_LINES)) {
+ if (!line.trim()) continue
+ let obj: Record<string, unknown>
+ try { obj = JSON.parse(line) as Record<string, unknown> } catch { continue }
+ if (typeof obj.cwd === 'string' && obj.cwd) return { cwd: obj.cwd }
+ }
+ return null
+ } catch { return null }
+}
+
+/** Session id from `<id>.jsonl`, or from pi's `<timestamp>_<id>.jsonl`. */
+function idFromFile(path: string): string {
+ const base = path.split('/').pop()?.replace(/\.jsonl$/, '') ?? ''
+ const underscore = base.lastIndexOf('_')
+ return underscore === -1 ? base : base.slice(underscore + 1)
+}
+
+/**
+ * Compare two directories as the filesystem sees them, not as strings.
+ *
+ * On macOS `/tmp` is a symlink to `/private/tmp`, so a launcher reporting one and an engine recording the
+ * other describe the SAME directory and would never match textually — measured: a repair that resolved
+ * correctly for `/private/tmp/synctest` returned null for `/tmp/synctest`.
+ */
+async function sameDir(a: string, b: string): Promise<boolean> {
+ if (a === b) return true
+ const [ra, rb] = await Promise.all([
+ realpath(a).catch(() => a),
+ realpath(b).catch(() => b),
+ ])
+ return ra === rb
+}
+
+/**
+ * Two tiers, because two different things look alike from here.
+ *
+ * born — the transcript was CREATED after the process started: a session this engine opened itself.
+ * wrote — created earlier but written to after the process started: a session it RESUMED.
+ *
+ * Preferring `born` is what stops a just-exited session from being handed to its replacement: the dead
+ * transcript was created before the new process, and its final write lands before the new process starts,
+ * so it qualifies for neither tier and the pane stays unbound until the real session appears.
+ */
+interface TranscriptMeta { cwd: string | null; sessionId?: string }
+
+async function fileEngineSession(
+ root: string,
+ cwd: string,
+ startedAtMs: number,
+ readMeta: (path: string) => Promise<TranscriptMeta | null>,
+ opts?: { bornOnly?: boolean },
+): Promise<RepairedSession | null> {
+ const since = startedAtMs - START_SLACK_MS
+ const born: RepairedSession[] = []
+ const wrote: RepairedSession[] = []
+ for (const file of await transcripts(root)) {
+ if (file.mtimeMs < since) break // sorted newest-first: everything after is older still
+ const meta = await readMeta(file.path)
+ if (!meta?.cwd || !await sameDir(meta.cwd, cwd)) continue
+ const found = { sessionId: meta.sessionId || idFromFile(file.path), transcriptPath: file.path }
+ ;(file.birthMs >= since ? born : wrote).push(found)
+ }
+ // "Unique or nothing" at each tier: two candidates means two agents in one directory, and a wrong guess
+ // wires one agent's tile to the other's transcript.
+ if (born.length === 1) return born[0]
+ if (born.length > 1) return null
+ // `bornOnly`: the caller is binding an agent that has NEVER had a session. Accepting the `wrote` tier
+ // there hands it whatever session was last touched in this directory — measured: exit the launcher,
+ // run `harness claude` again in the same pane, and the new agent adopted the PREVIOUS conversation,
+ // so the web opened a fresh tab already full of old messages. A resume the user asked for by name is
+ // matched from argv by the discovery path instead, which needs no guessing.
+ if (opts?.bornOnly) return null
+ return wrote.length === 1 ? wrote[0] : null
+}
+
+async function dbEngineSession(dbPath: string, sql: string): Promise<RepairedSession | null> {
+ let stdout: string
+ try {
+ // Same invocation the readers use: `.timeout` as a dot-command (the PRAGMA form prints a row under
+ // -json and corrupts the parse), and query_only so a repair can never write to the user's store.
+ ({ stdout } = await execFileAsync(
+ 'sqlite3',
+ ['-json', '-cmd', '.timeout 3000', '-cmd', 'PRAGMA query_only=1', dbPath, sql],
+ { maxBuffer: 1024 * 1024 },
+ ))
+ } catch { return null }
+ const trimmed = stdout.trim()
+ if (!trimmed) return null
+ let rows: Array<Record<string, unknown>>
+ try { rows = JSON.parse(trimmed) as Array<Record<string, unknown>> } catch { return null }
+ if (rows.length !== 1) return null // 0 = nothing to adopt, >1 = ambiguous
+ const id = rows[0].id
+ return typeof id === 'string' && id ? { sessionId: id } : null
+}
+
+/** SQL-escape a directory for a literal comparison (the readers build literals the same way). */
+function quote(value: string): string {
+ return `'${value.replace(/'/g, "''")}'`
+}
+
+/**
+ * The session a launcher's engine is running in `cwd`, or null when it cannot be said for certain.
+ *
+ * `startedAtMs` is when the engine process started (`ps` lstart). Cursor is absent on purpose: its
+ * transcripts are located by id rather than listed by directory, and its resumes already have a
+ * dedicated discovery path.
+ */
+export async function findLiveSession(
+ engine: AgentEngine,
+ cwd: string,
+ startedAtMs: number,
+ opts?: { bornOnly?: boolean },
+): Promise<RepairedSession | null> {
+ const sinceMs = startedAtMs - START_SLACK_MS
+ // The DB engines match on a directory STRING, so ask for both spellings of it (see sameDir).
+ const real = await realpath(cwd).catch(() => cwd)
+ const dirs = real === cwd ? [cwd] : [cwd, real]
+ const dirList = dirs.map(quote).join(', ')
+ switch (engine) {
+ case 'claude':
+ return fileEngineSession(env.CLAUDE_PROJECTS_DIR, cwd, startedAtMs, readTranscriptMeta, opts)
+ case 'codex':
+ // Codex writes no `cwd` on line one; its rollout meta carries it — and says whether the rollout
+ // belongs to a subagent, which must never become an agent of its own.
+ // Its session id lives INSIDE the file: the name is `rollout-<timestamp>-<id>.jsonl`, so deriving
+ // the id from the filename produced the literal string "rollout-…" (seen on a live pane).
+ return fileEngineSession(join(env.CODEX_HOME, 'sessions'), cwd, startedAtMs, async (path) => {
+ const meta = readCodexRolloutMeta(path)
+ return meta && !meta.isSubagent ? { cwd: meta.cwd, sessionId: meta.id || undefined } : null
+ }, opts)
+ case 'pi':
+ return fileEngineSession(join(env.PI_HOME, 'agent', 'sessions'), cwd, startedAtMs, readTranscriptMeta, opts)
+ case 'commandcode':
+ return fileEngineSession(join(env.COMMANDCODE_HOME, 'projects'), cwd, startedAtMs, readTranscriptMeta, opts)
+ case 'opencode':
+ // time_created is epoch MILLISECONDS here.
+ return dbEngineSession(
+ join(env.OPENCODE_DATA_DIR, 'opencode.db'),
+ `SELECT id FROM session WHERE directory IN (${dirList}) AND parent_id IS NULL`
+ + ` AND (time_created >= ${Math.trunc(sinceMs)} OR time_updated >= ${Math.trunc(sinceMs)})`
+ + ` ORDER BY time_updated DESC LIMIT 2;`,
+ )
+ case 'hermes':
+ // started_at is epoch SECONDS (fractional).
+ return dbEngineSession(
+ join(env.HERMES_HOME, 'state.db'),
+ `SELECT id FROM sessions WHERE cwd IN (${dirList}) AND started_at >= ${Math.trunc(sinceMs / 1000)}`
+ + ` ORDER BY started_at DESC LIMIT 2;`,
+ )
+ case 'devin':
+ // created_at is epoch SECONDS (integer).
+ return dbEngineSession(
+ join(env.DEVIN_HOME, 'sessions.db'),
+ // created_at is when the session began; last_activity_at moves when devin resumes into it, which
+ // is the only marker a continued session leaves behind.
+ `SELECT id FROM sessions WHERE working_directory IN (${dirList})`
+ + ` AND (created_at >= ${Math.trunc(sinceMs / 1000)} OR last_activity_at >= ${Math.trunc(sinceMs / 1000)})`
+ + ` ORDER BY last_activity_at DESC LIMIT 2;`,
+ )
+ default:
+ return null
+ }
+}
diff --git a/cli/src/lib/sessions.ts b/cli/src/lib/sessions.ts
new file mode 100644
index 000000000..5a6e26a34
--- /dev/null
+++ b/cli/src/lib/sessions.ts
@@ -0,0 +1,149 @@
+/**
+ * Session discovery + raw tail reads over the Claude projects directory.
+ *
+ * Phase 1 is deliberately raw: we do not parse transcripts into rich events. We
+ * only enumerate session files and read their raw lines.
+ */
+
+import { readdir, readFile, stat, open } from 'fs/promises'
+import { join } from 'path'
+import { env } from '../config/env.js'
+import { isSessionFile, isCodexPath, sessionIdFromFile } from './paths.js'
+
+export interface SessionMeta {
+ sessionId: string
+ /** Absolute path to the session's .jsonl file. */
+ filePath: string
+ /** The mangled project dir name (parent folder). */
+ projectDir: string
+ /** Real working directory, read from the JSONL `cwd` field (best effort). */
+ cwd: string | null
+ gitBranch: string | null
+ /** File mtime in epoch ms — used to order newest → oldest. */
+ updatedAt: number
+ sizeBytes: number
+}
+
+const ROOT = env.CLAUDE_PROJECTS_DIR
+
+/** Pull `cwd` / `gitBranch` from the first line of a session file (best effort). */
+async function readFirstLineMeta(
+ filePath: string
+): Promise<{ cwd: string | null; gitBranch: string | null }> {
+ try {
+ // Read a small prefix; the first JSON line is well under 64 KiB.
+ const fh = await open(filePath, 'r')
+ try {
+ const buf = Buffer.alloc(64 * 1024)
+ const { bytesRead } = await fh.read(buf, 0, buf.length, 0)
+ const chunk = buf.subarray(0, bytesRead).toString('utf-8')
+ const nl = chunk.indexOf('\n')
+ const firstLine = nl === -1 ? chunk : chunk.slice(0, nl)
+ const obj = JSON.parse(firstLine) as Record<string, unknown>
+ return {
+ cwd: typeof obj.cwd === 'string' ? obj.cwd : null,
+ gitBranch: typeof obj.gitBranch === 'string' ? obj.gitBranch : null,
+ }
+ } finally {
+ await fh.close()
+ }
+ } catch {
+ return { cwd: null, gitBranch: null }
+ }
+}
+
+/** List every Claude session across all project dirs, newest → oldest. */
+export async function listSessions(): Promise<SessionMeta[]> {
+ let projectDirs: string[]
+ try {
+ const entries = await readdir(ROOT, { withFileTypes: true })
+ projectDirs = entries.filter((e) => e.isDirectory()).map((e) => e.name)
+ } catch {
+ return []
+ }
+
+ const sessions: SessionMeta[] = []
+
+ for (const dir of projectDirs) {
+ const dirPath = join(ROOT, dir)
+ let files: string[]
+ try {
+ files = await readdir(dirPath)
+ } catch {
+ continue
+ }
+
+ for (const name of files) {
+ const filePath = join(dirPath, name)
+ if (!isSessionFile(filePath) || isCodexPath(filePath)) continue
+
+ let st
+ try {
+ st = await stat(filePath)
+ } catch {
+ continue
+ }
+ if (!st.isFile() || st.size === 0) continue
+
+ const { cwd, gitBranch } = await readFirstLineMeta(filePath)
+ sessions.push({
+ sessionId: sessionIdFromFile(filePath),
+ filePath,
+ projectDir: dir,
+ cwd,
+ gitBranch,
+ updatedAt: st.mtimeMs,
+ sizeBytes: st.size,
+ })
+ }
+ }
+
+ sessions.sort((a, b) => b.updatedAt - a.updatedAt)
+ return sessions
+}
+
+/** Resolve a sessionId to its absolute .jsonl path (searches all project dirs). */
+export async function resolveSessionFile(sessionId: string): Promise<string | null> {
+ // Hardening: this value can originate from a remote web/device request. A bare session id only ever
+ // contains [A-Za-z0-9._-]; reject anything with a path separator or `..` so it can never build a
+ // path outside a project dir (e.g. `../../../../etc/x` → reading arbitrary *.jsonl on the computer).
+ if (!/^[A-Za-z0-9._-]+$/.test(sessionId) || sessionId.includes('..')) return null
+ let projectDirs: string[]
+ try {
+ const entries = await readdir(ROOT, { withFileTypes: true })
+ projectDirs = entries.filter((e) => e.isDirectory()).map((e) => e.name)
+ } catch {
+ return null
+ }
+ for (const dir of projectDirs) {
+ const candidate = join(ROOT, dir, `${sessionId}.jsonl`)
+ try {
+ const st = await stat(candidate)
+ if (st.isFile()) return candidate
+ } catch {
+ // not here
+ }
+ }
+ return null
+}
+
+/** Return the last `n` non-empty raw lines of a specific transcript file. Prefer this over
+ * `tailLines` when the caller already holds a trusted, registered `transcriptPath` — it takes no
+ * request-controlled id, so there is no path to traverse. */
+export async function tailFile(filePath: string, n = 200): Promise<string[]> {
+ try {
+ const content = await readFile(filePath, 'utf-8')
+ const lines = content.split('\n').filter((l) => l.trim().length > 0)
+ return lines.slice(-n)
+ } catch {
+ return []
+ }
+}
+
+/** Return the last `n` raw lines of a session file, resolved from a sessionId (guarded — see
+ * `resolveSessionFile`). Only reads files under CLAUDE_PROJECTS_DIR. */
+export async function tailLines(sessionId: string, n = 200): Promise<string[]> {
+ const filePath = await resolveSessionFile(sessionId)
+ if (!filePath) return []
+ return tailFile(filePath, n)
+}
diff --git a/cli/src/lib/subagentTurn.spec.ts b/cli/src/lib/subagentTurn.spec.ts
new file mode 100644
index 000000000..5d8b2a282
--- /dev/null
+++ b/cli/src/lib/subagentTurn.spec.ts
@@ -0,0 +1,173 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, readFileSync, rmSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import { fileURLToPath } from 'url'
+import { CommanderMirror, type CommanderFrame } from './commander.js'
+import { lineToEvents, newTurnState, type LiveEvent } from './normalize.js'
+
+/**
+ * One REAL claude turn that spawned three ASYNC sub-agents ("Chạy 3 sub-agent SONG SONG…"), replayed
+ * through the same two stages the daemon uses: `lineToEvents` → `CommanderMirror.ingest`.
+ *
+ * What made this worth a fixture: claude answers the `Agent` tool_use in ~4ms with "Async agent launched
+ * successfully." and then ENDS the turn — the three sub-agents are still working. Taking either of those
+ * at face value showed the user a finished tile and a recap of the launch message ("đã spawn 3 sub-agent"),
+ * while the answer they actually asked for landed minutes later with nothing left on screen to show it.
+ */
+function transcript(): string[] {
+ const p = fileURLToPath(new URL('./__fixtures__/transcript-async-subagents.jsonl', import.meta.url))
+ return readFileSync(p, 'utf-8').split('\n').filter((l) => l.trim())
+}
+
+function events(): LiveEvent[] {
+ const state = newTurnState()
+ return transcript().flatMap((line) => lineToEvents(line, state))
+}
+
+let dataDir = ''
+
+describe('async sub-agents (real claude transcript)', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ dataDir = mkdtempSync(join(tmpdir(), 'adapter-subagent-'))
+ })
+ afterEach(() => {
+ vi.useRealTimers()
+ rmSync(dataDir, { recursive: true, force: true })
+ })
+
+ it('turns each task-notification into one subagent_finished keyed by its tool-use id', () => {
+ const finished = events().filter((e) => e.type === 'subagent_finished')
+ expect(finished).toHaveLength(3)
+ const spawned = events().filter((e) => e.type === 'tool_start' && e.payload.tool === 'Agent')
+ expect(spawned).toHaveLength(3)
+ // Ids must PAIR with the spawning tool_use — that is what lets the list tick off the right row.
+ expect(new Set(finished.map((e) => (e as { payload: { id: string } }).payload.id)))
+ .toEqual(new Set(spawned.map((e) => (e as { payload: { id: string } }).payload.id)))
+ for (const e of finished) expect((e as { payload: { status: string } }).payload.status).toBe('completed')
+ })
+
+ it('a task-notification is not a prompt: exactly one turn, and it is the user\'s', () => {
+ const starts = events().filter((e) => e.type === 'turn_started')
+ expect(starts).toHaveLength(1)
+ expect((starts[0] as { payload: { userMessage: string } }).payload.userMessage).toContain('SONG SONG')
+ })
+
+ function replay(): { frames: CommanderFrame[]; summarize: ReturnType<typeof vi.fn> } {
+ const frames: CommanderFrame[] = []
+ const summarize = vi.fn(async (text: string) => `recap\n\n${text.slice(0, 40)}`)
+ const mirror = new CommanderMirror({
+ send: (f) => frames.push(f),
+ sendWeb: () => {},
+ hasDevice: () => true,
+ summarize,
+ dataDir,
+ })
+ const state = newTurnState()
+ for (const line of transcript()) mirror.ingest(lineToEvents(line, state), 'sess-async')
+ return { frames, summarize }
+ }
+
+ const agentFrames = (frames: CommanderFrame[]) =>
+ frames.filter((f) => (f.payload as { kind?: string }).kind === 'agents')
+ .map((f) => (f.payload as { agents: Array<{ text: string }> }).agents.map((a) => a.text))
+
+ it('never ticks a sub-agent off on its launch ack', () => {
+ const { frames } = replay()
+ // Three spawns + three finishes = six list pushes (this turn started with no list to clear).
+ const live = agentFrames(frames)
+ expect(live).toHaveLength(6)
+ // After the third spawn every row is still running: a `✓` there would be the launch-ack bug.
+ expect(live[2]).toHaveLength(3)
+ expect(live[2].every((t) => t.startsWith('›'))).toBe(true)
+ expect(live[5].every((t) => t.startsWith('✓'))).toBe(true)
+ })
+
+ it('holds the recap until the last sub-agent reports in, then recaps the FINISHED answer', async () => {
+ const { frames, summarize } = replay()
+ // The parent turn already ended in the transcript — nothing may have been summarized yet.
+ expect(summarize).not.toHaveBeenCalled()
+ expect(frames.some((f) => (f.payload as { kind?: string }).kind === 'summary')).toBe(false)
+
+ await vi.advanceTimersByTimeAsync(13_000) // backstop window after the last finish
+ expect(summarize).toHaveBeenCalledTimes(1)
+ const text = summarize.mock.calls[0][0] as string
+ expect(text).toContain('Cả 3 sub-agent đã hoàn thành') // the wrap-up, not the launch message
+ })
+
+ it('a cancel while sub-agents run drops the held recap instead of firing it later', async () => {
+ const frames: CommanderFrame[] = []
+ const summarize = vi.fn(async () => 'recap\n\nbody')
+ const mirror = new CommanderMirror({ send: (f) => frames.push(f), sendWeb: () => {}, hasDevice: () => true, summarize, dataDir })
+ const state = newTurnState()
+ for (const line of transcript()) {
+ const evs = lineToEvents(line, state)
+ // Cut the replay off at the turn-end that the sub-agents are holding open.
+ mirror.ingest(evs, 'sess-cancel')
+ if (evs.some((e) => e.type === 'turn_ended')) break
+ }
+ mirror.cancel('sess-cancel')
+ await vi.advanceTimersByTimeAsync(15 * 60_000)
+ expect(summarize).not.toHaveBeenCalled()
+ })
+
+ it('keeps a sub-agent announced just BEFORE its turn opened (cursor hook ordering)', () => {
+ // Measured live: cursor's tool-start hook reached the mirror at 10:20:36.799 and its transcript-derived
+ // turn_started at 10:20:36.862 — 63ms later. A blanket reset on turn_started deleted the first Task, so
+ // two parallel sub-agents showed as one row and the held turn-end released a sub-agent early.
+ const frames: CommanderFrame[] = []
+ const mirror = new CommanderMirror({ send: (f) => frames.push(f), sendWeb: () => {}, hasDevice: () => true, summarize: async () => null, dataDir })
+ mirror.ingest([
+ { type: 'tool_start', payload: { id: 'task-a', tool: 'Task', input: { description: 'SJC gold price today' } } },
+ { type: 'turn_started', payload: { userMessage: 'two sub-agents' } },
+ { type: 'tool_start', payload: { id: 'task-b', tool: 'Task', input: { description: 'USD/VND rate today' } } },
+ ] as LiveEvent[], 'sess-order')
+ const lists = agentFrames(frames)
+ expect(lists[lists.length - 1]).toHaveLength(2)
+ })
+
+ it('does not let LAST turn\'s sub-agent hold THIS turn\'s recap', async () => {
+ // The row survives the turn boundary so the device keeps showing it — but an agent spawned two
+ // prompts ago must not park the answer to the question just asked (worst case: the 10-minute
+ // backstop, with nothing on screen to explain the wait).
+ const frames: CommanderFrame[] = []
+ const summarize = vi.fn(async (_text: string) => 'recap\n\nbody')
+ const mirror = new CommanderMirror({ send: (f) => frames.push(f), sendWeb: () => {}, hasDevice: () => true, summarize, dataDir })
+ mirror.ingest([
+ { type: 'turn_started', payload: { userMessage: 'spawn one' } },
+ { type: 'tool_start', payload: { id: 'toolu_slow', tool: 'Agent', input: { description: 'still running' } } },
+ { type: 'tool_end', payload: { id: 'toolu_slow', tool: 'Agent', output: 'Async agent launched successfully.', isError: false, summary: '' } },
+ { type: 'turn_ended', payload: {} },
+ // …the user moves on to something unrelated while it runs.
+ { type: 'turn_started', payload: { userMessage: 'what time is it?' } },
+ { type: 'text_delta', payload: { content: 'It is 11:00.' } },
+ { type: 'turn_ended', payload: {} },
+ ] as LiveEvent[], 'sess-carry')
+
+ await vi.advanceTimersByTimeAsync(100)
+ expect(summarize).toHaveBeenCalledTimes(1)
+ expect(summarize.mock.calls[0][0]).toContain('It is 11:00.')
+ // and the carried row is still on the device's list, still marked running
+ const last = frames.filter((f) => (f.payload as { kind?: string }).kind === 'agents').at(-1)
+ expect((last?.payload as { agents: Array<{ text: string }> }).agents.map((a) => a.text)).toEqual(['› still running'])
+ })
+
+ it('releases the turn-end anyway if a sub-agent never reports back', async () => {
+ const frames: CommanderFrame[] = []
+ const summarize = vi.fn(async () => 'recap\n\nbody')
+ const mirror = new CommanderMirror({ send: (f) => frames.push(f), sendWeb: () => {}, hasDevice: () => true, summarize, dataDir })
+ mirror.ingest([
+ { type: 'turn_started', payload: { userMessage: 'spawn one' } },
+ { type: 'tool_start', payload: { id: 'toolu_x', tool: 'Agent', input: { description: 'never returns' } } },
+ { type: 'tool_end', payload: { id: 'toolu_x', tool: 'Agent', output: 'Async agent launched successfully.', isError: false, summary: '' } },
+ { type: 'text_delta', payload: { content: 'launched it' } },
+ { type: 'turn_ended', payload: {} },
+ ] as LiveEvent[], 'sess-stuck')
+
+ await vi.advanceTimersByTimeAsync(60_000)
+ expect(summarize).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(10 * 60_000)
+ expect(summarize).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/cli/src/lib/summarize.spec.ts b/cli/src/lib/summarize.spec.ts
new file mode 100644
index 000000000..e93492bba
--- /dev/null
+++ b/cli/src/lib/summarize.spec.ts
@@ -0,0 +1,169 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const mocks = vi.hoisted(() => ({
+ configure: vi.fn(),
+ runClaude: vi.fn(),
+ runCodex: vi.fn(),
+ runCursor: vi.fn(),
+ cleanupCursor: vi.fn(),
+ setCounts: vi.fn(),
+}))
+
+vi.mock('../config/env.js', () => ({
+ env: {
+ ADAPTER_DATA_DIR: '/tmp/machine-adapter-summarize-spec',
+ CURSOR_HOME: '/tmp/machine-adapter-summarize-spec/cursor',
+ SUMMARY_MODEL: 'sonnet',
+ CODEX_SUMMARY_MODEL: 'gpt-5.5',
+ CURSOR_SUMMARY_MODEL: 'auto',
+ SUMMARY_EFFORT: 'low',
+ },
+}))
+
+vi.mock('./oneshot.js', () => ({
+ cleanupCursorOneShotSession: mocks.cleanupCursor,
+ configureOneShotPool: mocks.configure,
+ runClaudeOneShot: mocks.runClaude,
+ runCodexOneShot: mocks.runCodex,
+ runCursorOneShot: mocks.runCursor,
+ setOneShotPoolActiveCounts: mocks.setCounts,
+ setOneShotPoolDeviceConnected: vi.fn(),
+ shutdownOneShotPool: vi.fn(),
+}))
+
+import { summarizeTurnText, syncSummaryPoolSessions } from './summarize.js'
+
+beforeEach(() => {
+ mocks.runClaude.mockReset()
+ mocks.runCodex.mockReset()
+ mocks.runCursor.mockReset()
+ mocks.cleanupCursor.mockReset()
+ mocks.cleanupCursor.mockResolvedValue(undefined)
+ mocks.setCounts.mockReset()
+})
+
+describe('Cursor recap', () => {
+ it('uses a Cursor one-shot with the configured Cursor model', async () => {
+ mocks.runCursor.mockResolvedValue({
+ text: 'Cursor recap works.\n\nThe Cursor turn now produces a persisted device recap.',
+ sessionId: 'cursor-recap-session',
+ })
+
+ await expect(summarizeTurnText(
+ 'Implemented Cursor recap support.',
+ undefined,
+ 'Does Cursor recap work?',
+ 'cursor',
+ )).resolves.toBe(
+ 'Cursor recap works.\n\nThe Cursor turn now produces a persisted device recap.',
+ )
+
+ expect(mocks.runCursor).toHaveBeenCalledOnce()
+ expect(mocks.runCursor.mock.calls[0][0]).toMatchObject({
+ model: 'auto',
+ effort: 'low',
+ })
+ expect(mocks.runClaude).not.toHaveBeenCalled()
+ expect(mocks.runCodex).not.toHaveBeenCalled()
+ expect(mocks.cleanupCursor).toHaveBeenCalledWith('cursor-recap-session')
+ })
+
+ it('includes Cursor, OpenCode and Pi sessions when sizing recap workers', () => {
+ syncSummaryPoolSessions([
+ { engine: 'claude' },
+ { engine: 'codex' },
+ { engine: 'cursor' },
+ { engine: 'cursor' },
+ { engine: 'opencode' },
+ { engine: 'pi' },
+ { engine: 'commandcode' },
+ { engine: 'hermes' }, // not poolable (prompt is argv) — must NOT be counted
+ { engine: 'devin' }, // likewise: piping a prompt to `devin -p` panics the CLI
+ ])
+
+ expect(mocks.setCounts).toHaveBeenCalledWith({ claude: 1, codex: 1, cursor: 2, opencode: 1, pi: 1, commandcode: 1 })
+ })
+})
+
+describe('language fidelity', () => {
+ const VI_SOURCE = 'Đội tuyển Việt Nam đã thắng trận chung kết với tỉ số hai một trước Thái Lan tối qua tại sân Mỹ Đình.'
+ const VI_ASK = 'Trận đấu tối qua kết quả thế nào?'
+
+ it('retries when the recap comes back in another language than the source', async () => {
+ // The old check only fired for "should be English, came back Vietnamese"; this is the reverse, which
+ // is what users actually hit — talking Vietnamese and getting an English recap.
+ mocks.runClaude
+ .mockResolvedValueOnce({ text: 'Vietnam won the final two one.\n\nVietnam beat Thailand two one last night.', sessionId: 's1' })
+ .mockResolvedValueOnce({ text: 'Việt Nam thắng chung kết 2-1.\n\nViệt Nam hạ Thái Lan 2-1 tối qua tại Mỹ Đình.', sessionId: 's2' })
+
+ const out = await summarizeTurnText(VI_SOURCE, undefined, VI_ASK, 'claude')
+
+ expect(mocks.runClaude).toHaveBeenCalledTimes(2)
+ expect(mocks.runClaude.mock.calls[1][0].prompt).toContain('RETRY')
+ expect(out).toContain('Việt Nam thắng chung kết')
+ })
+
+ it('does not retry when the recap keeps the source language', async () => {
+ mocks.runClaude.mockResolvedValue({
+ text: 'Việt Nam thắng chung kết 2-1.\n\nViệt Nam hạ Thái Lan 2-1 tối qua tại sân Mỹ Đình.',
+ sessionId: 's1',
+ })
+
+ await summarizeTurnText(VI_SOURCE, undefined, VI_ASK, 'claude')
+ expect(mocks.runClaude).toHaveBeenCalledOnce()
+ })
+
+ it('does not retry an English turn answered in English', async () => {
+ mocks.runClaude.mockResolvedValue({
+ text: 'Vietnam won the final two one.\n\nVietnam beat Thailand two one last night at My Dinh stadium.',
+ sessionId: 's1',
+ })
+
+ await summarizeTurnText(
+ 'Vietnam won the final against Thailand two one last night at the My Dinh stadium.',
+ undefined,
+ 'How did the match go last night?',
+ 'claude',
+ )
+ expect(mocks.runClaude).toHaveBeenCalledOnce()
+ })
+
+ it('tolerates a technical term in another script inside a matching recap', async () => {
+ // A quoted identifier or product name must not read as a language switch.
+ mocks.runClaude.mockResolvedValue({
+ text: 'Đã sửa lỗi ở hàm parseConfig.\n\nMình đã sửa hàm parseConfig trong module loader và thêm kiểm tra đầu vào.',
+ sessionId: 's1',
+ })
+
+ await summarizeTurnText(
+ 'Mình đã sửa hàm parseConfig trong module loader và thêm kiểm tra đầu vào cho tham số.',
+ undefined,
+ 'Sửa xong chưa?',
+ 'claude',
+ )
+ expect(mocks.runClaude).toHaveBeenCalledOnce()
+ })
+})
+
+describe('summary completeness', () => {
+ it('strips any ellipsis and ends the summary on a finished sentence', async () => {
+ const longBody = Array.from({ length: 60 }, (_, i) => `detail number ${i} here.`).join(' ')
+ mocks.runClaude.mockResolvedValue({
+ text: `Work is done.\n\n${longBody} and then it trails off…`,
+ sessionId: 's1',
+ })
+
+ const out = await summarizeTurnText('A long English message about the work.', undefined, 'Status?', 'claude')
+ const body = out!.split('\n\n')[1]
+
+ expect(body).not.toContain('…')
+ expect(body).not.toMatch(/\.\.\./)
+ expect(body).toMatch(/[.!?]$/)
+ })
+
+ it('keeps a summary that is already within budget untouched', async () => {
+ mocks.runClaude.mockResolvedValue({ text: 'All good.\n\nThe deploy finished and the service is healthy.', sessionId: 's1' })
+ const out = await summarizeTurnText('The deploy finished and the service is healthy.', undefined, 'Done?', 'claude')
+ expect(out!.split('\n\n')[1]).toBe('The deploy finished and the service is healthy.')
+ })
+})
diff --git a/cli/src/lib/summarize.ts b/cli/src/lib/summarize.ts
new file mode 100644
index 000000000..ce94398da
--- /dev/null
+++ b/cli/src/lib/summarize.ts
@@ -0,0 +1,333 @@
+/**
+ * Device turn-recap summarizer — self-contained port of the brain's `summarizeTurnText`
+ *. Summarizes one turn's assistant text into the
+ * device's `recap\n\nsummary` shape (recap ≤15 words, summary ≤100) via a disposable one-shot
+ * from the same CLI engine as the interactive session. Honors an AbortSignal so a newer turn can
+ * supersede a stale recap.
+ */
+
+import { existsSync, mkdirSync } from 'fs'
+import { unlink } from 'fs/promises'
+import { homedir } from 'os'
+import { join } from 'path'
+import { env } from '../config/env.js'
+import type { AgentEngine } from '../engines/types.js'
+import {
+ cleanupCursorOneShotSession,
+ configureOneShotPool,
+ runClaudeOneShot,
+ runCodexOneShot,
+ runCursorOneShot,
+ runOpencodeOneShot,
+ runPiOneShot,
+ runHermesOneShot,
+ runCommandCodeOneShot,
+ runDevinOneShot,
+ setOneShotPoolActiveCounts,
+ setOneShotPoolDeviceConnected,
+ shutdownOneShotPool,
+} from './oneshot.js'
+
+const SUMMARY_MAX_WORDS = 120
+const RECAP_MAX_WORDS = 15 // ~12-15 words; ONE complete sentence (20 overflowed the device tile).
+const MAX_INPUT_CHARS = 50_000
+const SUMMARY_SCRATCH = join(env.ADAPTER_DATA_DIR, 'summary-scratch')
+
+function ensureSummaryScratch(): string {
+ if (!existsSync(SUMMARY_SCRATCH)) mkdirSync(SUMMARY_SCRATCH, { recursive: true })
+ return SUMMARY_SCRATCH
+}
+
+configureOneShotPool({
+ cwd: ensureSummaryScratch(),
+ claudeModel: env.SUMMARY_MODEL,
+ codexModel: env.CODEX_SUMMARY_MODEL,
+ cursorModel: env.CURSOR_SUMMARY_MODEL,
+ opencodeModel: env.OPENCODE_SUMMARY_MODEL,
+ piModel: env.PI_SUMMARY_MODEL,
+ commandcodeModel: env.COMMANDCODE_SUMMARY_MODEL,
+ effort: env.SUMMARY_EFFORT,
+})
+
+export function syncSummaryPoolSessions(sessions: Array<{ engine: AgentEngine }>): void {
+ const counts = { claude: 0, codex: 0, cursor: 0, opencode: 0, pi: 0, commandcode: 0 }
+ for (const session of sessions) {
+ // Hermes and Devin take their recap prompt as argv, so they can't be pre-warmed — no pooled worker.
+ if (session.engine === 'hermes' || session.engine === 'devin') continue
+ counts[session.engine]++
+ }
+ setOneShotPoolActiveCounts(counts)
+}
+
+export function setSummaryPoolDeviceConnected(connected: boolean): void {
+ setOneShotPoolDeviceConnected(connected)
+}
+
+export function shutdownSummaryPool(): void {
+ shutdownOneShotPool()
+}
+
+/**
+ * A coarse WRITING-SYSTEM fingerprint — deliberately not a language identifier. Naming languages meant a
+ * hand-maintained word list per language and a drift check that only ever ran in one direction (it caught
+ * "should be English, came back Vietnamese" but never the reverse). Comparing which scripts a text uses,
+ * and how accented its Latin part is, catches "answered in a different language" for any pair of languages
+ * with nothing to maintain.
+ */
+interface ScriptProfile {
+ /** Share of letters per writing system, e.g. { Latin: 0.9, Han: 0.1 }. */
+ shares: Record<string, number>
+ /** Share of Latin letters carrying a diacritic — what separates Vietnamese/Polish/Turkish from English. */
+ accented: number
+ letters: number
+}
+
+const SCRIPTS: Array<[string, RegExp]> = [
+ ['Han', /\p{Script=Han}/u],
+ ['Hiragana', /\p{Script=Hiragana}/u],
+ ['Katakana', /\p{Script=Katakana}/u],
+ ['Hangul', /\p{Script=Hangul}/u],
+ ['Cyrillic', /\p{Script=Cyrillic}/u],
+ ['Arabic', /\p{Script=Arabic}/u],
+ ['Hebrew', /\p{Script=Hebrew}/u],
+ ['Thai', /\p{Script=Thai}/u],
+ ['Devanagari', /\p{Script=Devanagari}/u],
+ ['Greek', /\p{Script=Greek}/u],
+ ['Latin', /\p{Script=Latin}/u],
+]
+
+function scriptProfile(text: string): ScriptProfile {
+ const counts: Record<string, number> = {}
+ let letters = 0
+ let accented = 0
+ for (const ch of text || '') {
+ if (!/\p{L}/u.test(ch)) continue
+ const hit = SCRIPTS.find(([, re]) => re.test(ch))
+ if (!hit) continue
+ letters++
+ counts[hit[0]] = (counts[hit[0]] || 0) + 1
+ // NFD splits an accented letter into base + combining mark(s); a bare ASCII letter never does.
+ if (hit[0] === 'Latin' && /\p{M}/u.test(ch.normalize('NFD'))) accented++
+ }
+ const shares: Record<string, number> = {}
+ if (letters) for (const [k, v] of Object.entries(counts)) shares[k] = v / letters
+ const latin = counts.Latin || 0
+ return { shares, accented: latin ? accented / latin : 0, letters }
+}
+
+/**
+ * True when `out` reads as a DIFFERENT language than `src`: it dropped (or invented) a writing system the
+ * other side relies on, or its Latin text lost (or gained) diacritics wholesale. Thresholds are loose on
+ * purpose — quoting a product name or a code identifier in another script must not trip it.
+ */
+function languageDrifted(src: string, out: string): boolean {
+ const a = scriptProfile(src)
+ const b = scriptProfile(out)
+ if (a.letters < 12 || b.letters < 12) return false // too little signal to judge
+ for (const [name] of SCRIPTS) {
+ if (name === 'Latin') continue
+ const sa = a.shares[name] || 0
+ const sb = b.shares[name] || 0
+ if (sa >= 0.15 && sb <= 0.02) return true // the source is written in it, the output is not
+ if (sb >= 0.15 && sa <= 0.02) return true // the output switched into a script the source never used
+ }
+ const latinBoth = (a.shares.Latin || 0) >= 0.5 && (b.shares.Latin || 0) >= 0.5
+ if (latinBoth && a.accented >= 0.08 && b.accented <= 0.02) return true
+ if (latinBoth && b.accented >= 0.08 && a.accented <= 0.02) return true
+ return false
+}
+
+/**
+ * Cap the SUMMARY the way the recap is capped: never an ellipsis, always a finished sentence. Prefers to
+ * cut at the last sentence terminator inside the budget — which works for any language that ends a sentence
+ * with one — and only falls back to the clause/connector trim when there is none.
+ */
+function capComplete(text: string, max: number): string {
+ let t = (text || '').replace(/…|\.{2,}/g, ' ').replace(/\s+/g, ' ').trim()
+ const words = t.split(/\s+/)
+ if (words.length > max) {
+ const head = words.slice(0, max).join(' ')
+ const m = [...head.matchAll(/[.!?。!?]/gu)].pop()
+ t = m && m.index !== undefined && m.index > head.length * 0.4
+ ? head.slice(0, m.index + 1)
+ : head
+ }
+ if (!/[.!?。!?]$/u.test(t)) {
+ let prev: string
+ do { prev = t; t = t.replace(DANGLING_TAIL, '').replace(/[\s,;:–—-]+$/, '').trim() } while (t !== prev)
+ }
+ return t
+}
+
+// Trailing connectors (VN + EN) a recap must never END on — cutting here would leave it dangling
+// ("…2-1, nhờ"). Stripped from the tail if a hard cut lands on one. Prefix with a separator rather
+// than \b: JS \b is ASCII-only, so it fails on a Vietnamese word ending in a diacritic (e.g. "nhờ").
+const DANGLING_TAIL =
+ /[\s,;:–—-]+(nhờ|vì|do|bởi|để|và|hoặc|nhưng|mà|với|của|cho|khi|nếu|thì|theo|cùng|rằng|là|nên|and|or|but|with|because|since|so|to|for|of|in|on|at|the|a|an)[\s,;:–—-]*$/i
+
+/**
+ * Cap the RECAP to a clean newspaper-style headline: ONE line, ≤ max words, and NEVER any "…". The model is
+ * told to write a complete headline within budget; this is the hard guard. If it overshoots we cut at the
+ * last clause boundary and strip any dangling connector so it still ends on a complete point — but we do
+ * NOT append an ellipsis (a headline reads as finished, not truncated).
+ */
+function capRecap(text: string, max: number): string {
+ // Drop any ellipsis the model emitted (leading/trailing/mid) — headlines never carry "…".
+ let t = text.replace(/…|\.{2,}/g, ' ').replace(/\s+/g, ' ').trim()
+ const words = t.split(/\s+/)
+ if (words.length > max) {
+ let head = words.slice(0, max).join(' ')
+ const b = Math.max(head.lastIndexOf(','), head.lastIndexOf(';'), head.lastIndexOf('. '))
+ if (b > head.length * 0.5) head = head.slice(0, b)
+ t = head
+ }
+ // Strip a dangling connector / trailing punctuation so the headline ends on a complete point. No "…".
+ let prev: string
+ do { prev = t; t = t.replace(DANGLING_TAIL, '').replace(/[\s,;:–—-]+$/, '').trim() } while (t !== prev)
+ return t
+}
+
+// The CLI mangles a cwd into its projects-dir name (every non-alphanumeric → '-'); used to delete
+// the throwaway one-shot transcript so it never lingers under the watched projects root.
+function scratchTranscript(scratch: string, id: string): string {
+ const mangled = scratch.replace(/[^a-zA-Z0-9]/g, '-')
+ return join(homedir(), '.claude', 'projects', mangled, `${id}.jsonl`)
+}
+
+async function cleanupRecapSession(engine: AgentEngine, scratch: string, sessionId: string | null): Promise<void> {
+ if (!sessionId) return
+ if (engine === 'claude') {
+ await unlink(scratchTranscript(scratch, sessionId)).catch(() => {})
+ return
+ }
+ if (engine === 'cursor') await cleanupCursorOneShotSession(sessionId)
+}
+
+export async function summarizeTurnText(
+ text: string,
+ signal?: AbortSignal,
+ userMessage?: string,
+ engine: AgentEngine = 'claude',
+): Promise<string | null> {
+ let last = (text || '').trim()
+ if (!last) return null
+ if (last.length > MAX_INPUT_CHARS) last = last.slice(-MAX_INPUT_CHARS)
+
+ // If we know the user's request for this turn, tell the recap to LEAD with the direct answer to it
+ // (asked a price → give the price), not a generic characterization of the topic — the answer text
+ // still comes from the assistant's message. Whitespace-flattened + capped so a long paste can't
+ // dominate the prompt.
+ const ask = (userMessage || '').replace(/\s+/g, ' ').trim().slice(0, 400)
+ const askBlock = ask
+ ? `The user's request this turn was: «${ask}». Use this request as the turn's language signal ` +
+ `and context, but take all facts from the assistant message below. Your recap MUST lead with the DIRECT answer to that ` +
+ `exact request — the specific fact, number, decision or result they asked for (asked a price → the ` +
+ `price; asked yes/no → the verdict; asked "how" → the key step), taken from the assistant's message ` +
+ `below, then a few words of context. Do NOT lead with a generic characterization of the topic, and ` +
+ `do NOT invent anything not in the message.\n\n`
+ : ''
+
+ // Kept in sync with the hosted runtime’s recap. Guards two failure
+ // modes: (1) META-TASK LEAK — the summarizer writing its own intent ("I need to convert…") into the
+ // recap instead of re-voicing the content; (2) WRONG LANGUAGE — the recap drifting away from the
+ // source message's language.
+ const prompt =
+ `LANGUAGE RULE (most important): choose the output language ONLY from the user's request for this ` +
+ `turn and the assistant message between the --- markers below. If both are in English, output English. ` +
+ `If they use another language, output that language. If they mix languages, preserve that mix naturally. ` +
+ `Never switch to a language that does not appear in the user's request or the assistant message. Ignore ` +
+ `previous conversation, account locale, environment locale, and the language of these instructions.\n\n` +
+ askBlock +
+ `Between the --- markers below is a message the assistant already sent to the user. Re-voice its ` +
+ `CONTENT back to the user, in the FIRST PERSON as that same assistant (its own "I"). You are ONLY ` +
+ `restating what the message says — you are NOT performing any task and NOT describing this ` +
+ `summarizing job. NEVER write a meta or intent sentence such as "I need to…", "I will ` +
+ `summarize/convert/translate…", "let me…", or "the message is about…". Output ONLY these two parts ` +
+ `separated by a blank line, with no headings, labels or preamble:\n` +
+ `Part 1 (recap) — a NEWSPAPER HEADLINE for this turn: ONE punchy, self-contained line of at most ` +
+ `${RECAP_MAX_WORDS} words. State the SINGLE most important thing the user needs from this turn — the ` +
+ `direct answer, decision, result or recommendation to their request (what was said or done, NOT a plan ` +
+ `of what you will do next, NOT a description of the topic) — and FRONT-LOAD it so the first few words ` +
+ `alone carry the point (only the opening may be shown). Headline voice: active, specific, punchy; NO ` +
+ `hedging or throat-clearing (never open with "I think…", "This is a close one…", "It is about…", ` +
+ `"Regarding…") — conclusion first, then at most a few words of why; if the source hedges, still commit ` +
+ `to its leaning up front. It MUST be COMPLETE within ${RECAP_MAX_WORDS} words: never cut off mid-idea, ` +
+ `never end on a connector/preposition/unfinished clause, and NEVER use "…", "..." or any ellipsis or ` +
+ `trailing dots. If you would run long, TIGHTEN the wording into a shorter headline — do not truncate. ` +
+ `Do NOT enumerate long lists — give the gist (use counts like "4 forwards" instead of naming everyone). ` +
+ `PLAIN TEXT ONLY: no emoji, markdown, tables, bullets or URLs.\n` +
+ `Part 2 (after a blank line) — a fuller summary: present tense, condensed to the key ` +
+ `points, markedly shorter than the original; scale to the source (a short message → a ` +
+ `sentence or two, a long/detailed one → a short recap), never a full restatement, at most ` +
+ `${SUMMARY_MAX_WORDS} words. Here you MAY include the important specifics/lists that the ` +
+ `recap omitted. Like the recap it MUST read as finished: end on a COMPLETE sentence, never mid-idea or ` +
+ `on a dangling connector, and NEVER use "…", "..." or any ellipsis or trailing dots. If you would run ` +
+ `long, drop the least important detail — do not truncate.\n` +
+ `For both parts, restate the substance itself; do NOT narrate the process (avoid ` +
+ `"I wrote/did…").\n\n---\n${last}\n\n---\n` +
+ `IMPORTANT: before you answer, re-check the user's request and source message. Write BOTH parts — ` +
+ `INCLUDING the one-line recap — in their language and register. Do NOT translate or switch to any ` +
+ `language absent from those two inputs. Keep technical terms, code, and product names as-is.`
+
+ const scratch = ensureSummaryScratch()
+
+ const t0 = Date.now()
+ const model = engine === 'claude'
+ ? env.SUMMARY_MODEL
+ : engine === 'codex'
+ ? env.CODEX_SUMMARY_MODEL
+ : engine === 'cursor'
+ ? env.CURSOR_SUMMARY_MODEL
+ : engine === 'pi'
+ ? env.PI_SUMMARY_MODEL
+ : engine === 'hermes'
+ ? env.HERMES_SUMMARY_MODEL
+ : engine === 'commandcode'
+ ? env.COMMANDCODE_SUMMARY_MODEL
+ : engine === 'devin'
+ ? env.DEVIN_SUMMARY_MODEL
+ : env.OPENCODE_SUMMARY_MODEL
+ const effort = engine === 'cursor' ? 'model-defined' : env.SUMMARY_EFFORT
+ console.log(`[recap] one-shot ${engine} · model=${model} · effort=${effort} · inputChars=${last.length}${ask ? ' · withAsk' : ''}`)
+ const run = engine === 'claude'
+ ? runClaudeOneShot
+ : engine === 'codex'
+ ? runCodexOneShot
+ : engine === 'cursor'
+ ? runCursorOneShot
+ : engine === 'pi'
+ ? runPiOneShot
+ : engine === 'hermes'
+ ? runHermesOneShot
+ : engine === 'commandcode'
+ ? runCommandCodeOneShot
+ : engine === 'devin'
+ ? runDevinOneShot
+ : runOpencodeOneShot
+ let r = await run({ prompt, model, effort: env.SUMMARY_EFFORT, cwd: scratch, signal })
+ console.log(`[recap] one-shot returned in ${Date.now() - t0}ms · rawLen=${(r.text || '').length}`)
+ await cleanupRecapSession(engine, scratch, r.sessionId)
+ // Language check without naming a language: compare the writing system of the output against the inputs
+ // it was supposed to mirror. Works in both directions and for any language pair.
+ if (languageDrifted(`${ask} ${last}`, r.text || '')) {
+ console.warn('[recap] one-shot language drift detected · retrying')
+ r = await run({
+ prompt: prompt + `\n\nRETRY: your previous output was NOT in the same language as the user's request ` +
+ `and the assistant message. Rewrite it in exactly that language — same script and same diacritics — ` +
+ `preserving the required two-part format.`,
+ model,
+ effort: env.SUMMARY_EFFORT,
+ cwd: scratch,
+ signal,
+ })
+ await cleanupRecapSession(engine, scratch, r.sessionId)
+ }
+
+ // Cap the recap (complete-reading) and body independently.
+ const trimmed = (r.text || '').trim()
+ const nl = trimmed.indexOf('\n\n')
+ const recap = capRecap((nl >= 0 ? trimmed.slice(0, nl) : trimmed).trim(), RECAP_MAX_WORDS)
+ const body = capComplete((nl >= 0 ? trimmed.slice(nl + 2) : '').trim(), SUMMARY_MAX_WORDS)
+ if (!recap) { console.warn('[recap] one-shot produced no usable recap (empty after cap)'); return null }
+ return body ? `${recap}\n\n${body}` : recap
+}
diff --git a/cli/src/lib/tmux.spec.ts b/cli/src/lib/tmux.spec.ts
new file mode 100644
index 000000000..570e730be
--- /dev/null
+++ b/cli/src/lib/tmux.spec.ts
@@ -0,0 +1,392 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, rmSync, writeFileSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+
+let dataDir = ''
+let execErr: Error | null = null
+let execOut = ''
+let execResponder: ((cmd: string, args: string[]) => { err?: Error; stdout?: string }) | null = null
+
+vi.mock('child_process', () => ({
+ execFile: vi.fn((cmd: string, args: string[], _opts: unknown, cb: (err: Error | null, stdout: string) => void) => {
+ const response = execResponder?.(cmd, args)
+ cb(response?.err ?? execErr, response?.stdout ?? execOut)
+ }),
+}))
+
+async function loadModules() {
+ vi.resetModules()
+ process.env.ADAPTER_DATA_DIR = dataDir
+ process.env.CLAUDE_PROJECTS_DIR = dataDir
+ return {
+ ...(await import('./registry.js')),
+ ...(await import('./tmux.js')),
+ launcherSessions: (await import('./launcherSessions.js')).launcherSessions,
+ }
+}
+
+describe('tmux reaper', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ dataDir = mkdtempSync(join(tmpdir(), 'adapter-tmux-'))
+ execErr = null
+ execOut = ''
+ execResponder = null
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ rmSync(dataDir, { recursive: true, force: true })
+ delete process.env.ADAPTER_DATA_DIR
+ delete process.env.CLAUDE_PROJECTS_DIR
+ })
+
+ it('keeps registry entries when tmux pane listing fails', async () => {
+ const transcriptPath = join(dataDir, 'session-1.jsonl')
+ writeFileSync(transcriptPath, '{}\n')
+ const { registry, startTmuxReaper } = await loadModules()
+ registry.load()
+ registry.register({ launcherId: 'h1', sessionId: 'session-1', transcriptPath, tmuxPane: '%1', cwd: '/tmp/demo' })
+
+ execErr = new Error('tmux unavailable')
+ const removed: string[] = []
+ const timer = startTmuxReaper(1000, (id) => { removed.push(id); registry.remove(id) })
+ await vi.advanceTimersByTimeAsync(3000)
+ clearInterval(timer)
+
+ expect(removed).toEqual([])
+ expect(registry.has('session-1')).toBe(true)
+ })
+
+ it('reads cleaned tmux pane titles by pane id', async () => {
+ const { listPaneTitles } = await loadModules()
+ execOut = '%0\t✳ Clarify assistant identity\n%2\t autonomous-code \nnot-pane\tIgnored\n'
+
+ const titles = await listPaneTitles()
+
+ expect(Object.fromEntries(titles)).toEqual({
+ '%0': 'Clarify assistant identity',
+ '%2': 'autonomous-code',
+ })
+ })
+
+ it('removes a session after the pane is missing from valid tmux output twice', async () => {
+ const transcriptPath = join(dataDir, 'session-2.jsonl')
+ writeFileSync(transcriptPath, '{}\n')
+ const { registry, startTmuxReaper } = await loadModules()
+ registry.load()
+ registry.register({ launcherId: 'h1', sessionId: 'session-2', transcriptPath, tmuxPane: '%2', cwd: '/tmp/demo' })
+
+ execOut = '%9\n'
+ const removed: string[] = []
+ const timer = startTmuxReaper(1000, (id) => { removed.push(id); registry.remove(id) })
+ await vi.advanceTimersByTimeAsync(2500)
+ clearInterval(timer)
+
+ expect(removed).toEqual(['session-2'])
+ expect(registry.has('session-2')).toBe(false)
+ })
+
+ it('never evicts a session whose launcher is still connected', async () => {
+ // An agent exists exactly as long as its launcher's socket is open (launcherSessions.ts). That socket
+ // is a fact the daemon holds; `tmux` and `ps` are subprocesses that time out — and one already cost a
+ // live Command Code pane, which renames its own argv mid-life. The strong signal must win.
+ const transcriptPath = join(dataDir, 'session-3.jsonl')
+ writeFileSync(transcriptPath, '{}\n')
+ const { registry, startTmuxReaper, launcherSessions } = await loadModules()
+ registry.load()
+ registry.register({ launcherId: '11111111-2222-4333-8444-555555555555', sessionId: 'session-3', transcriptPath, tmuxPane: '%3', cwd: '/tmp/demo' })
+ launcherSessions.open(
+ { launcherId: '11111111-2222-4333-8444-555555555555', engine: 'claude', tmuxPane: '%3', cwd: '/tmp/demo' },
+ { close: () => {}, send: () => {} },
+ )
+
+ execOut = '%9\n' // tmux says the pane is gone — the weaker claim
+ const removed: string[] = []
+ const timer = startTmuxReaper(1000, (id) => { removed.push(id); registry.remove(id) })
+ await vi.advanceTimersByTimeAsync(5_000)
+ clearInterval(timer)
+
+ expect(removed).toEqual([])
+ expect(registry.has('session-3')).toBe(true)
+ launcherSessions.close('11111111-2222-4333-8444-555555555555')
+ })
+
+ it('prefers the stable Codex CLI over a matching app-server helper', async () => {
+ const { engineProcessMatchScore } = await loadModules()
+
+ const cliScore = engineProcessMatchScore(
+ { executable: '/usr/local/bin/codex', args: 'codex --yolo --profile minimax' },
+ 'codex',
+ )
+ const helperScore = engineProcessMatchScore(
+ {
+ executable: '/Applications/Co',
+ args: '/Applications/Codex.app/Contents/Resources/codex app-server --listen stdio://',
+ },
+ 'codex',
+ )
+
+ expect(cliScore).toBeGreaterThan(helperScore)
+ expect(helperScore).toBeGreaterThan(0)
+ })
+
+ it('matches Command Code by its ⌘ title after the TUI overwrites its own argv', async () => {
+ const { engineProcessMatchScore } = await loadModules()
+
+ // Real `ps` output: the entrypoint is gone within a second of launch, first replaced by the boot
+ // title and then by the session title. Missing these makes a live pane fail validateSessionRuntime.
+ const bootTitle = engineProcessMatchScore({ executable: '⌘', args: '⌘ Command Code · cc-fresh' }, 'commandcode')
+ const sessionTitle = engineProcessMatchScore({ executable: '⌘', args: '⌘ E2E OK' }, 'commandcode')
+ const entrypoint = engineProcessMatchScore(
+ { executable: '/usr/local/bin/node', args: 'node /usr/local/lib/node_modules/command-code/dist/index.mjs' },
+ 'commandcode',
+ )
+
+ expect(bootTitle).toBe(3)
+ expect(sessionTitle).toBe(3)
+ expect(entrypoint).toBe(3)
+ expect(engineProcessMatchScore({ executable: 'claude', args: 'claude' }, 'commandcode')).toBe(0)
+ })
+
+ it('parses a ps row whose comm contains spaces', async () => {
+ const { parseProcessRow } = await loadModules()
+
+ // Command Code's rewritten argv, exactly as `ps -axo pid=,ppid=,comm=,lstart=,args=` prints it.
+ expect(parseProcessRow('47692 70597 ⌘ Greeting Thu Jul 30 11:00:03 2026 ⌘ Greeting')).toEqual({
+ pid: 47692,
+ parentPid: 70597,
+ executable: '⌘ Greeting',
+ startMarker: 'Thu Jul 30 11:00:03 2026',
+ args: '⌘ Greeting',
+ })
+ // A single-token comm is unchanged — every other engine goes down this path.
+ expect(parseProcessRow('900 1 /usr/bin/node Thu Jul 30 09:15:00 2026 node cli.js --resume x')).toEqual({
+ pid: 900,
+ parentPid: 1,
+ executable: '/usr/bin/node',
+ startMarker: 'Thu Jul 30 09:15:00 2026',
+ args: 'node cli.js --resume x',
+ })
+ expect(parseProcessRow('not a process row')).toBeNull()
+ })
+
+ it('keeps a live Command Code pane when the TUI renames the session', async () => {
+ const { registry, startTmuxReaper } = await loadModules()
+ registry.load()
+ registry.register({ launcherId: 'h1', engine: 'commandcode', sessionId: 'cc-1', tmuxPane: '%3', cwd: '/tmp/demo' })
+
+ // Same process throughout — only the argv title changes, which is what Command Code does once it
+ // has named the session. Before the lstart-anchored parse this shifted `startMarker` and the reaper
+ // declared the pane "gone" ~10s later, while it was still serving turns.
+ let title = '⌘ Command Code · opencode-agent1'
+ execResponder = (cmd, args) => {
+ if (cmd === 'ps') return { stdout: `4242 1 ${title} Thu Jul 30 11:00:03 2026 ${title}\n` }
+ if (args[0] === 'display-message') return { stdout: '4242\n' }
+ return { stdout: '%3\n' } // list-panes
+ }
+
+ const removed: string[] = []
+ const timer = startTmuxReaper(1000, (id) => { removed.push(id); registry.remove(id) })
+ await vi.advanceTimersByTimeAsync(1500) // identity captured under the boot title
+ title = '⌘ Greeting'
+ await vi.advanceTimersByTimeAsync(4000) // four more ticks — twice the reaper's miss limit
+ clearInterval(timer)
+
+ expect(removed).toEqual([])
+ expect(registry.has('cc-1')).toBe(true)
+ expect(registry.get('cc-1')?.processIdentity?.startMarker).toBe('Thu Jul 30 11:00:03 2026')
+ })
+
+ it('keeps a session when the process probe itself fails, and evicts once it answers', async () => {
+ const { registry, startTmuxReaper } = await loadModules()
+ registry.load()
+ registry.register({ launcherId: 'h1', engine: 'commandcode', sessionId: 'cc-3', tmuxPane: '%3', cwd: '/tmp/demo' })
+
+ // `ps` / `tmux display-message` are subprocesses with 2-3s timeouts. A timeout says nothing about
+ // whether the pane's CLI is alive, so it must not spend a reaper miss — this is what dropped a live
+ // Command Code pane with "no commandcode process under pane %3".
+ let psFails = true
+ execResponder = (cmd, args) => {
+ if (cmd === 'ps') {
+ return psFails
+ ? { err: new Error('spawn ps ETIMEDOUT') }
+ : { stdout: '4242 1 ⌘ Greeting Thu Jul 30 11:00:03 2026 ⌘ Greeting\n' }
+ }
+ if (args[0] === 'display-message') return { stdout: '4242\n' }
+ return { stdout: '%3\n' }
+ }
+
+ const removed: string[] = []
+ const timer = startTmuxReaper(1000, (id) => { removed.push(id); registry.remove(id) })
+ await vi.advanceTimersByTimeAsync(6000) // six failed probes — twice would have been fatal before
+ expect(removed).toEqual([])
+ expect(registry.has('cc-3')).toBe(true)
+
+ // …and the tolerance is only for the unknown: once ps answers and the pane really is empty, it goes.
+ psFails = false
+ await vi.advanceTimersByTimeAsync(1500)
+ expect(registry.get('cc-3')?.processIdentity?.pid).toBe(4242) // adopted the process it can now see
+
+ execResponder = (cmd, args) => {
+ if (cmd === 'ps') return { stdout: '999 1 zsh Thu Jul 30 11:00:03 2026 -zsh\n' }
+ if (args[0] === 'display-message') return { stdout: '4242\n' }
+ return { stdout: '%3\n' }
+ }
+ await vi.advanceTimersByTimeAsync(3000)
+ clearInterval(timer)
+
+ expect(removed).toEqual(['cc-3'])
+ })
+
+ it('adopts a legacy identity written by the pre-fix parser instead of evicting', async () => {
+ const { registry, startTmuxReaper } = await loadModules()
+ registry.load()
+ registry.register({ launcherId: 'h1', engine: 'commandcode', sessionId: 'cc-2', tmuxPane: '%3', cwd: '/tmp/demo' })
+ // What the old parser persisted: comm truncated to `⌘`, the title swallowed into the start time.
+ registry.updateProcessIdentity('cc-2', {
+ pid: 4242,
+ executable: '⌘',
+ startMarker: 'Greeting Thu Jul 30 11:00:03',
+ })
+
+ execResponder = (cmd, args) => {
+ if (cmd === 'ps') return { stdout: '4242 1 ⌘ Greeting Thu Jul 30 11:00:03 2026 ⌘ Greeting\n' }
+ if (args[0] === 'display-message') return { stdout: '4242\n' }
+ return { stdout: '%3\n' }
+ }
+
+ const removed: string[] = []
+ const timer = startTmuxReaper(1000, (id) => { removed.push(id); registry.remove(id) })
+ await vi.advanceTimersByTimeAsync(3000)
+ clearInterval(timer)
+
+ expect(removed).toEqual([])
+ expect(registry.get('cc-2')?.processIdentity).toEqual({
+ pid: 4242,
+ executable: '⌘ Greeting',
+ startMarker: 'Thu Jul 30 11:00:03 2026',
+ })
+ })
+
+ it('matches Devin by its bare argv and by the versioned entrypoint', async () => {
+ const { engineProcessMatchScore } = await loadModules()
+
+ // `ps -o command=` on a live pane prints exactly `devin` — the symlink name, no path, no args.
+ expect(engineProcessMatchScore({ executable: 'devin', args: 'devin' }, 'devin')).toBe(3)
+ expect(engineProcessMatchScore(
+ { executable: '/Users/x/.local/share/devin/cli/_versions/3000.2.17/bin/devin', args: 'devin -r' },
+ 'devin',
+ )).toBe(3)
+ expect(engineProcessMatchScore({ executable: 'claude', args: 'claude' }, 'devin')).toBe(0)
+ })
+
+ it('extracts resume session ids per engine, and only when the value looks like an id', async () => {
+ const { resumeSessionId } = await loadModules()
+
+ // Both cursor spellings.
+ expect(resumeSessionId('cursor', 'agent --resume=53d3843c-724e-47ff-ae3a-9fedfa328bba'))
+ .toBe('53d3843c-724e-47ff-ae3a-9fedfa328bba')
+ expect(resumeSessionId('cursor', 'agent --resume 53d3843c-724e-47ff-ae3a-9fedfa328bba'))
+ .toBe('53d3843c-724e-47ff-ae3a-9fedfa328bba')
+ expect(resumeSessionId('cursor', 'agent --model sonnet')).toBeNull()
+
+ // Real argv captured on 2026-08-03 from panes the daemon had failed to list.
+ expect(resumeSessionId('opencode', 'opencode -s ses_05e335115ffeM05DT5hJHeN3Vp'))
+ .toBe('ses_05e335115ffeM05DT5hJHeN3Vp')
+ expect(resumeSessionId('hermes', 'python3.11 hermes --resume 20260728_115628_f2c86a'))
+ .toBe('20260728_115628_f2c86a')
+
+ // `-r` on Command Code takes an id OR a human title — a title is not a session id.
+ expect(resumeSessionId('commandcode', 'cmd -r 1348716c-421f-417f-99ef-cd6096ed248a'))
+ .toBe('1348716c-421f-417f-99ef-cd6096ed248a')
+ expect(resumeSessionId('commandcode', 'cmd -r Greeting')).toBeNull()
+
+ // `--continue` carries no id on any engine: nothing to adopt, and nothing to invent.
+ expect(resumeSessionId('opencode', 'opencode --continue')).toBeNull()
+ expect(resumeSessionId('hermes', 'hermes --continue')).toBeNull()
+ // Claude and codex are handled by their own SessionStart hooks, so argv is not read for them.
+ expect(resumeSessionId('claude', 'claude --resume 53d3843c-724e-47ff-ae3a-9fedfa328bba')).toBeNull()
+ })
+
+ it('discovers an idle Cursor resume from its tmux process tree', async () => {
+ const { discoverTmuxResumes } = await loadModules()
+ execResponder = (cmd, args) => {
+ if (cmd === 'tmux' && args[0] === 'list-panes') {
+ return { stdout: '%23\t63442\t/tmp/cursor-project\n' }
+ }
+ if (cmd === 'ps') {
+ return {
+ stdout: [
+ '63442 1 zsh Thu Jul 23 14:18:50 2026 -zsh',
+ '64095 63442 /Users/demo/.local/bin/agent Thu Jul 23 14:18:57 2026 /Users/demo/.local/share/cursor-agent/versions/2026.07.20/index.js --resume=53d3843c-724e-47ff-ae3a-9fedfa328bba',
+ ].join('\n'),
+ }
+ }
+ return { err: new Error(`unexpected command: ${cmd}`) }
+ }
+
+ await expect(discoverTmuxResumes()).resolves.toEqual([{
+ engine: 'cursor',
+ sessionId: '53d3843c-724e-47ff-ae3a-9fedfa328bba',
+ tmuxPane: '%23',
+ cwd: '/tmp/cursor-project',
+ processIdentity: {
+ pid: 64095,
+ executable: '/Users/demo/.local/bin/agent',
+ startMarker: 'Thu Jul 23 14:18:57 2026',
+ },
+ }])
+ })
+
+ it('discovers a resumed session for a non-cursor engine too', async () => {
+ const { discoverTmuxResumes } = await loadModules()
+ execResponder = (cmd, args) => {
+ if (cmd === 'tmux' && args[0] === 'list-panes') {
+ return { stdout: '%3\t70597\t/tmp/oc\n' }
+ }
+ if (cmd === 'ps') {
+ return {
+ stdout: [
+ '70597 1 zsh Fri Jul 31 16:57:00 2026 -zsh',
+ '45656 70597 opencode Fri Jul 31 16:57:01 2026 opencode -s ses_05e335115ffeM05DT5hJHeN3Vp',
+ ].join('\n'),
+ }
+ }
+ return { err: new Error(`unexpected command: ${cmd}`) }
+ }
+
+ await expect(discoverTmuxResumes()).resolves.toEqual([{
+ engine: 'opencode',
+ sessionId: 'ses_05e335115ffeM05DT5hJHeN3Vp',
+ tmuxPane: '%3',
+ cwd: '/tmp/oc',
+ processIdentity: {
+ pid: 45656,
+ executable: 'opencode',
+ startMarker: 'Fri Jul 31 16:57:01 2026',
+ },
+ }])
+ })
+
+ it('ignores a session resumed in more than one tmux pane', async () => {
+ const { discoverTmuxResumes } = await loadModules()
+ execResponder = (cmd, args) => {
+ if (cmd === 'tmux' && args[0] === 'list-panes') {
+ return { stdout: '%23\t63442\t/tmp/one\n%24\t63443\t/tmp/two\n' }
+ }
+ if (cmd === 'ps') {
+ return {
+ stdout: [
+ '64095 63442 agent Thu Jul 23 14:18:57 2026 agent --resume=53d3843c-724e-47ff-ae3a-9fedfa328bba',
+ '64096 63443 agent Thu Jul 23 14:19:57 2026 agent --resume=53d3843c-724e-47ff-ae3a-9fedfa328bba',
+ ].join('\n'),
+ }
+ }
+ return { err: new Error(`unexpected command: ${cmd}`) }
+ }
+
+ await expect(discoverTmuxResumes()).resolves.toEqual([])
+ })
+})
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
new file mode 100644
index 000000000..732491535
--- /dev/null
+++ b/cli/src/lib/tmux.ts
@@ -0,0 +1,583 @@
+/**
+ * tmux integration: pane liveness (reaper) + typing messages into a pane.
+ *
+ * The reaper handles hard-killed panes: a killed pane (or a dead tmux server) terminates claude
+ * before SessionEnd can fire, which would leave the session registered forever. It periodically
+ * checks which panes still exist and drops any registered session whose pane is gone (debounced
+ * by 2 consecutive misses).
+ */
+
+import { execFile, spawn } from 'child_process'
+import { basename } from 'path'
+import { registry, type ProcessIdentity, type RegisteredSession } from './registry.js'
+import { launcherSessions } from './launcherSessions.js'
+
+const MISS_LIMIT = 2
+
+type PaneListResult =
+ | { ok: true; panes: Set<string> }
+ | { ok: false; error: string }
+
+/** Live tmux pane ids (e.g. "%0","%3"). Empty set if tmux is unreachable. */
+export function listLivePanes(): Promise<PaneListResult> {
+ return new Promise((resolve) => {
+ execFile('tmux', ['list-panes', '-a', '-F', '#{pane_id}'], { timeout: 2000 }, (err, stdout) => {
+ if (err) {
+ resolve({ ok: false, error: err.message })
+ return
+ }
+ const panes = stdout
+ .split('\n')
+ .map((l) => l.trim())
+ .filter(Boolean)
+ resolve({ ok: true, panes: new Set(panes) })
+ })
+ })
+}
+
+function cleanPaneTitle(title: string): string | null {
+ const cleaned = title
+ .trim()
+ .replace(/^[\s"'`*✳✱✲✴✶✷✸✹✺✻✼✽✾✿❃❉❋•·.-]+/, '')
+ .trim()
+ .slice(0, 80)
+ return cleaned || null
+}
+
+/** Current tmux pane titles keyed by pane id. AI CLIs update this with their live session title. */
+export function listPaneTitles(): Promise<Map<string, string>> {
+ return new Promise((resolve) => {
+ execFile('tmux', ['list-panes', '-a', '-F', '#{pane_id}\t#{pane_title}'], { timeout: 2000 }, (err, stdout) => {
+ const titles = new Map<string, string>()
+ if (err) { resolve(titles); return }
+ for (const line of stdout.split('\n')) {
+ const [pane, ...titleParts] = line.split('\t')
+ if (!/^%\d+$/.test(pane)) continue
+ const title = cleanPaneTitle(titleParts.join('\t'))
+ if (title) titles.set(pane, title)
+ }
+ resolve(titles)
+ })
+ })
+}
+
+interface ProcessRow extends ProcessIdentity {
+ parentPid: number
+ args: string
+}
+
+interface TmuxPaneProcess {
+ tmuxPane: string
+ rootPid: number
+ cwd: string
+}
+
+export interface TmuxResume {
+ engine: RegisteredSession['engine']
+ sessionId: string
+ tmuxPane: string
+ cwd: string
+ processIdentity: ProcessIdentity
+}
+
+/**
+ * One `ps -axo pid=,ppid=,comm=,lstart=,args=` line → a row.
+ *
+ * `comm` can itself contain spaces: Command Code rewrites its argv to `⌘ <session title>` and macOS
+ * prints that verbatim as the command name. Splitting comm off as a single `\S+` therefore shifted every
+ * later field — `startMarker` came out as `"<rest of title> Thu Jul 30"` instead of a start time, so it
+ * changed whenever Command Code renamed the session, `validateSessionRuntime` saw a different process,
+ * and the reaper evicted a live pane ~10s after its first turn (observed four times on one session; the
+ * pane went on serving turn-stop hooks after being declared "gone"). It also silently defeated the
+ * PID-reuse guard that startMarker exists for.
+ *
+ * So anchor on `lstart` instead — it is the one field with a fixed shape (`DOW MON DD HH:MM:SS YYYY`) —
+ * and let comm be lazy. The day/month names stay unconstrained so a non-English `LC_TIME` still parses.
+ */
+export function parseProcessRow(line: string): ProcessRow | null {
+ const match = /^\s*(\d+)\s+(\d+)\s+(.+?)\s+(\S+\s+\S+\s+\d{1,2}\s+\d{1,2}:\d{2}:\d{2}\s+\d{4})\s*(.*)$/.exec(line)
+ if (!match) return null
+ return {
+ pid: Number(match[1]),
+ parentPid: Number(match[2]),
+ executable: match[3],
+ startMarker: match[4],
+ args: match[5],
+ }
+}
+
+/** The process table, or null when `ps` itself failed — "we could not look" is not "nothing is there". */
+function processRows(): Promise<ProcessRow[] | null> {
+ return new Promise((resolve) => {
+ execFile('ps', ['-axo', 'pid=,ppid=,comm=,lstart=,args='], { timeout: 3000 }, (err, stdout) => {
+ if (err) { resolve(null); return }
+ const rows: ProcessRow[] = []
+ for (const line of stdout.split('\n')) {
+ const row = parseProcessRow(line)
+ if (row) rows.push(row)
+ }
+ resolve(rows)
+ })
+ })
+}
+
+function tmuxPaneProcesses(): Promise<TmuxPaneProcess[]> {
+ return new Promise((resolve) => {
+ execFile(
+ 'tmux',
+ ['list-panes', '-a', '-F', '#{pane_id}\t#{pane_pid}\t#{pane_current_path}'],
+ { timeout: 2000 },
+ (err, stdout) => {
+ if (err) { resolve([]); return }
+ const panes: TmuxPaneProcess[] = []
+ for (const line of stdout.split('\n')) {
+ const [tmuxPane, pidText, ...cwdParts] = line.split('\t')
+ const rootPid = Number(pidText)
+ if (!/^%\d+$/.test(tmuxPane) || !Number.isSafeInteger(rootPid) || rootPid <= 0) continue
+ panes.push({ tmuxPane, rootPid, cwd: cwdParts.join('\t') })
+ }
+ resolve(panes)
+ },
+ )
+ })
+}
+
+function panePid(pane: string): Promise<number | null> {
+ return new Promise((resolve) => {
+ execFile('tmux', ['display-message', '-p', '-t', pane, '#{pane_pid}'], { timeout: 2000 }, (err, stdout) => {
+ const pid = Number(stdout.trim())
+ resolve(!err && Number.isSafeInteger(pid) && pid > 0 ? pid : null)
+ })
+ })
+}
+
+export function engineProcessMatchScore(
+ row: Pick<ProcessRow, 'executable' | 'args'>,
+ engine: RegisteredSession['engine'],
+): number {
+ const haystack = `${row.executable} ${row.args}`.toLowerCase()
+ const executable = basename(row.executable).toLowerCase()
+ if (engine === 'codex') {
+ if (executable === 'codex') return 3
+ return /(^|[\/\s])codex(?:[\s]|$)/.test(haystack) ? 1 : 0
+ }
+ if (engine === 'cursor') {
+ if (executable === 'agent' || executable === 'cursor-agent') return 3
+ return /cursor-agent[\/\\]versions[\/\\][^/\\\s]+[\/\\]index\.js(?:\s|$)/.test(haystack) ? 1 : 0
+ }
+ if (engine === 'opencode') {
+ if (executable === 'opencode') return 3
+ return /(^|[\/\s])opencode(?:[\s]|$)/.test(haystack) ? 1 : 0
+ }
+ if (engine === 'commandcode') {
+ // The TUI overwrites its own argv within the first second — `ps` shows `⌘ Command Code · <dir>` and
+ // then `⌘ <session title>`, with no trace of the node entrypoint. So the ⌘ (U+2318) prefix is the
+ // only marker present for a pane's whole life; without it a live session fails validateSessionRuntime
+ // and the reaper evicts it. The entrypoint rules below still cover a non-renaming/wrapped launch.
+ if (/^\s*⌘(?:\s|$)/.test(haystack)) return 3
+ if (/command-code[\/\\]dist[\/\\]index\.mjs(?:\s|$)/.test(haystack)) return 3
+ if (executable === 'commandcode' || executable === 'command-code') return 3
+ return /(^|[\/\s])commandcode(?:[\s]|$)/.test(haystack) ? 1 : 0
+ }
+ if (engine === 'devin') {
+ // `~/.local/bin/devin` is a symlink into `…/devin/cli/_versions/<ver>/bin/devin`, but the pane process
+ // keeps the bare `devin` argv (verified live: `ps -o command=` prints exactly `devin`), so the
+ // basename is the primary signal and the versioned path only covers a direct/wrapped launch.
+ if (executable === 'devin') return 3
+ if (/devin[\/\\]cli[\/\\]_versions[\/\\][^/\\\s]+[\/\\]bin[\/\\]devin(?:\s|$)/.test(haystack)) return 3
+ return /(^|[\/\s])devin(?:[\s]|$)/.test(haystack) ? 1 : 0
+ }
+ if (engine === 'hermes') {
+ // The launcher shim `exec`s away, so the pane process is `…/venv/bin/python …/hermes-agent/hermes`.
+ if (/hermes-agent[\/\\]hermes(?:\s|$)/.test(haystack)) return 3
+ if (executable === 'hermes') return 3
+ return /(^|[\/\s])hermes(?:[\s]|$)/.test(haystack) ? 1 : 0
+ }
+ if (engine === 'pi') {
+ // Pi sets process.title = 'pi'; when the platform ignores that it stays `node …/pi-coding-agent/dist/cli.js`.
+ if (executable === 'pi') return 3
+ return /pi-coding-agent[\/\\]dist[\/\\]cli\.js(?:\s|$)|(^|[\/\s])pi(?:[\s]|$)/.test(haystack) ? 1 : 0
+ }
+ if (executable === 'claude') return 3
+ return /(^|[\/\s])claude(?:[\s]|$)/.test(haystack) ? 1 : 0
+}
+
+function selectEngineProcess(
+ rows: ProcessRow[],
+ rootPid: number,
+ engine: RegisteredSession['engine'],
+): ProcessRow | null {
+ const byPid = new Map(rows.map((row) => [row.pid, row]))
+ 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)
+ }
+ const queue: Array<{ pid: number; depth: number }> = [{ pid: rootPid, depth: 0 }]
+ let best: { row: ProcessRow; depth: number; score: number } | null = null
+ while (queue.length > 0) {
+ const current = queue.shift()!
+ const row = byPid.get(current.pid)
+ const score = row ? engineProcessMatchScore(row, engine) : 0
+ if (row && score > 0 && (!best || score > best.score || (score === best.score && current.depth < best.depth))) {
+ best = { row, depth: current.depth, score }
+ }
+ for (const child of children.get(current.pid) ?? []) queue.push({ pid: child.pid, depth: current.depth + 1 })
+ }
+ return best?.row ?? null
+}
+
+/**
+ * How each engine names an already-existing session on its command line, and what its ids look like.
+ *
+ * This exists because RESUMING is the one way to start an agent that announces nothing: the engine's
+ * SessionStart hook fires for a NEW session, so a pane that reattached to an old one is invisible to the
+ * daemon until the user happens to type. Read from each CLI's own `--help` on 2026-08-03.
+ *
+ * Two deliberate holes:
+ * - `--continue` / `-c` carries NO id on any of these CLIs. Nothing can be recovered from argv there.
+ * - claude and codex are absent: `registry.register` demands a transcript path for those two, which
+ * argv does not carry — and both DO fire SessionStart on resume, so there is nothing to repair.
+ *
+ * The id pattern is a filter, not decoration: `-r` on Command Code takes "a name (use quotes for
+ * multi-word names)", so a title would otherwise be registered as a session id.
+ */
+const RESUME_ARGS: Partial<Record<RegisteredSession['engine'], { flags: string[]; id: RegExp }>> = {
+ cursor: { flags: ['--resume'], id: /^[0-9a-f-]{16,}$/i },
+ opencode: { flags: ['--session', '-s'], id: /^ses_[A-Za-z0-9]+$/ },
+ pi: { flags: ['--session', '--session-id'], id: /^[0-9a-f][0-9a-f-]{7,}$/i },
+ // Hermes ids are timestamps: 20260728_115628_f2c86a.
+ hermes: { flags: ['--resume'], id: /^\d{8}_\d{6}_[0-9a-z]+$/i },
+ commandcode: { flags: ['--resume', '-r', '--session'], id: /^[0-9a-f-]{16,}$/i },
+}
+
+/** The session id an engine was told to resume, or null when argv does not name one. */
+export function resumeSessionId(engine: RegisteredSession['engine'], args: string): string | null {
+ const spec = RESUME_ARGS[engine]
+ if (!spec) return null
+ for (const flag of spec.flags) {
+ const escaped = flag.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+ const value = new RegExp(`(?:^|\\s)${escaped}(?:=|\\s+)(\\S+)`, 'i').exec(args)?.[1]
+ if (value && spec.id.test(value)) return value
+ }
+ return null
+}
+
+/**
+ * Every tmux pane whose engine was launched against an EXISTING session, from the stable CLI process.
+ * Ambiguous duplicate resumes are ignored rather than assigning one remote tab to an arbitrary pane.
+ *
+ * Only the pane and its argv are read here; whether such a session may be adopted is the caller's call
+ * (it needs a live launcher on that pane — see cli.ts).
+ */
+export async function discoverTmuxResumes(): Promise<TmuxResume[]> {
+ const [panes, probed] = await Promise.all([tmuxPaneProcesses(), processRows()])
+ const rows = probed ?? []
+ const candidates = new Map<string, TmuxResume[]>()
+ for (const pane of panes) {
+ for (const engine of Object.keys(RESUME_ARGS) as Array<RegisteredSession['engine']>) {
+ const process = selectEngineProcess(rows, pane.rootPid, engine)
+ if (!process) continue
+ const sessionId = resumeSessionId(engine, process.args)
+ if (!sessionId) continue
+ const candidate: TmuxResume = {
+ engine,
+ sessionId,
+ tmuxPane: pane.tmuxPane,
+ cwd: pane.cwd,
+ processIdentity: {
+ pid: process.pid,
+ executable: process.executable,
+ startMarker: process.startMarker,
+ },
+ }
+ const matches = candidates.get(sessionId) ?? []
+ matches.push(candidate)
+ candidates.set(sessionId, matches)
+ break // one engine per pane: the first match owns it
+ }
+ }
+ return [...candidates.values()].filter((matches) => matches.length === 1).map(([match]) => match)
+}
+
+/**
+ * Resolve the stable CLI process below one tmux pane, ahead of short-lived helper descendants — and say
+ * whether a negative answer means "nothing is running there" or "the probe itself failed". Those are not
+ * the same fact: `tmux display-message` and `ps` are subprocesses with 2-3s timeouts, and treating a
+ * timeout as proof of death evicts a live session.
+ */
+type PaneProcessLookup =
+ | { ok: true; identity: ProcessIdentity }
+ | { ok: false; unknown: boolean; reason: string }
+
+async function lookupPaneEngineProcess(
+ pane: string,
+ engine: RegisteredSession['engine'],
+): Promise<PaneProcessLookup> {
+ const rootPid = await panePid(pane)
+ // The caller already confirmed the pane is in `tmux list-panes`, so a failure here is the tmux call,
+ // not a missing pane.
+ if (!rootPid) return { ok: false, unknown: true, reason: `tmux could not resolve pane ${pane}` }
+ const rows = await processRows()
+ if (!rows) return { ok: false, unknown: true, reason: 'the process table could not be read' }
+ const process = selectEngineProcess(rows, rootPid, engine)
+ if (!process) return { ok: false, unknown: false, reason: `no ${engine} process under pane ${pane}` }
+ return {
+ ok: true,
+ identity: { pid: process.pid, executable: process.executable, startMarker: process.startMarker },
+ }
+}
+
+/** Boolean form for callers that only need "is it there". */
+export async function resolvePaneEngineProcess(
+ pane: string,
+ engine: RegisteredSession['engine'],
+): Promise<ProcessIdentity | null> {
+ const found = await lookupPaneEngineProcess(pane, engine)
+ return found.ok ? found.identity : null
+}
+
+/** A whole `lstart` stamp — `DOW MON DD HH:MM:SS YYYY` — and nothing else. */
+const LSTART_MARKER_RE = /^\S+\s+\S+\s+\d{1,2}\s+\d{1,2}:\d{2}:\d{2}\s+\d{4}$/
+
+/** Pane + engine process validation. A saved identity prevents PID reuse from reviving a stale entry. */
+export async function validateSessionRuntime(session: RegisteredSession): Promise<boolean> {
+ return (await checkSessionRuntime(session)).state === 'alive'
+}
+
+/**
+ * The same check, but three-valued and with a reason — the reaper needs both.
+ *
+ * `unknown` exists because a failed probe is not evidence of death. The reaper already refuses to evict
+ * when `tmux list-panes` fails; the per-session probes (`tmux display-message`, `ps`) deserve exactly the
+ * same treatment, and did not get it: a live Command Code pane was dropped with "no commandcode process
+ * under pane %3" 14s after attaching, while that process was demonstrably running — still alive minutes
+ * later, and matched by this very resolver run by hand. The eviction landed 3.6s into a 5s tick, i.e.
+ * `ps` had hit its 3s timeout during the load spike of a freshly started daemon warming its pools.
+ *
+ * The reason string matters just as much. "process for pane %3 gone" read identically whether the user
+ * had quit the CLI or the adapter had simply lost sight of it, and telling those apart after the fact
+ * means reconstructing a process table that no longer exists.
+ */
+type RuntimeCheck =
+ | { state: 'alive' }
+ | { state: 'gone'; reason: string }
+ | { state: 'unknown'; reason: string }
+
+async function checkSessionRuntime(session: RegisteredSession): Promise<RuntimeCheck> {
+ const found = await lookupPaneEngineProcess(session.tmuxPane, session.engine)
+ if (!found.ok) return { state: found.unknown ? 'unknown' : 'gone', reason: found.reason }
+ const live = found.identity
+ const saved = session.processIdentity
+ // A persisted identity whose startMarker is not an lstart stamp was written by the pre-fix parser (see
+ // parseProcessRow) — its fields are shifted, so it can NEVER match the corrected ones again. Adopt the
+ // corrected identity instead of failing: the pane still has a matching engine process, and failing here
+ // would drop a live session for good (Command Code, the only engine affected, does not re-register on
+ // its Stop hook). One-time, per session.
+ if (saved && !LSTART_MARKER_RE.test(saved.startMarker)) {
+ registry.updateProcessIdentity(session.sessionId, live)
+ return { state: 'alive' }
+ }
+ // pid + start time IS the identity of a process, and neither can change under it — that is the whole
+ // PID-reuse guard. `executable` is argv-derived and therefore mutable (Command Code rewrites its own
+ // argv to `⌘ <session title>` and renames the session mid-life), so it is recorded but not compared:
+ // comparing it evicted live panes for renaming themselves.
+ if (saved && (saved.pid !== live.pid || saved.startMarker !== live.startMarker)) {
+ return {
+ state: 'gone',
+ reason: `process changed under pane ${session.tmuxPane}`
+ + ` (was pid ${saved.pid} @ ${saved.startMarker}, now pid ${live.pid} @ ${live.startMarker})`,
+ }
+ }
+ if (!saved) registry.updateProcessIdentity(session.sessionId, live)
+ 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).
+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).
+const INJECT_PASTE_DELAY_BASE_MS = 400
+// A NAMED tmux buffer so we never clobber the user's default paste buffer; `-d` deletes it after paste.
+let injectBufferSequence = 0
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((r) => setTimeout(r, ms))
+}
+
+function tmuxEnter(pane: string): Promise<boolean> {
+ return new Promise((resolve) => {
+ execFile('tmux', ['send-keys', '-t', pane, 'Enter'], { timeout: 2000 }, (err) => {
+ if (err) console.error(`[tmux] Enter to ${pane} failed:`, err.message)
+ resolve(!err)
+ })
+ })
+}
+
+/** Stage text in a NAMED tmux buffer via stdin (avoids arg-length limits + the user's default buffer). */
+function tmuxLoadBuffer(name: string, content: string): Promise<boolean> {
+ return new Promise((resolve) => {
+ const c = spawn('tmux', ['load-buffer', '-b', name, '-'])
+ c.on('error', () => resolve(false))
+ c.on('close', (code) => resolve(code === 0))
+ c.stdin.on('error', () => { /* EPIPE if tmux died first — 'close' still resolves false */ })
+ c.stdin.end(content)
+ })
+}
+
+/**
+ * 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.
+ *
+ * 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.)
+ */
+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)))
+ return tmuxEnter(pane)
+ })()
+}
+
+/** Send a control key (e.g. 'C-c' to interrupt) to a pane. */
+/**
+ * Type text into a pane WITHOUT submitting it. Needed by filter boxes that act on every keystroke: pi's
+ * settings list opens a row as soon as the filter narrows to one, so the Enter `sendToTmux` appends would
+ * 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)
+ })
+ })
+}
+
+export function sendKeyToTmux(pane: string, key: string): Promise<boolean> {
+ return new Promise((resolve) => {
+ execFile('tmux', ['send-keys', '-t', pane, key], { timeout: 2000 }, (err) => resolve(!err))
+ })
+}
+
+/** 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> {
+ const bounded = Math.max(20, Math.min(300, Math.floor(historyLines)))
+ return new Promise((resolve) => {
+ execFile('tmux', ['capture-pane', '-p', '-e', '-J', '-t', pane, '-S', `-${bounded}`], { timeout: 2000 }, (err, stdout) => {
+ if (err) { resolve(null); return }
+ resolve(stdout)
+ })
+ })
+}
+
+/**
+ * Nothing here kills a pane, on purpose.
+ *
+ * Deleting an agent used to run `tmux kill-pane` — which also closed the window, and the session when it
+ * was the last pane. That destroys the user's workspace to end OUR process. Deletion now asks the
+ * launcher to stop its engine and exit (see `deleteAgentFallback.ts`), leaving the pane and its shell.
+ *
+ * Known limit: a pane whose ROOT process is the launcher itself (`tmux new-session 'harness claude'`,
+ * with no shell in between) still disappears when the launcher exits. Nothing at this layer can change
+ * that — it follows from how the pane was created.
+ */
+
+export function startTmuxReaper(
+ intervalMs: number,
+ onRemoved: (sessionId: string) => void,
+): NodeJS.Timeout {
+ const misses = new Map<string, number>()
+
+ // A tick shells out to tmux + `ps` per session. `setInterval` does not wait for the previous one, so a
+ // slow tick used to overlap the next — piling on more `ps` calls exactly when the computer is already too
+ // busy to answer them, which is how two probes time out back to back and a live pane looks dead.
+ let ticking = false
+
+ const tick = async (): Promise<void> => {
+ if (ticking) return
+ const sessions = registry.list()
+ if (sessions.length === 0) {
+ misses.clear()
+ return
+ }
+ ticking = true
+ try {
+ await sweep(sessions)
+ } finally {
+ ticking = false
+ }
+ }
+
+ const sweep = async (sessions: RegisteredSession[]): Promise<void> => {
+ const live = await listLivePanes()
+ if (!live.ok) {
+ misses.clear()
+ console.warn(`[reaper] tmux list-panes failed; keeping ${sessions.length} registered session(s): ${live.error}`)
+ return
+ }
+
+ for (const s of sessions) {
+ // The launcher's socket outranks every probe below. An agent exists exactly as long as its wrapper
+ // is connected (launcherSessions.ts), and that is a fact the daemon HOLDS — while `tmux` and `ps` are
+ // subprocesses that can time out, and whose answer already cost a live Command Code pane once (it
+ // renames its own argv mid-life). If the wrapper is still there, so is the agent; nothing to check.
+ if (launcherSessions.has(s.launcherId)) {
+ misses.delete(s.sessionId)
+ continue
+ }
+ const check: RuntimeCheck = live.panes.has(s.tmuxPane)
+ ? await checkSessionRuntime(s)
+ : { state: 'gone', reason: `pane ${s.tmuxPane} is gone` }
+ if (check.state === 'alive') {
+ misses.delete(s.sessionId)
+ continue
+ }
+ // Inconclusive: hold the session and the miss count where they are. Same rule as the list-panes
+ // failure above — the adapter only evicts on evidence that the process is gone, never on a probe
+ // it could not complete.
+ if (check.state === 'unknown') {
+ console.warn(`[reaper] keeping ${s.engine} session ${s.sessionId} · ${check.reason}`)
+ continue
+ }
+ const n = (misses.get(s.sessionId) ?? 0) + 1
+ if (n >= MISS_LIMIT) {
+ misses.delete(s.sessionId)
+ console.log(`[reaper] removing ${s.engine} session ${s.sessionId} · ${check.reason}`)
+ onRemoved(s.sessionId)
+ } else {
+ misses.set(s.sessionId, n)
+ }
+ }
+ }
+
+ return setInterval(() => void tick(), intervalMs)
+}
diff --git a/cli/src/lib/voiceRouter.spec.ts b/cli/src/lib/voiceRouter.spec.ts
new file mode 100644
index 000000000..e55371ab2
--- /dev/null
+++ b/cli/src/lib/voiceRouter.spec.ts
@@ -0,0 +1,230 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+// Mock the one-shot LLM runner so routeVoiceTask can be tested without spawning `claude`. The behavior is
+// driven by a PLAIN per-test impl (routerImpl) rather than the vi.fn's own return, so a rejection is only ever
+// consumed by routeVoiceTask's await — this avoids tinyspy's async settled-result tracking leaving an
+// unhandled rejection once a resolved test has run on the same spy. The vi.fn is kept only for call counts.
+const runRouterOneShot = vi.fn()
+let routerImpl: (o: unknown) => Promise<{ text: string; sessionId: null }> = async () => ({ text: '', sessionId: null })
+vi.mock('./oneshot.js', () => ({
+ runRouterOneShot: (...args: unknown[]) => { runRouterOneShot(...args); return routerImpl(args[0]) },
+ configureRouterOneShot: vi.fn(),
+ setRouterOneShotDeviceConnected: vi.fn(),
+ shutdownRouterOneShot: vi.fn(),
+}))
+
+// Import AFTER the mock is registered.
+const { buildRouterPrompt, parseRouteOutput, routeVoiceTask, pickAgentHeuristic, chooseRouterEngine, routerModelFor } = await import('./voiceRouter.js')
+type RouterAgent = import('./voiceRouter.js').RouterAgent
+
+const AGENTS: RouterAgent[] = [
+ { id: '1', name: 'Frontend', recentSummary: 'dark mode + settings page', engine: 'claude' },
+ { id: '2', name: 'Auth', recentSummary: 'JWT refresh, login rate-limit', engine: 'claude' },
+ { id: '3', name: 'DevOps', engine: 'claude' },
+]
+
+describe('parseRouteOutput', () => {
+ it('parses a clean JSON object', () => {
+ const d = parseRouteOutput('{"agentId":"2","confidence":0.9,"reason":"login","needNewAgent":false}', AGENTS)
+ expect(d).toEqual({ agentId: '2', confidence: 0.9, reason: 'login', needNewAgent: false })
+ })
+
+ it('extracts JSON from a markdown code fence', () => {
+ const raw = '```json\n{"agentId":"1","confidence":0.8,"reason":"ui","needNewAgent":false}\n```'
+ expect(parseRouteOutput(raw, AGENTS).agentId).toBe('1')
+ })
+
+ it('extracts JSON wrapped in prose', () => {
+ const raw = 'Sure! Here is the routing: {"agentId":"3","confidence":0.7,"reason":"deploy","needNewAgent":false} — done.'
+ expect(parseRouteOutput(raw, AGENTS).agentId).toBe('3')
+ })
+
+ it('clamps confidence to [0,1]', () => {
+ expect(parseRouteOutput('{"agentId":"1","confidence":5,"reason":"x","needNewAgent":false}', AGENTS).confidence).toBe(1)
+ expect(parseRouteOutput('{"agentId":"1","confidence":-2,"reason":"x","needNewAgent":false}', AGENTS).confidence).toBe(0)
+ })
+
+ it('coerces a string confidence', () => {
+ expect(parseRouteOutput('{"agentId":"1","confidence":"0.55","reason":"x","needNewAgent":false}', AGENTS).confidence).toBeCloseTo(0.55)
+ })
+
+ it('falls back to the closest (first) agent when the id is NOT in the machine (and caps confidence)', () => {
+ const d = parseRouteOutput('{"agentId":"99","confidence":0.95,"reason":"x"}', AGENTS)
+ expect(d.agentId).toBe('1')
+ expect(d.needNewAgent).toBe(false)
+ expect(d.confidence).toBeLessThanOrEqual(0.3)
+ })
+
+ it('falls back to the closest (first) agent when agentId is empty — never "no agent"', () => {
+ const d = parseRouteOutput('{"agentId":"","confidence":0.2,"reason":"no fit"}', AGENTS)
+ expect(d.agentId).toBe('1')
+ expect(d.needNewAgent).toBe(false)
+ })
+
+ it('ignores a stray needNewAgent:true — a valid pick always wins', () => {
+ const d = parseRouteOutput('{"agentId":"2","confidence":0.5,"reason":"auth","needNewAgent":true}', AGENTS)
+ expect(d.needNewAgent).toBe(false)
+ expect(d.agentId).toBe('2')
+ })
+
+ it('falls back to the closest agent (never needNewAgent) on malformed / non-JSON output', () => {
+ for (const raw of ['', 'not json at all', '{ broken', 'null', '{"agentId":']) {
+ const d = parseRouteOutput(raw, AGENTS)
+ expect(d.needNewAgent).toBe(false)
+ expect(d.agentId).toBe('1')
+ expect(d.confidence).toBe(0)
+ }
+ })
+
+ it('caps an overlong reason', () => {
+ const d = parseRouteOutput(`{"agentId":"1","confidence":0.5,"reason":"${'x'.repeat(500)}","needNewAgent":false}`, AGENTS)
+ expect(d.reason.length).toBeLessThanOrEqual(120)
+ })
+})
+
+describe('buildRouterPrompt', () => {
+ it('includes the transcript, each agent name, and the recent summary (or a placeholder)', () => {
+ const p = buildRouterPrompt('sửa lỗi đăng nhập', AGENTS)
+ expect(p).toContain('sửa lỗi đăng nhập')
+ expect(p).toContain('name="Frontend"')
+ expect(p).toContain('name="Auth"')
+ expect(p).toContain('JWT refresh, login rate-limit')
+ expect(p).toContain('(no activity yet)') // DevOps has no recentSummary
+ expect(p).toMatch(/JSON/i)
+ // Must instruct the model to always pick — no "none"/decline option.
+ expect(p).toMatch(/always .*(pick|choose).*one agent|no "none"/i)
+ })
+})
+
+describe('routeVoiceTask', () => {
+ beforeEach(() => { runRouterOneShot.mockReset(); routerImpl = async () => ({ text: '', sessionId: null }) })
+
+ it('returns needNewAgent for an empty machine WITHOUT calling the LLM', async () => {
+ const d = await routeVoiceTask('anything', [])
+ expect(d.needNewAgent).toBe(true)
+ expect(runRouterOneShot).not.toHaveBeenCalled()
+ })
+
+ it('short-circuits to the only agent WITHOUT calling the LLM', async () => {
+ const d = await routeVoiceTask('anything', [{ id: '7', name: 'Solo' }])
+ expect(d).toEqual({ agentId: '7', confidence: 1, reason: 'only agent in machine', needNewAgent: false })
+ expect(runRouterOneShot).not.toHaveBeenCalled()
+ })
+
+ it('calls the LLM for >1 agent and parses its output', async () => {
+ routerImpl = async () => ({ text: '{"agentId":"2","confidence":0.88,"reason":"auth","needNewAgent":false}', sessionId: null })
+ const d = await routeVoiceTask('login broken', AGENTS)
+ expect(runRouterOneShot).toHaveBeenCalledOnce()
+ expect(d.agentId).toBe('2')
+ expect(d.confidence).toBeCloseTo(0.88)
+ })
+
+ it('still picks the closest agent (never needNewAgent) when the LLM returns garbage', async () => {
+ routerImpl = async () => ({ text: 'I cannot decide', sessionId: null })
+ const d = await routeVoiceTask('login broken', AGENTS)
+ expect(d.needNewAgent).toBe(false)
+ expect(d.agentId).toBe('1')
+ })
+
+ it('falls back to a heuristic pick (never throws) when the one-shot TIMES OUT', async () => {
+ routerImpl = async () => { throw new Error('claude one-shot timed out after 12000ms') }
+ const d = await routeVoiceTask('fix the auth login please', AGENTS)
+ expect(d.needNewAgent).toBe(false)
+ expect(d.agentId).toBe('2') // "auth"/"login" → the Auth agent by name/recent match
+ expect(d.confidence).toBeLessThanOrEqual(0.4)
+ })
+
+ it('RE-THROWS an AbortError (caller cancelled) rather than papering over it', async () => {
+ routerImpl = async () => { throw Object.assign(new Error('aborted'), { name: 'AbortError' }) }
+ await expect(routeVoiceTask('anything', AGENTS)).rejects.toThrow('aborted')
+ })
+})
+
+describe('pickAgentHeuristic', () => {
+ it('matches the agent NAME (diacritic/case-insensitive)', () => {
+ expect(pickAgentHeuristic('mở trang FRONTEND lên', AGENTS).agentId).toBe('1')
+ expect(pickAgentHeuristic('auth bị lỗi', AGENTS).agentId).toBe('2')
+ })
+
+ it('uses recent activity when the name does not appear', () => {
+ expect(pickAgentHeuristic('sửa dark mode', AGENTS).agentId).toBe('1') // recent: "dark mode + settings"
+ })
+
+ it('returns the first agent (never needNewAgent) when nothing matches', () => {
+ const d = pickAgentHeuristic('xyzzy nothing relevant', AGENTS)
+ expect(d.agentId).toBe('1')
+ expect(d.needNewAgent).toBe(false)
+ expect(d.confidence).toBeLessThanOrEqual(0.3)
+ })
+})
+
+/**
+ * Which CLI classifies the route. It used to be Claude and only Claude, so a machine without it never
+ * routed at all: the warm spawn failed on a loop and every voice fell through to name matching, whose
+ * capped confidence can never clear the backend's 0.75 auto-dispatch threshold. The live agent list is the
+ * evidence — a running agent proves its CLI exists and is logged in.
+ */
+describe('chooseRouterEngine', () => {
+ it('prefers Claude when the user actually has a Claude agent', () => {
+ expect(chooseRouterEngine([{ engine: 'codex' }, { engine: 'claude' }, { engine: 'commandcode' }])).toBe('claude')
+ })
+
+ it('picks by priority when there is no Claude agent', () => {
+ expect(chooseRouterEngine([{ engine: 'commandcode' }, { engine: 'codex' }])).toBe('codex')
+ expect(chooseRouterEngine([{ engine: 'commandcode' }])).toBe('commandcode')
+ expect(chooseRouterEngine([{ engine: 'opencode' }, { engine: 'cursor' }])).toBe('cursor')
+ })
+
+ it('returns null when nothing can serve the router', () => {
+ // Hermes and Devin take the prompt as argv, so they cannot be warmed or run as a one-shot here.
+ expect(chooseRouterEngine([{ engine: 'hermes' }, { engine: 'devin' }])).toBeNull()
+ expect(chooseRouterEngine([])).toBeNull()
+ })
+})
+
+describe('routeVoiceTask engine selection', () => {
+ beforeEach(() => { runRouterOneShot.mockReset(); routerImpl = async () => ({ text: '', sessionId: null }) })
+
+ it('classifies with the engine the agents run on', async () => {
+ routerImpl = async () => ({ text: '{"agentId":"2","confidence":0.9,"reason":"auth"}', sessionId: null })
+ const codexAgents: RouterAgent[] = [
+ { id: '1', name: 'Frontend', engine: 'codex' },
+ { id: '2', name: 'Auth', engine: 'codex' },
+ ]
+ const d = await routeVoiceTask('login broken', codexAgents)
+ expect(runRouterOneShot).toHaveBeenCalledOnce()
+ expect(runRouterOneShot.mock.calls[0][0]).toBe('codex') // NOT claude
+ expect(d.agentId).toBe('2')
+ })
+
+ it('lets a non-Claude engine use the model the user already selected', async () => {
+ // Naming a model per engine sent Codex a frontier model for a 20-word classification, and any id the
+ // user's account or CLI version rejects fails the one-shot — which drops the route back to name
+ // matching, silently. The selected model is the one model guaranteed to run.
+ expect(routerModelFor('codex')).toBe('')
+ expect(routerModelFor('commandcode')).toBe('')
+ expect(routerModelFor('cursor')).toBe('')
+ routerImpl = async () => ({ text: '{"agentId":"1","confidence":0.9,"reason":"x"}', sessionId: null })
+ await routeVoiceTask('anything', [
+ { id: '1', name: 'A', engine: 'codex' },
+ { id: '2', name: 'B', engine: 'codex' },
+ ])
+ expect((runRouterOneShot.mock.calls[0][1] as { model?: string }).model).toBe('')
+ })
+
+ it('keeps Claude on its own small model', () => {
+ // Haiku is on every Claude plan and routing has a 12s budget; Opus for a classification is waste.
+ expect(routerModelFor('claude')).toBe('haiku')
+ })
+
+ it('goes straight to the heuristic — no spawn — when no agent can serve it', async () => {
+ const argvOnly: RouterAgent[] = [
+ { id: '1', name: 'Frontend', engine: 'hermes' },
+ { id: '2', name: 'Auth', recentSummary: 'login rate-limit', engine: 'devin' },
+ ]
+ const d = await routeVoiceTask('fix the auth login please', argvOnly)
+ expect(runRouterOneShot).not.toHaveBeenCalled() // a doomed spawn on every voice is the thing to avoid
+ expect(d.agentId).toBe('2') // still a real pick, by name/recent match
+ expect(d.confidence).toBeLessThanOrEqual(0.4) // and never enough to auto-dispatch
+ })
+})
diff --git a/cli/src/lib/voiceRouter.ts b/cli/src/lib/voiceRouter.ts
new file mode 100644
index 000000000..f98c4a088
--- /dev/null
+++ b/cli/src/lib/voiceRouter.ts
@@ -0,0 +1,248 @@
+// Voice router (adapter side, for REMOTE machines) — self-contained port of the the hosted runtime's
+// Given a transcribed voice task and this machine's agents (name + a
+// short summary of each agent's recent turn), pick the single best-fit agent. Uses the same key-free CLI
+// one-shot path as the turn summarizer (runClaudeOneShot) with a small/fast model (Haiku by default). Name
+// is the strongest signal (users name agents by role/domain); recent activity disambiguates.
+import { existsSync, mkdirSync } from 'fs'
+import { join } from 'path'
+import { env } from '../config/env.js'
+import { runRouterOneShot, configureRouterOneShot, setRouterOneShotDeviceConnected, shutdownRouterOneShot } from './oneshot.js'
+
+export interface RouterAgent {
+ id: string
+ name: string
+ /** The CLI this agent runs on. It is what decides which engine classifies the route — see
+ * chooseRouterEngine — so the decision is made from the very list being routed over. */
+ engine?: string
+ /** Recaps of the agent's last few completed turns (up to 3), joined — a broader, less skewed picture
+ * of what it's working on than a single turn. */
+ recentSummary?: string
+}
+
+export interface RouteDecision {
+ agentId: string
+ confidence: number
+ reason: string
+ needNewAgent: boolean
+}
+
+const ROUTE_SCRATCH = join(env.ADAPTER_DATA_DIR, 'voice-route-scratch')
+
+/** Engines that can serve the router, best first. Hermes and Devin are absent on purpose: they take the
+ * prompt as argv so they cannot be pre-warmed — the same exclusion the recap pool makes. */
+const ROUTER_ENGINE_PRIORITY = ['claude', 'codex', 'commandcode', 'cursor', 'pi', 'opencode'] as const
+export type RouterEngine = (typeof ROUTER_ENGINE_PRIORITY)[number]
+
+/**
+ * Pick the engine to classify with, from the agents the machine is ACTUALLY running.
+ *
+ * A live agent is proof that its CLI exists and is logged in; nothing else here is. The router used to be
+ * pinned to Claude, so a machine without it never routed at all — the warm spawn failed on a loop and every
+ * voice silently fell through to name-matching, whose capped confidence can never reach the backend's
+ * auto-dispatch threshold. Claude is still preferred, but only when the user has a Claude agent.
+ *
+ * null = no agent this can run on. The caller goes straight to the heuristic instead of spending a doomed
+ * spawn out of the 12s route budget on every voice.
+ */
+export function chooseRouterEngine(sessions: Array<{ engine: string }>): RouterEngine | null {
+ const present = new Set(sessions.map((session) => session.engine))
+ return ROUTER_ENGINE_PRIORITY.find((engine) => present.has(engine)) ?? null
+}
+
+/**
+ * Which model classifies the route.
+ *
+ * Claude gets an explicit one (Haiku by default): it is the cheapest, fastest model on every Claude plan,
+ * and routing has a 12s budget for what is a 20-word classification. Set VOICE_ROUTE_MODEL='' to make it
+ * follow the selected model like the others.
+ *
+ * Every other engine gets NOTHING, which makes its CLI use the model the user already has selected. Naming
+ * a model per engine looked tidy and was wrong twice over: it pointed Codex at a frontier model (gpt-5.5)
+ * for a classification, and a model id the user's account or CLI version does not accept fails the one-shot
+ * — dropping back to name matching, silently, which is the very bug this router path exists to fix. The
+ * selected model is the one model guaranteed to run.
+ */
+export function routerModelFor(engine: RouterEngine): string {
+ return engine === 'claude' ? env.VOICE_ROUTE_MODEL : ''
+}
+
+/** The engine the pool is currently warmed for; null until the registry has been synced at least once. */
+let routerEngine: RouterEngine | null = null
+
+// With --no-session-persistence the one-shot writes nothing here; the dir just has to exist as the cwd.
+function ensureRouteScratch(): string {
+ if (!existsSync(ROUTE_SCRATCH)) mkdirSync(ROUTE_SCRATCH, { recursive: true })
+ return ROUTE_SCRATCH
+}
+
+// Point the warm router worker at the chosen engine's small model @ the route scratch. Lazy (not at import)
+// so importing this module for the pure helpers has no filesystem/pool side effects.
+function ensureRouterConfigured(engine: RouterEngine): void {
+ configureRouterOneShot({ engine, cwd: ensureRouteScratch(), model: routerModelFor(engine), effort: 'low' })
+}
+
+/**
+ * Tell the router which agents exist. Called from the same place the recap pool is synced, so the warm
+ * worker always belongs to an engine the machine really runs.
+ */
+export function setVoiceRouterSessions(sessions: Array<{ engine: string }>): void {
+ const next = chooseRouterEngine(sessions)
+ if (next === routerEngine) return
+ routerEngine = next
+ if (!next) {
+ console.log('[voice-route] no agent this router can run on — voice will route by name matching')
+ return
+ }
+ console.log(`[voice-route] router engine=${next} model=${routerModelFor(next) || '(engine default)'}`)
+ ensureRouterConfigured(next)
+}
+
+/** Warm (device connected) / unwarm the router worker — wired to commander presence in cli.ts. */
+export function setVoiceRouterDeviceConnected(connected: boolean): void {
+ // Config must be set before the pool spawns a warm worker. With no usable engine there is nothing to
+ // warm — the heuristic needs no process.
+ if (connected && routerEngine) ensureRouterConfigured(routerEngine)
+ setRouterOneShotDeviceConnected(connected)
+}
+export function shutdownVoiceRouter(): void {
+ shutdownRouterOneShot()
+}
+
+// Diacritic/case-insensitive tokens (Vietnamese-aware) for the heuristic fallback matcher.
+function routeTokens(s: string): string[] {
+ const norm = s.normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[\u0111\u0110]/g, 'd').toLowerCase()
+ return norm.split(/[^a-z0-9]+/).filter((t) => t.length >= 2)
+}
+
+// Fallback when the LLM router is unavailable (timed out / spawn failed): score each agent by how many
+// transcript words appear in its NAME (strong signal) and recent activity (weak), and pick the best. Always
+// returns a concrete in-machine agent with a low, capped confidence — the voice still dispatches, never errors.
+export function pickAgentHeuristic(transcript: string, agents: RouterAgent[]): RouteDecision {
+ const words = new Set(routeTokens(transcript))
+ let best = agents[0]
+ let bestScore = -1
+ for (const a of agents) {
+ const nameHits = routeTokens(a.name).filter((t) => words.has(t)).length
+ const recentHits = routeTokens(a.recentSummary ?? '').filter((t) => words.has(t)).length
+ const score = nameHits * 3 + recentHits
+ if (score > bestScore) { bestScore = score; best = a }
+ }
+ const matched = bestScore > 0
+ return {
+ agentId: best?.id ?? agents[0]?.id ?? '',
+ confidence: matched ? 0.4 : 0.2,
+ reason: matched ? 'heuristic name/recent match' : 'closest agent (router unavailable)',
+ needNewAgent: false,
+ }
+}
+
+/** One line of the voice task, bounded — the adapter log already carries injected messages this way. */
+function taskPreview(text: string): string {
+ const flat = text.replace(/\s+/g, ' ').trim()
+ return flat.length > 80 ? `${flat.slice(0, 79)}…` : flat
+}
+
+/** Name the winner. Without this the log said an engine ran and never which agent it picked, so a wrong
+ * route looked identical to a right one. `via` separates a real classification from a fallback. */
+function logDecision(via: string, agents: RouterAgent[], decision: RouteDecision): RouteDecision {
+ const chosen = agents.find((agent) => agent.id === decision.agentId)
+ console.log(
+ `[voice-route] → picked "${chosen?.name ?? '(unknown)'}" id=${decision.agentId || '(none)'}` +
+ ` · confidence=${decision.confidence.toFixed(2)} · via=${via}` +
+ `${decision.reason ? ` · "${decision.reason}"` : ''}`,
+ )
+ return decision
+}
+
+export function buildRouterPrompt(transcript: string, agents: RouterAgent[]): string {
+ const lines = agents
+ .map((a) => `- id=${a.id} | name="${a.name}" | recent: ${a.recentSummary?.trim() || '(no activity yet)'}`)
+ .join('\n')
+ return (
+ `You are a ROUTER. Assign ONE incoming voice task to the single best-fit agent from the fixed list ` +
+ `below. You MUST always choose exactly one agent from the list — there is NO "none" option and you may ` +
+ `NOT decline. The agent NAME is a strong signal — the user names agents by role/domain ("Frontend", ` +
+ `"Auth", "DevOps"). Each agent's RECENT activity disambiguates when names alone are ambiguous. If nothing ` +
+ `matches well, still pick the CLOSEST agent and give it a low confidence.\n\n` +
+ `Voice task (verbatim; may be Vietnamese — do NOT translate it): "${transcript}"\n\n` +
+ `Agents:\n${lines}\n\n` +
+ `Always pick exactly one agent id from the list above. Set confidence 0..1 for how good the fit is:\n` +
+ `- 0.85+ when the name and/or recent activity clearly match\n` +
+ `- ~0.6 when it's a reasonable but not certain match\n` +
+ `- ~0.3 when nothing fits well but this is the closest agent.\n\n` +
+ `Respond with ONLY a single JSON object, no prose, no markdown fence:\n` +
+ `{"agentId":"<one id from the list>","confidence":<0..1>,"reason":"<max 12 words>"}`
+ )
+}
+
+// Defensive parse: Haiku is told to emit bare JSON, but tolerate a stray code fence or surrounding prose by
+// extracting the first {...} block. Validates the id against the machine and clamps confidence.
+export function parseRouteOutput(raw: string, agents: RouterAgent[]): RouteDecision {
+ const ids = new Set(agents.map((a) => a.id))
+ // The router ALWAYS picks — there is no "no agent" outcome. If the model misbehaves (bad JSON, empty or
+ // unknown id) we still resolve to the closest available agent (the first in the list) with a low, capped
+ // confidence, so the backend always has a concrete agent to dispatch to. `needNewAgent` is retired
+ // (always false); the field is kept only for wire-contract compatibility with the device/backend.
+ const fallbackId = agents[0]?.id ?? ''
+ const fallback: RouteDecision = { agentId: fallbackId, confidence: 0, reason: 'closest agent (parse failed)', needNewAgent: false }
+ const start = raw.indexOf('{')
+ const end = raw.lastIndexOf('}')
+ if (start < 0 || end <= start) return fallback
+ let obj: Record<string, unknown>
+ try {
+ obj = JSON.parse(raw.slice(start, end + 1))
+ } catch {
+ return fallback
+ }
+ const agentId = typeof obj.agentId === 'string' ? obj.agentId : ''
+ let confidence = typeof obj.confidence === 'number' ? obj.confidence : Number(obj.confidence)
+ if (!Number.isFinite(confidence)) confidence = 0
+ confidence = Math.max(0, Math.min(1, confidence))
+ const reason = typeof obj.reason === 'string' ? obj.reason.slice(0, 120) : ''
+ // An empty or unknown id ⇒ fall back to the closest (first) agent with capped confidence; a valid
+ // in-machine pick wins as-is. Either way we return a real agent and needNewAgent:false.
+ if (!agentId || !ids.has(agentId)) return { agentId: fallbackId, confidence: Math.min(confidence, 0.3), reason: reason || 'closest agent', needNewAgent: false }
+ return { agentId, confidence, reason, needNewAgent: false }
+}
+
+// Route a transcript to an agent. Skips the LLM for the trivial cases (0 / 1 agent).
+export async function routeVoiceTask(transcript: string, agents: RouterAgent[], signal?: AbortSignal): Promise<RouteDecision> {
+ // What the backend handed down, and what it may choose between. Logged before anything can fail, so a
+ // route that times out still shows the task and the candidates it was weighing.
+ console.log(
+ `[voice-route] task "${taskPreview(transcript)}" · candidates=${agents.length}` +
+ `${agents.length ? ` [${agents.map((agent) => `${agent.name}/${agent.engine ?? '?'}`).join(', ')}]` : ''}`,
+ )
+ if (agents.length === 0) {
+ return logDecision('empty-machine', agents, { agentId: '', confidence: 0, reason: 'no agents in machine', needNewAgent: true })
+ }
+ if (agents.length === 1) {
+ return logDecision('only-agent', agents, { agentId: agents[0].id, confidence: 1, reason: 'only agent in machine', needNewAgent: false })
+ }
+
+ // Decide from the agents in hand, falling back to whatever the registry sync last warmed (a caller that
+ // does not label its agents). No usable engine → the heuristic, without burning a doomed spawn on every
+ // voice.
+ const engine = chooseRouterEngine(agents.filter((agent) => agent.engine).map((agent) => ({ engine: agent.engine as string }))) ?? routerEngine
+ if (!engine) {
+ console.log('[voice-route] no agent this router can run on → name matching')
+ return logDecision('heuristic (no engine)', agents, pickAgentHeuristic(transcript, agents))
+ }
+ const model = routerModelFor(engine)
+ const prompt = buildRouterPrompt(transcript, agents)
+ ensureRouterConfigured(engine) // so runRouterOneShot matches the pool config and uses the warm worker
+ // BEFORE the call: on a timeout this is the only record of which CLI was asked.
+ console.log(`[voice-route] classifying with ${engine} · model=${model || '(engine default)'}`)
+ try {
+ // Served from the warm router worker (no cold spawn). Cap under the backend's 15s nodeRequest budget so
+ // a slow route surfaces before the RPC deadline.
+ const { text } = await runRouterOneShot(engine, { prompt, model, effort: 'low', cwd: ensureRouteScratch(), signal, timeoutMs: 12_000 })
+ return logDecision(engine, agents, parseRouteOutput(text || '', agents))
+ } catch (err) {
+ if (err instanceof Error && err.name === 'AbortError') throw err // caller cancelled — don't paper over it
+ // The classifier timed out / spawn failed → NEVER fail the RPC. Fall back to a heuristic pick so the
+ // voice still dispatches to a plausible agent instead of erroring out on the device.
+ console.log(`[voice-route] ${engine} one-shot failed (${err instanceof Error ? err.message : String(err)}) → name matching`)
+ return logDecision(`heuristic (${engine} failed)`, agents, pickAgentHeuristic(transcript, agents))
+ }
+}
diff --git a/cli/src/version.ts b/cli/src/version.ts
new file mode 100644
index 000000000..8d83d9300
--- /dev/null
+++ b/cli/src/version.ts
@@ -0,0 +1,24 @@
+/**
+ * The adapter's own version, the single runtime source of truth for the self-updater's compare.
+ *
+ * `__ADAPTER_VERSION__` is injected at build time via esbuild `define` (both the bundle build
+ * `build-bundle.mjs` and the per-file `build.mjs`), sourced from `package.json` (or the release
+ * script's `ADAPTER_VERSION`). Under `tsx` dev there is no define, so we fall back to reading
+ * `package.json` at runtime — `npm run dev` still reports the real version, not a sentinel.
+ */
+import { readFileSync } from 'node:fs'
+
+declare const __ADAPTER_VERSION__: string | undefined
+
+function resolveVersion(): string {
+ if (typeof __ADAPTER_VERSION__ !== 'undefined') return __ADAPTER_VERSION__
+ try {
+ // src/version.ts (or dist/version.js) → ../package.json = package.json.
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version?: string }
+ return pkg.version ?? '0.0.0-dev'
+ } catch {
+ return '0.0.0-dev'
+ }
+}
+
+export const VERSION: string = resolveVersion()
diff --git a/cli/src/watcher/watcher.spec.ts b/cli/src/watcher/watcher.spec.ts
new file mode 100644
index 000000000..f646ec0c8
--- /dev/null
+++ b/cli/src/watcher/watcher.spec.ts
@@ -0,0 +1,71 @@
+import { appendFile, mkdtemp, rm, writeFile } from 'fs/promises'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { Watcher, type LineEvent } from './watcher.js'
+
+const cleanup: string[] = []
+
+afterEach(async () => {
+ await Promise.all(cleanup.splice(0).map((path) => rm(path, { recursive: true, force: true })))
+})
+
+describe('Watcher.pollAll', () => {
+ it('drains every registered transcript to EOF without waiting for chokidar', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'machine-watcher-'))
+ cleanup.push(dir)
+ const transcriptPath = join(dir, 'session.jsonl')
+ await writeFile(transcriptPath, '{"n":1}\n')
+ const watcher = new Watcher()
+ const lines: string[] = []
+ watcher.on('line', (event: LineEvent) => lines.push(event.text))
+ await watcher.addSession({ sessionId: 's1', engine: 'codex', transcriptPath })
+ await appendFile(transcriptPath, '{"n":2}\n{"n":3}\n')
+
+ await watcher.pollAll()
+
+ expect(lines).toEqual(['{"n":2}', '{"n":3}'])
+ await watcher.stop()
+ })
+
+ it('replays only the changed Cursor suffix when a trailing turn sentinel is replaced', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'machine-cursor-watcher-'))
+ cleanup.push(dir)
+ const transcriptPath = join(dir, 'session.jsonl')
+ const user = '{"role":"user","message":{"content":[{"type":"text","text":"hi"}]}}'
+ const assistant = '{"role":"assistant","message":{"content":[{"type":"text","text":"hello"}]}}'
+ const ended = '{"type":"turn_ended","status":"completed"}'
+ await writeFile(transcriptPath, `${user}\n${ended}\n`)
+ const watcher = new Watcher()
+ const lines: string[] = []
+ watcher.on('line', (event: LineEvent) => lines.push(event.text))
+ await watcher.addSession({ sessionId: 's1', engine: 'cursor', transcriptPath })
+
+ await writeFile(transcriptPath, `${user}\n${assistant}\n`)
+ await watcher.pollSession('s1')
+ await appendFile(transcriptPath, `${ended}\n`)
+ await watcher.pollSession('s1')
+
+ expect(lines).toEqual([assistant, ended])
+ await watcher.stop()
+ })
+
+ it('can emit an existing Cursor transcript from the start for first-turn discovery', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'machine-cursor-first-turn-'))
+ cleanup.push(dir)
+ const transcriptPath = join(dir, 'session.jsonl')
+ await writeFile(transcriptPath, '{"n":1}\n{"n":2}\n')
+ const watcher = new Watcher()
+ const lines: string[] = []
+ watcher.on('line', (event: LineEvent) => lines.push(event.text))
+
+ await watcher.addSession(
+ { sessionId: 's1', engine: 'cursor', transcriptPath },
+ { fromStart: true },
+ )
+ await watcher.pollSession('s1')
+
+ expect(lines).toEqual(['{"n":1}', '{"n":2}'])
+ await watcher.stop()
+ })
+})
diff --git a/cli/src/watcher/watcher.ts b/cli/src/watcher/watcher.ts
new file mode 100644
index 000000000..be4e60ccf
--- /dev/null
+++ b/cli/src/watcher/watcher.ts
@@ -0,0 +1,238 @@
+/** Registration-driven JSONL tailer. It watches only transcript files already admitted by the
+ * tmux-backed registry, so inactive Claude/Codex history is never discovered or exposed. */
+
+import { EventEmitter } from 'events'
+import chokidar, { type FSWatcher } from 'chokidar'
+import { open, readFile, stat } from 'fs/promises'
+import { basename, dirname } from 'path'
+import type { AgentEngine } from '../engines/types.js'
+
+export interface WatchedSession {
+ sessionId: string
+ engine: AgentEngine
+ transcriptPath: string
+}
+
+export interface LineEvent {
+ sessionId: string
+ engine: AgentEngine
+ projectDir: string
+ text: string
+ seq: number
+ ts: number
+}
+
+interface FileState extends WatchedSession {
+ offset: number
+ partial: string
+ seq: number
+ debounce: NodeJS.Timeout | null
+ reading: boolean
+ pending: boolean
+ cursorLines: string[]
+}
+
+const DEBOUNCE_MS = 40
+
+export class Watcher extends EventEmitter {
+ private watcher: FSWatcher | null = null
+ private files = new Map<string, FileState>()
+ private bySession = new Map<string, string>()
+
+ start(): void {
+ if (this.watcher) return
+ this.watcher = chokidar.watch([], { ignoreInitial: false, alwaysStat: true })
+ this.watcher
+ .on('add', (filePath: string) => this.schedule(filePath))
+ .on('change', (filePath: string) => { this.noteChange(filePath); this.schedule(filePath) })
+ .on('unlink', (filePath: string) => {
+ const state = this.files.get(filePath)
+ if (state) state.pending = true // keep registration; a rotate/recreate may follow
+ })
+ .on('error', (err: unknown) => console.error('[watcher] error:', err))
+ if (this.files.size) this.watcher.add([...this.files.keys()])
+ }
+
+ /** Attach one trusted transcript. Runtime hydration is handled by cli.ts; the tail starts at EOF. */
+ async addSession(session: WatchedSession, opts: { fromStart?: boolean } = {}): Promise<void> {
+ const oldPath = this.bySession.get(session.sessionId)
+ if (oldPath && oldPath !== session.transcriptPath) await this.removeSession(session.sessionId)
+
+ let offset = 0
+ let cursorLines: string[] = []
+ if (!opts.fromStart) {
+ try { offset = (await stat(session.transcriptPath)).size } catch { offset = 0 }
+ if (session.engine === 'cursor') {
+ try { cursorLines = completeLines(await readFile(session.transcriptPath, 'utf8')) } catch { cursorLines = [] }
+ }
+ }
+ const existing = this.files.get(session.transcriptPath)
+ if (existing) {
+ existing.engine = session.engine
+ existing.sessionId = session.sessionId
+ this.bySession.set(session.sessionId, session.transcriptPath)
+ return
+ }
+ // Two rounds of "the CLI accepted it but the adapter never saw the line" were spent guessing whether
+ // this registration had happened at all. Say it once per file, with the offset it starts from.
+ console.log(`[watcher] tail ${session.engine} ${session.sessionId.slice(0, 8)} @${offset} · ${session.transcriptPath}`)
+ this.files.set(session.transcriptPath, {
+ ...session,
+ offset,
+ partial: '',
+ seq: 0,
+ debounce: null,
+ reading: false,
+ pending: false,
+ cursorLines,
+ })
+ this.bySession.set(session.sessionId, session.transcriptPath)
+ this.watcher?.add(session.transcriptPath)
+ if (opts.fromStart) this.schedule(session.transcriptPath)
+ }
+
+ async removeSession(sessionId: string): Promise<void> {
+ const filePath = this.bySession.get(sessionId)
+ if (!filePath) return
+ this.bySession.delete(sessionId)
+ const state = this.files.get(filePath)
+ if (state?.debounce) clearTimeout(state.debounce)
+ this.files.delete(filePath)
+ await this.watcher?.unwatch(filePath)
+ }
+
+ async stop(): Promise<void> {
+ for (const state of this.files.values()) if (state.debounce) clearTimeout(state.debounce)
+ this.files.clear()
+ this.bySession.clear()
+ if (this.watcher) await this.watcher.close()
+ this.watcher = null
+ }
+
+ /** Re-read every registered file to EOF. Used by the low-frequency full reconciliation pass. */
+ async pollAll(): Promise<void> {
+ await Promise.all([...this.files.keys()].map(async (filePath) => {
+ await this.readNew(filePath)
+ // A chokidar read may already own this file. readNew() marks it pending in that case;
+ // wait for the owner to finish its pending pass so reconciliation really reaches EOF.
+ while (this.files.get(filePath)?.reading) {
+ await new Promise((resolve) => setTimeout(resolve, 10))
+ }
+ }))
+ }
+
+ async pollSession(sessionId: string): Promise<void> {
+ const filePath = this.bySession.get(sessionId)
+ if (!filePath) return
+ await this.readNew(filePath)
+ while (this.files.get(filePath)?.reading) await new Promise((resolve) => setTimeout(resolve, 10))
+ }
+
+ /** Chokidar told us the file moved. Logged for commandcode/devin only, whose whole turn lifecycle rides
+ * on these reads — for claude the hooks say the same thing and this would just be noise. */
+ private noteChange(filePath: string): void {
+ const state = this.files.get(filePath)
+ if (state && (state.engine === 'commandcode' || state.engine === 'devin')) {
+ console.log(`[watcher] change ${state.engine} ${state.sessionId.slice(0, 8)} @${state.offset}`)
+ }
+ }
+
+ private schedule(filePath: string): void {
+ const state = this.files.get(filePath)
+ if (!state) return
+ if (state.debounce) clearTimeout(state.debounce)
+ state.debounce = setTimeout(() => {
+ state.debounce = null
+ void this.readNew(filePath)
+ }, DEBOUNCE_MS)
+ }
+
+ private async readNew(filePath: string): Promise<void> {
+ const state = this.files.get(filePath)
+ if (!state) return
+ if (state.reading) { state.pending = true; return }
+ state.reading = true
+ try {
+ do {
+ state.pending = false
+ await this.readOnce(filePath, state)
+ } while (state.pending && this.files.get(filePath) === state)
+ } finally {
+ state.reading = false
+ }
+ }
+
+ private async readOnce(filePath: string, state: FileState): Promise<void> {
+ if (state.engine === 'cursor') {
+ await this.readCursor(filePath, state)
+ return
+ }
+ let size: number
+ try { size = (await stat(filePath)).size } catch { return }
+ if (size < state.offset) {
+ state.offset = 0
+ state.partial = ''
+ }
+ if (size <= state.offset) return
+
+ const start = state.offset
+ let chunk = ''
+ try {
+ const fh = await open(filePath, 'r')
+ try {
+ const buf = Buffer.alloc(size - start)
+ const { bytesRead } = await fh.read(buf, 0, buf.length, start)
+ chunk = buf.subarray(0, bytesRead).toString('utf8')
+ state.offset = start + bytesRead
+ } finally {
+ await fh.close()
+ }
+ } catch (err) {
+ console.error(`[watcher] read failed (${basename(filePath)}):`, err)
+ return
+ }
+
+ const combined = state.partial + chunk
+ const lines = combined.split('\n')
+ state.partial = combined.endsWith('\n') ? '' : (lines.pop() ?? '')
+ for (const raw of lines) {
+ const text = raw.replace(/\r$/, '')
+ if (!text.trim()) continue
+ this.emit('line', {
+ sessionId: state.sessionId,
+ engine: state.engine,
+ projectDir: basename(dirname(filePath)),
+ text,
+ seq: state.seq++,
+ ts: Date.now(),
+ } satisfies LineEvent)
+ }
+ }
+
+ private async readCursor(filePath: string, state: FileState): Promise<void> {
+ let next: string[]
+ try { next = completeLines(await readFile(filePath, 'utf8')) } catch { return }
+ let common = 0
+ while (common < state.cursorLines.length && common < next.length && state.cursorLines[common] === next[common]) common++
+ state.cursorLines = next
+ state.offset = 0
+ state.partial = ''
+ for (const text of next.slice(common)) {
+ if (!text.trim()) continue
+ this.emit('line', {
+ sessionId: state.sessionId,
+ engine: state.engine,
+ projectDir: basename(dirname(filePath)),
+ text,
+ seq: state.seq++,
+ ts: Date.now(),
+ } satisfies LineEvent)
+ }
+ }
+}
+
+function completeLines(content: string): string[] {
+ const lines = content.split('\n')
+ if (!content.endsWith('\n')) lines.pop()
+ return lines.map((line) => line.replace(/\r$/, '')).filter((line) => line.trim())
+}
diff --git a/cli/src/webui.ts b/cli/src/webui.ts
new file mode 100644
index 000000000..7827735e7
--- /dev/null
+++ b/cli/src/webui.ts
@@ -0,0 +1,334 @@
+/**
+ * Self-contained local dashboard for the machine-adapter, served by the hook server on
+ * 127.0.0.1:<port>. Vanilla HTML/CSS/JS (no framework, no build) — polls GET /api/status and drives
+ * the loopback management API (approve pairing, unpair, stop). Scoped to LOCAL-only concerns (adapter
+ * health, machine fingerprint, local pairings); it never renders chat/transcripts — that's the cloud
+ * web (WEB_URL/machine/<agentId>).
+ *
+ * CSRF: mutating calls send the `x-adapter-local: 1` header, which a cross-origin page cannot set on a
+ * simple request (a custom header forces a CORS preflight the server never allows) — so only this
+ * same-origin page (and the CLI) can trigger actions.
+ */
+export const LOCAL_WEB_HTML = /* html */ `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<title>harness</title>
+<style>
+ :root { color-scheme: dark; --bg:#0e1116; --card:#161b22; --line:#232a34; --fg:#e6edf3; --mut:#8b949e; --faint:#6e7681; --grn:#3fb950; --red:#e5534b; --yel:#d29922; --acc:#4c8bf5; --mono: ui-monospace, SFMono-Regular, Menlo, monospace; }
+ * { box-sizing: border-box; }
+ body { margin:0; background:var(--bg); color:var(--fg); font:14px/1.5 -apple-system, system-ui, sans-serif; }
+ a { color:var(--acc); text-decoration:none; } a:hover { text-decoration:underline; }
+ .wrap { max-width:960px; margin:0 auto; padding:20px 16px 48px; }
+ .bar { display:flex; flex-wrap:wrap; align-items:center; gap:8px 16px; background:var(--card); border:1px solid var(--line); border-radius:12px; padding:14px 16px; }
+ .brand { font-weight:600; }
+ .dot { width:9px; height:9px; border-radius:50%; display:inline-block; vertical-align:middle; }
+ .on { background:var(--grn); } .off { background:var(--red); } .idle { background:var(--faint); }
+ .mut { color:var(--mut); } .mono { font-family:var(--mono); }
+ .fp { font-family:var(--mono); letter-spacing:.04em; }
+ .pill { display:inline-block; border:1px solid var(--line); border-radius:999px; padding:1px 7px; font-size:11px; color:var(--mut); margin-right:6px; text-transform:uppercase; }
+ .spacer { flex:1; }
+ .btn { background:none; border:1px solid var(--line); color:var(--fg); border-radius:8px; padding:5px 12px; font-size:12.5px; cursor:pointer; }
+ .btn:hover { border-color:var(--acc); }
+ .btn.danger:hover { border-color:var(--red); color:var(--red); }
+ .btn.primary { background:var(--acc); border-color:var(--acc); color:#fff; font-weight:600; }
+ .btn.primary:hover { filter:brightness(1.08); }
+ .btn:disabled { opacity:.6; cursor:default; }
+ /* approve modal */
+ .modal { position:fixed; inset:0; background:rgba(0,0,0,.55); display:flex; align-items:center; justify-content:center; z-index:50; padding:16px; }
+ .modalCard { background:var(--card); border:1px solid var(--line); border-radius:14px; padding:22px 22px 18px; max-width:440px; width:100%; box-shadow:0 12px 40px rgba(0,0,0,.5); }
+ .mTitle { font-size:17px; font-weight:600; }
+ .mSub { color:var(--mut); font-size:13px; margin-top:8px; line-height:1.5; }
+ .mCodeLabel { font-size:11px; letter-spacing:.06em; text-transform:uppercase; color:var(--faint); margin-top:16px; }
+ .mCode { font-family:var(--mono); font-size:30px; letter-spacing:.22em; font-weight:700; margin-top:4px; }
+ .mNote { font-size:12px; color:var(--mut); margin-top:6px; }
+ .mInput { font-family:var(--mono); background:var(--bg); border:1px solid var(--line); color:var(--fg); border-radius:8px; padding:8px 12px; letter-spacing:.2em; text-transform:uppercase; width:150px; margin-top:6px; }
+ .mFp { font-size:12px; color:var(--mut); margin-top:16px; }
+ .mBtns { display:flex; justify-content:flex-end; gap:10px; margin-top:20px; }
+ .grid { display:grid; grid-template-columns:1fr 1fr; gap:16px; margin-top:16px; }
+ @media (max-width:720px){ .grid { grid-template-columns:1fr; } }
+ .card { background:var(--card); border:1px solid var(--line); border-radius:12px; padding:14px 16px; }
+ .card h2 { margin:0 0 10px; font-size:13px; font-weight:600; color:var(--mut); text-transform:uppercase; letter-spacing:.05em; }
+ .row { display:flex; align-items:center; gap:10px; padding:8px 0; border-top:1px solid var(--line); }
+ .row:first-of-type { border-top:0; }
+ .row .main { flex:1; min-width:0; }
+ .row .name { font-weight:500; }
+ .row .sub { color:var(--faint); font-size:12px; font-family:var(--mono); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
+ .empty { color:var(--faint); padding:8px 0; }
+ .pending { margin-top:16px; background:#20160a; border:1px solid #4a3a12; border-radius:12px; padding:14px 16px; }
+ .pending input { font-family:var(--mono); background:var(--bg); border:1px solid var(--line); color:var(--fg); border-radius:8px; padding:6px 10px; letter-spacing:.2em; text-transform:uppercase; width:120px; }
+ .about { margin-top:16px; }
+ .statusGrid { display:grid; grid-template-columns:1fr 1fr; gap:8px 18px; }
+ @media (max-width:520px){ .statusGrid { grid-template-columns:1fr; } }
+ .metric { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:7px 0; border-top:1px solid var(--line); }
+ .metric:first-child, .metric:nth-child(2) { border-top:0; }
+ @media (max-width:520px){ .metric:nth-child(2) { border-top:1px solid var(--line); } }
+ .metric .k { color:var(--mut); }
+ .metric .v { font-weight:600; white-space:nowrap; }
+ .actions { display:flex; flex-wrap:wrap; gap:8px; margin-top:12px; }
+ .adv { margin-top:12px; border-top:1px solid var(--line); padding-top:10px; }
+ .adv summary { cursor:pointer; color:var(--mut); font-size:12.5px; }
+ .adv .kv { display:flex; gap:8px; padding:3px 0; font-size:12.5px; }
+ .adv .k { color:var(--faint); width:110px; flex:none; }
+ .adv .v { font-family:var(--mono); overflow:hidden; text-overflow:ellipsis; }
+ .toast { position:fixed; bottom:16px; left:50%; transform:translateX(-50%); background:var(--card); border:1px solid var(--line); border-radius:10px; padding:10px 16px; opacity:0; transition:opacity .2s; }
+ .toast.show { opacity:1; }
+ pre.logs { max-height:220px; overflow:auto; background:var(--bg); border:1px solid var(--line); border-radius:8px; padding:10px; font-size:11.5px; color:var(--mut); margin:0; }
+</style>
+</head>
+<body>
+<div class="wrap">
+ <div class="bar">
+ <span class="brand">harness</span>
+ <span id="conn"><span class="dot idle"></span> <span class="mut">connecting…</span></span>
+ <span id="device"><span class="dot idle"></span> <span class="mut">device —</span></span>
+ <span class="mut">machine <span id="agent" class="mono">—</span></span>
+ <span class="mut" id="agents">no agents</span>
+ <span class="mut">up <span id="uptime">—</span></span>
+ <span class="spacer"></span>
+ <button class="btn danger" onclick="stopAdapter()">Stop</button>
+ </div>
+ <div class="bar" style="margin-top:10px;">
+ <span class="mut">machine fingerprint</span> <span id="fp" class="fp">—</span>
+ <span class="spacer"></span>
+ <a id="weblink" href="#" target="_blank" rel="noreferrer">open in web ↗</a>
+ </div>
+
+ <div id="pending"></div>
+
+ <div class="grid">
+ <div class="card">
+ <h2>Sessions (tmux claude)</h2>
+ <div id="sessions"><div class="empty">loading…</div></div>
+ </div>
+ <div class="card">
+ <h2>Paired browsers <button class="btn danger" style="float:right;font-size:11px;padding:2px 8px" onclick="unpairAll()">Unpair all</button></h2>
+ <div id="pairs"><div class="empty">loading…</div></div>
+ </div>
+ </div>
+
+ <div class="card about">
+ <h2>Machine</h2>
+ <div id="about"></div>
+ <details id="logsBox" style="margin-top:10px"><summary class="mut" style="cursor:pointer">Logs</summary>
+ <pre class="logs" id="logs">—</pre>
+ </details>
+ </div>
+</div>
+<div class="toast" id="toast"></div>
+
+<script>
+const H = { 'x-adapter-local': '1' };
+let pendKey = null; // identity of the pending shown — so polling doesn't clobber the modal/input
+let dismissedKey = null; // pending fully handled (approved) — don't rebuild until it changes
+let modalClosed = false; // user hit Close on the approve modal → behave like no ?code (normal UI) this session
+let lastStatus = null; // last /api/status snapshot (for closeModal to re-render inline immediately)
+// Code from the "Open dashboard & approve" link on the web (?code=…). It travels via the URL the user
+// clicks in their own browser (loopback), never through the backend — so CPace security is preserved.
+const params = new URLSearchParams(location.search);
+const urlCode = (params.get('code') || '').toUpperCase();
+const setupMode = params.get('setup') === 'browser';
+let setupModalOpen = false;
+let setupInFlight = false;
+let setupAutoAttempted = false;
+function esc(s){ return String(s==null?'':s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); }
+function toast(m){ const t=document.getElementById('toast'); t.textContent=m; t.classList.add('show'); clearTimeout(t._h); t._h=setTimeout(()=>t.classList.remove('show'),1800); }
+function fmtDur(s){ s=Math.max(0,s|0); const d=s/86400|0,h=s%86400/3600|0,m=s%3600/60|0; return d?d+'d '+h+'h':h?h+'h '+m+'m':m?m+'m':s+'s'; }
+function fmtWhen(ts){ try{ return new Date(ts).toISOString().slice(0,16).replace('T',' ') }catch{ return '' } }
+
+async function post(path, body){
+ const r = await fetch(path, { method:'POST', headers:{...H, ...(body?{'content-type':'application/json'}:{})}, body: body?JSON.stringify(body):undefined });
+ const j = await r.json().catch(()=>({})); return { ok:r.ok, status:r.status, j };
+}
+// Strip ?code=… from the address bar (no reload) once the pairing is handled — so a refresh doesn't
+// re-open the modal with a stale/consumed code, and the code doesn't linger in history.
+function clearUrlCode(){ try { history.replaceState(null, '', location.pathname); } catch(e) {} }
+function clearSetupUrl(){ try { history.replaceState(null, '', location.pathname); } catch(e) {} }
+
+function showBrowserSetup(html){
+ document.getElementById('pending').innerHTML = '<div class="pending">'+html+'</div>';
+}
+function buildSetupApproveModal(s){
+ const machineUrl = s && s.webUrl && s.agentId ? (s.webUrl.replace(/\\/$/,'')+'/machine/'+s.agentId) : 'Machine';
+ document.getElementById('pending').innerHTML =
+ '<div class="modal"><div class="modalCard">'
+ + '<div class="mTitle">Set up browser encryption?</div>'
+ + '<div class="mSub">This will create a 7-day setup link for the Machine browser you just opened. Approve only if you started this flow.</div>'
+ + '<div class="mCodeLabel">machine</div><div class="mFp"><span class="fp">'+esc((s&&s.fingerprint)||'—')+'</span></div>'
+ + '<div class="mCodeLabel">destination</div><div class="mFp">'+esc(machineUrl)+'</div>'
+ + '<div class="mBtns"><button class="btn" onclick="closeSetupModal()">Cancel</button><button id="setupApproveBtn" class="btn primary" onclick="approveBrowserSetup()">Approve</button></div>'
+ + '</div></div>';
+}
+function startBrowserSetup(){
+ if (setupInFlight) return;
+ setupModalOpen = true;
+ buildSetupApproveModal(lastStatus || {});
+}
+function closeSetupModal(){
+ setupModalOpen = false;
+ if (setupMode) {
+ history.back();
+ setTimeout(() => {
+ clearSetupUrl();
+ document.getElementById('pending').innerHTML = '';
+ if (lastStatus) render(lastStatus);
+ }, 250);
+ return;
+ }
+ clearSetupUrl();
+ document.getElementById('pending').innerHTML = '';
+ if (lastStatus) render(lastStatus);
+}
+async function approveBrowserSetup(){
+ if (setupInFlight) return;
+ setupInFlight = true;
+ setupModalOpen = false;
+ const btn = document.getElementById('setupApproveBtn');
+ if (btn) { btn.disabled = true; btn.textContent = 'Approving…'; }
+ showBrowserSetup('<b>Generating browser setup link…</b><div class="mut" style="margin-top:6px">You will be returned to Machine automatically.</div>');
+ const { ok, j } = await post('/api/e2ee/setup-link');
+ if (ok && typeof j.url === 'string' && j.url) {
+ location.replace(j.url);
+ return;
+ }
+ setupInFlight = false;
+ clearSetupUrl();
+ showBrowserSetup(
+ '<b>Could not generate setup link</b>'
+ + '<div class="mut" style="margin-top:6px">'+esc(j.error || 'Try running harness browser-link in the terminal.')+'</div>'
+ + '<div style="margin-top:10px"><button class="btn" onclick="startBrowserSetup()">Try again</button></div>'
+ );
+}
+
+async function doApprove(){
+ const el = document.getElementById('code');
+ const code = (urlCode || (el ? el.value.trim().toUpperCase() : '')).trim();
+ if(!code){ toast('Enter the pairing code'); return; }
+ clearUrlCode();
+ const btn = document.getElementById('approveBtn'); if(btn){ btn.disabled = true; btn.textContent = 'Approving…'; }
+ const { ok, j } = await post('/api/pair', { code });
+ if (ok){ toast('✓ Paired '+(j.fingerprint||'')); dismissedKey = pendKey; document.getElementById('pending').innerHTML = ''; }
+ else { toast('✗ '+(j.error||'failed')); if(btn){ btn.disabled = false; btn.textContent = 'Approve'; } }
+ refresh();
+}
+// Close = don't approve now → drop back to the normal page (same as opening without ?code): show the
+// subtle inline banner instead of the blocking modal, for the rest of this session.
+function closeModal(){ modalClosed = true; clearUrlCode(); pendKey = null; if (lastStatus) render(lastStatus); else document.getElementById('pending').innerHTML = ''; }
+function pendingRoleLabel(s){ return s && s.pending && s.pending.role === 'device' ? 'device' : 'browser'; }
+// Inline (non-blocking) banner when the dashboard is opened directly and a client happens to be waiting.
+function buildInlinePending(s){
+ const role = pendingRoleLabel(s);
+ document.getElementById('pending').innerHTML =
+ '<div class="pending"><b>🔒 A '+esc(role)+' is waiting to pair</b> — <span class="mut">'+esc(s.pending.label)+'</span>'
+ + '<div style="margin-top:8px">Enter the code shown on that '+esc(role)+': '
+ + '<input id="code" maxlength="8" placeholder="ABC123" onkeydown="if(event.key===\\'Enter\\')doApprove()"> '
+ + '<button class="btn" onclick="doApprove()">Approve</button></div></div>';
+}
+function buildApproveModal(s){
+ const p = s.pending;
+ const role = pendingRoleLabel(s);
+ const codeBlock = urlCode
+ ? '<div class="mCodeLabel">verification code</div><div class="mCode">'+esc(urlCode)+'</div><div class="mNote">Make sure this matches the code on your '+esc(role)+' screen.</div>'
+ : '<div class="mCodeLabel">enter the code shown on your '+esc(role)+'</div><input id="code" class="mInput" maxlength="8" placeholder="ABC123" onkeydown="if(event.key===\\'Enter\\')doApprove()">';
+ document.getElementById('pending').innerHTML =
+ '<div class="modal"><div class="modalCard">'
+ + '<div class="mTitle">🔒 Approve this '+esc(role)+'?</div>'
+ + '<div class="mSub">A '+esc(role)+' (<b>'+esc(p.label)+'</b>) is asking to pair for end-to-end encryption. Approve only if you started this flow.</div>'
+ + codeBlock
+ + '<div class="mFp">this computer · <span class="fp">'+esc(s.fingerprint||'')+'</span></div>'
+ + '<div class="mBtns"><button class="btn" onclick="closeModal()">Close</button><button id="approveBtn" class="btn primary" onclick="doApprove()">Approve</button></div>'
+ + '</div></div>';
+ const el = document.getElementById('code'); if (el) el.focus();
+}
+async function unpair(id){ const { ok, j } = await post('/api/revoke', { id }); toast(ok?('✓ Unpaired '+(j.fingerprint||'')):('✗ '+(j.error||'failed'))); refresh(); }
+async function unpairAll(){ if(!confirm('Unpair every browser?')) return; const { j } = await post('/api/revoke-all'); toast('✓ Unpaired '+(j.count||0)); refresh(); }
+async function stopAdapter(){ if(!confirm('Stop the adapter?')) return; await post('/api/stop'); toast('Stopping…'); }
+function isDevicePair(p){
+ return !!p && (p.role === 'device' || String(p.label || '').toLowerCase() === 'device');
+}
+
+function render(s){
+ lastStatus = s;
+ const c = document.getElementById('conn');
+ c.innerHTML = '<span class="dot '+(s.connected?'on':'off')+'"></span> <span class="mut">'+(s.connected?'cloud connected':'cloud reconnecting…')+'</span>';
+ const d = document.getElementById('device');
+ const deviceOnline = !!s.deviceE2eeConnected || !!((s.pairs||[]).find(p => isDevicePair(p) && p.online));
+ const deviceTransport = !!s.deviceTransportConnected;
+ d.innerHTML = '<span class="dot '+(deviceOnline?'on':deviceTransport?'idle':'off')+'"></span> <span class="mut">device '+(deviceOnline?'connected':deviceTransport?'pairing':'offline')+'</span>';
+ document.getElementById('agent').textContent = (s.agentId||'').slice(0,8) || '—';
+ const nAgents = (s.sessions||[]).length;
+ document.getElementById('agents').textContent = nAgents === 0 ? 'no agents' : nAgents + (nAgents === 1 ? ' agent' : ' agents');
+ document.getElementById('uptime').textContent = fmtDur(s.uptimeSec);
+ document.getElementById('fp').textContent = s.fingerprint || '—';
+ const wl = document.getElementById('weblink');
+ wl.href = s.webUrl ? (s.webUrl.replace(/\\/$/,'')+'/machine/'+s.agentId) : '#';
+
+ // 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>';
+
+ // pairs
+ const pe = document.getElementById('pairs');
+ pe.innerHTML = (s.pairs&&s.pairs.length) ? s.pairs.map(p => {
+ const role = isDevicePair(p) ? 'device' : (p.role || 'web');
+ return '<div class="row"><span class="dot '+(p.online?'on':'idle')+'"></span><div class="main"><div class="name fp">'+esc(p.fingerprint)+'</div><div class="sub"><span class="pill">'+esc(role)+'</span>'+esc(p.label)+' · paired '+fmtWhen(p.pairedAt)+'</div></div><button class="btn danger" onclick="unpair(\\''+esc(p.fingerprint)+'\\')">Unpair</button></div>';
+ }).join('') : '<div class="empty">No clients paired. Use Set up browser or run <span class="mono">harness browser-link</span>.</div>';
+
+ // pending — rebuild ONLY when it actually changes (new/rotated pairing), else leave the code input
+ // and whatever the user typed/pasted intact (polling every 2.5s must not wipe the field).
+ // Pending pairing → a MODAL popup. Built once per pending (guarded by pendKey) so polling every 2.5s
+ // doesn't clobber it. If the web link supplied ?code=…, it's pre-filled and the user just clicks
+ // Approve — nothing to type. Otherwise a code input is shown as a fallback.
+ const pd = document.getElementById('pending');
+ if (setupModalOpen) {
+ buildSetupApproveModal(s);
+ } else if (!setupInFlight) {
+ if (s.pending) {
+ const key = s.pending.expiresAt + '|' + s.pending.label;
+ if (key !== pendKey) {
+ pendKey = key;
+ // A blocking modal ONLY when arrived via the web "Approve" link (?code=…) and not yet closed;
+ // opening directly (or after Close) shows a subtle inline banner instead (normal UI, no overlay).
+ if (dismissedKey !== key) { if (urlCode && !modalClosed) buildApproveModal(s); else buildInlinePending(s); }
+ }
+ } else if (pendKey !== null) { pd.innerHTML = ''; pendKey = null; dismissedKey = null; }
+ }
+
+ // machine summary — keep the default view human-readable; tuck raw paths/ports into Advanced.
+ const cfg = s.config||{};
+ const sessionCount = (s.sessions&&s.sessions.length) || 0;
+ const pairCount = (s.pairs&&s.pairs.length) || 0;
+ const machineUrl = s.webUrl ? (s.webUrl.replace(/\\/$/,'')+'/machine/'+s.agentId) : '#';
+ document.getElementById('about').innerHTML =
+ '<div class="statusGrid">'
+ + metric('Machine cloud', s.connected ? 'Connected' : 'Reconnecting')
+ + metric('Claude sessions', sessionCount ? ('Watching '+sessionCount) : 'Waiting')
+ + metric('Browsers', pairCount ? (pairCount+' paired') : 'None paired')
+ + metric('Device', deviceOnline ? 'Connected' : deviceTransport ? 'Pairing' : 'Offline')
+ + '</div>'
+ + '<div class="actions"><a class="btn" href="'+esc(machineUrl)+'" target="_blank" rel="noreferrer">Open machine</a><button class="btn" onclick="startBrowserSetup()">Set up browser</button><a class="btn" href="#pairs">Clients</a><button class="btn" onclick="document.getElementById(\\'logsBox\\').open=true;document.getElementById(\\'logsBox\\').scrollIntoView({behavior:\\'smooth\\',block:\\'nearest\\'});">View logs</button></div>'
+ + '<details class="adv"><summary>Advanced</summary>'
+ + kv('Backend URL', s.backendUrl)
+ + kv('Watched folder', cfg.watching)
+ + kv('CLI data', cfg.dataDir)
+ + kv('Local control', cfg.port)
+ + '</details>';
+}
+function metric(k,v){ return '<div class="metric"><span class="k">'+esc(k)+'</span><span class="v">'+esc(v||'')+'</span></div>'; }
+function kv(k,v){ return '<div class="kv"><span class="k">'+esc(k)+'</span><span class="v">'+esc(v||'')+'</span></div>'; }
+
+async function refresh(){
+ try {
+ const s = await (await fetch('/api/status')).json();
+ render(s);
+ if (setupMode && !setupAutoAttempted) { setupAutoAttempted = true; startBrowserSetup(); }
+ fetch('/api/logs').then(r=>r.ok?r.text():'').then(t=>{ if(t) document.getElementById('logs').textContent = t; }).catch(()=>{});
+ } catch { document.getElementById('conn').innerHTML = '<span class="dot off"></span> <span class="mut">cloud unreachable</span>'; }
+}
+refresh(); setInterval(refresh, 2500);
+</script>
+</body>
+</html>`
diff --git a/cli/tsconfig.json b/cli/tsconfig.json
new file mode 100644
index 000000000..2b81634b4
--- /dev/null
+++ b/cli/tsconfig.json
@@ -0,0 +1,18 @@
+{
+ "compilerOptions": {
+ "target": "ES2023",
+ "lib": ["ES2023"],
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "esModuleInterop": true,
+ "strict": true,
+ "skipLibCheck": true,
+ "outDir": "dist",
+ "rootDir": "src",
+ "declaration": false,
+ "incremental": true,
+ "tsBuildInfoFile": ".tsbuildinfo"
+ },
+ "include": ["src/**/*"],
+ "exclude": ["node_modules", "dist", "src/public", ".tsbuildinfo"]
+}
diff --git a/cli/vitest.config.ts b/cli/vitest.config.ts
new file mode 100644
index 000000000..d22a55b92
--- /dev/null
+++ b/cli/vitest.config.ts
@@ -0,0 +1,9 @@
+import { defineConfig } from 'vitest/config'
+
+export default defineConfig({
+ test: {
+ environment: 'node',
+ setupFiles: ['./vitest.setup.ts'],
+ include: ['src/**/*.test.ts', 'src/**/*.spec.ts'],
+ },
+})
diff --git a/cli/vitest.setup.ts b/cli/vitest.setup.ts
new file mode 100644
index 000000000..adbaeb556
--- /dev/null
+++ b/cli/vitest.setup.ts
@@ -0,0 +1,13 @@
+/**
+ * Point every test's data dir at a throwaway directory BEFORE any module reads `env`.
+ *
+ * `config/env.ts` resolves `ADAPTER_DATA_DIR` at import time and defaults to the user's real
+ * `~/.harness/cli/data`. Specs that import the hook server (and through it the registry) therefore wrote
+ * their fixtures into the LIVE registry — a stale `late-session` record turned up there, written by
+ * `launcherWs.spec.ts`, which is how this was found. Tests must never touch the user's data.
+ */
+import { mkdtempSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+process.env.ADAPTER_DATA_DIR = mkdtempSync(join(tmpdir(), 'adapter-test-data-'))