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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(cli): discover tmux agents by process
0xken15b1b5ebd0754c
diff --git a/.github/assets/engines/README.md b/.github/assets/engines/README.mdindex 42fc7a8de..a42d86a6e 100644--- a/.github/assets/engines/README.md+++ b/.github/assets/engines/README.md@@ -58,7 +58,3 @@ Open items, recorded rather than left implicit:One token is rewritten before rasterising — `oklch(95% 0.15 108)` → `#f8f676` — because librsvg 2.60does not implement `oklch()` and renders the tile black without it. That is a notation change, not arecolour: the colour is inside sRGB (no channel clamped), so the hex is exactly the declared colour.--Copies of the same files live in `autonomous-code` at `apps/web/public/engine-icons/` and-`apps/orangepi/web/public/assets/engine-icons/`, where a script converts them to the 20×20 LVGL-ARGB8888 maps the device uses. Change them together.diff --git a/cli/README.md b/cli/README.mdindex 0084271a2..155b0ebcb 100644--- a/cli/README.md+++ b/cli/README.md@@ -23,8 +23,8 @@ token into the installer: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.)+(The installer is a first-party hosted script; it downloads the published bundle and writes the+`~/.local/bin/harness` command.)```bashharness join <token> # connect this computer to an existing machine@@ -57,9 +57,20 @@ produces the single-file release artifact.**Install your build as `harness` (no release):** `bash scripts/install-cli.sh` bundles thisworking tree into `~/.harness/cli` — the same layout the public installer produces — and restarts thedaemon 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+turned **off** in the command shim it writes (otherwise the published release overwrites your build withinthe minute). See [`RELEASE.md`](RELEASE.md#local-install-no-upload).+After joining, start each agent yourself in tmux with its normal vendor command. Harness observes the+process; it does not launch the CLI or choose its permission/trust flags:++```bash+tmux new -s work+claude # or: codex, agent, opencode, pi, hermes, cmd, devin, muse, amp, kilo, grok+```++Each supported top-level CLI process in a pane appears automatically. Exiting the CLI removes only the+agent; the tmux pane and its shell remain yours.+## How it works```@@ -69,28 +80,25 @@ claude in tmux pane %3 ──writes──▶ ~/.claude/projects/**.jsonladapter 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+- **The adapter emulates a node** on the backend hub: it answers the hosted runtime RPCs+ (`agents_list` = discovered tmux processes, `sessions_list`, `session_get` = full JSONLreplay, `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 onlyif it's **≤ 5 MB and text** (binary → rejected). The same guard was added to the hosted runtime soboth 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.+- **Process discovery is lifetime authority.** On startup and every five seconds the daemon reads all+ tmux panes once and the process table once. A supported top-level engine creates an agent immediately,+ before an engine session exists. A changed process in the same pane replaces it immediately; an absent+ process is removed after two successful scans. Probe failures do not remove anything.+- **Hooks bind mutable engine sessions** to the process agent (tmux-only via `$TMUX_PANE`). They do not+ require `MACHINE_ID`. `SessionStart` and catch hooks attach transcript/store metadata; `SessionEnd` only+ requests an immediate process reconciliation. `/clear`, `/new`, and resume move or rotate the binding+ without changing the live process agent's UUID.+- **Live agent sync** to web + device: discovery emits `agent_synced` immediately, even with no session;+ binding later emits session sync, and confirmed process exit emits one `agent_deleted`. A sessionless+ agent returns an empty `sessions_list`, accepts input by `agentId`, and binds after the first turn.- **Mirror-all**: every JSONL line streams up — prompts typed directly in the terminal render inthe 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@@ -113,7 +121,7 @@ claude in tmux pane %3 ──writes──▶ ~/.claude/projects/**.jsonl| `CLAUDE_PROJECTS_DIR` | `~/.claude/projects` | where Claude writes session JSONL || `ADAPTER_DATA_DIR` | `~/.harness/cli/data` | registry + token persistence || `DISABLE_HOOK_INSTALL` | `false` | skip auto-installing the claude hooks |-| `TMUX_REAP_INTERVAL_MS` | `5000` | how often the reaper drops dead-pane sessions |+| `TMUX_REAP_INTERVAL_MS` | `5000` | process discovery interval (removal requires two confirmed misses) || `ADAPTER_UPDATE_URL` | `…/adapter/metadata.json` | GCS release manifest the daemon polls for a newer build || `ADAPTER_UPDATE_KEY` | `cli` | manifest key for this CLI || `ADAPTER_UPDATE_CHECK_MS` | `60000` | how often (ms) to poll for a newer build (check also runs on start) |@@ -125,7 +133,7 @@ claude in tmux pane %3 ──writes──▶ ~/.claude/projects/**.jsonlA paired device mirrors the same agent. The adapter emits a curated **commander stream** from thesame 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+It answers the device's `agents_list` (tiles) and `agent_recent` (last summary) RPCs; voiceturns arrive as an injected `message` → `sendToTmux`. A device that joins **mid-turn** converges viaa client-count signal (`__clients`) — the adapter re-emits the open turn's live state on join (noperiodic heartbeat).diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjsindex c87510864..db7158fd0 100644--- a/cli/hook/notify.mjs+++ b/cli/hook/notify.mjs@@ -1,13 +1,14 @@#!/usr/bin/env node/**- * Claude Code / Codex / Cursor session hook for machine-adapter.+ * Pane-scoped session hook shared by the supported hook-capable engines.** 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).+ * SessionEnd: asks the adapter to reconcile the pane; process discovery remains+ * the authority for whether the agent exists.** Always exits 0 quickly and swallows every error, so it can never block or* delay claude's session start/teardown.@@ -15,6 +16,7 @@import http from 'node:http'import { execFile } from 'node:child_process'+import { randomUUID } from 'node:crypto'import {closeSync,mkdirSync,@@ -35,7 +37,6 @@ const BOOT_TOLERANCE_SEC = 120const LOCK_STALE_MS = 5000const LOCK_RETRIES = 20const LOCK_RETRY_MS = 25-const SESSION_END_VERIFY_DELAY_MS = 2000const CURSOR_TASK_MAX_AGE_MS = 10 * 60_000const CURSOR_TASK_MAX_ENTRIES = 64const CURSOR_TASK_MAX_INPUT_BYTES = 128 * 1024@@ -73,6 +74,7 @@ function paths() {const codexHome = argValue('--codex-home', process.env.CODEX_HOME || join(homedir(), '.codex'))const grokHome = argValue('--grok-home', process.env.GROK_HOME || join(homedir(), '.grok'))const cursorHome = argValue('--cursor-home', process.env.CURSOR_HOME || join(homedir(), '.cursor'))+ const hermesHome = argValue('--hermes-home', process.env.HERMES_HOME || join(homedir(), '.hermes'))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 {@@ -83,6 +85,7 @@ function paths() {codexSessionsDir: join(codexHome, 'sessions'),grokSessionsDir: join(grokHome, 'sessions'),cursorProjectsDir: join(cursorHome, 'projects'),+ hermesDb: join(hermesHome, 'state.db'),commandcodeProjectsDir: join(commandcodeHome, 'projects'),devinHome,devinLocksDir: join(devinHome, 'session_locks'),@@ -199,16 +202,72 @@ async function panePid(pane) {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)+function argvTokens(args) {+ return (String(args || '').match(/"[^"]*"|'[^']*'|\S+/g) || []).map((token) => {+ const quoted = (token.startsWith('"') && token.endsWith('"')) || (token.startsWith("'") && token.endsWith("'"))+ return quoted ? token.slice(1, -1) : token+ })+}++function processEntrypoint(args) {+ const tokens = argvTokens(args)+ if (!tokens.length) return ''+ let index = 0+ let command = basename(tokens[index]).toLowerCase()+ if (command === 'env') {+ index+++ while (index < tokens.length && (tokens[index].startsWith('-') || /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[index]))) index+++ command = basename(tokens[index] || '').toLowerCase()+ }+ if (!/^(?:node|nodejs|bun|deno|python(?:\d+(?:\.\d+)*)?|bash|zsh|sh)$/.test(command)) return tokens[index] || ''+ index+++ const optionsWithValue = new Set(['-r', '--require', '--loader', '--import', '--conditions', '--inspect-port'])+ const inlineCodeOptions = new Set(['-c', '--command', '-e', '--eval', '--print'])+ while (index < tokens.length) {+ const token = tokens[index]+ if (token === '--') { index++; break }+ if (token === '-m' && index + 1 < tokens.length) return tokens[index + 1]+ if (inlineCodeOptions.has(token)) return ''+ if (!token.startsWith('-')) break+ index += optionsWithValue.has(token) && index + 1 < tokens.length ? 2 : 1+ }+ return tokens[index] || ''+}++const ENGINE_COMMANDS = {+ claude: 'claude', codex: 'codex', cursor: 'agent', hermes: 'hermes', commandcode: 'cmd',+ devin: 'devin', muse: 'muse', grok: 'grok',+}+const ENGINE_PATH_ENV = {+ claude: 'CLAUDE_PATH', codex: 'CODEX_PATH', cursor: 'CURSOR_PATH', hermes: 'HERMES_PATH',+ commandcode: 'COMMANDCODE_PATH', devin: 'DEVIN_PATH', muse: 'MUSE_PATH', grok: 'GROK_PATH',+}++function processMatchScore(row, engine) {+ const executable = basename(row.executable).toLowerCase()+ const entrypoint = processEntrypoint(row.args).toLowerCase()+ const entrybase = basename(entrypoint).toLowerCase()+ const configured = String(process.env[ENGINE_PATH_ENV[engine]] || ENGINE_COMMANDS[engine] || '').toLowerCase()+ const configuredBase = basename(configured).toLowerCase()+ if (configuredBase && (executable === configuredBase || entrybase === configuredBase+ || row.executable.toLowerCase() === configured || entrypoint === configured)) return 4+ if (engine === 'codex') return /@openai[\/\\]codex[\/\\]bin[\/\\]codex(?:\.js)?$/.test(entrypoint) ? 2 : 0if (engine === 'cursor') {- const executable = basename(row.executable).toLowerCase()- return executable === 'agent'- || executable === 'cursor-agent'- || /cursor-agent[\/\\]versions[\/\\][^/\\\s]+[\/\\]index\.js(?:\s|$)/.test(haystack)+ if (executable === 'cursor-agent' || entrybase === 'cursor-agent') return 3+ return /cursor-agent[\/\\]versions[\/\\][^/\\]+[\/\\]index\.js$/.test(entrypoint) ? 2 : 0}- return /(^|[\/\s])claude(?:[\s]|$)/.test(haystack)+ if (engine === 'commandcode') {+ if (/^\s*⌘(?:\s|$)/.test(row.executable) || /^\s*⌘(?:\s|$)/.test(row.args)+ || executable === 'commandcode' || executable === 'command-code'+ || entrybase === 'commandcode' || entrybase === 'command-code') return 3+ return /command-code[\/\\]dist[\/\\]index\.mjs$/.test(entrypoint) ? 2 : 0+ }+ if (engine === 'devin') return /devin[\/\\]cli[\/\\]_versions[\/\\][^/\\]+[\/\\]bin[\/\\]devin$/.test(entrypoint) ? 2 : 0+ if (engine === 'hermes') return /hermes-agent[\/\\]hermes$/.test(entrypoint)+ || /^(?:hermes|hermes_cli)(?:\.|$)/.test(entrypoint) ? 2 : 0+ if (engine === 'muse') return /^muse-bin-/.test(executable) || /^muse-bin-/.test(entrybase) ? 3 : 0+ if (engine === 'grok') return /\.grok[\/\\]bin[\/\\]grok$/.test(entrypoint) ? 2 : 0+ return /@anthropic-ai[\/\\]claude-code[\/\\]cli\.js$/.test(entrypoint) ? 2 : 0}async function processRows() {@@ -216,7 +275,7 @@ async function processRows() {if (stdout === null) return nullconst 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)+ 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) continuerows.push({pid: Number(match[1]),@@ -229,26 +288,62 @@ async function processRows() {return rows}-async function paneEngineProcessState(pane, engine) {+async function paneEngineProcess(pane, engine) {const rootPid = await panePid(pane)- if (rootPid === undefined) return 'unknown'- if (!rootPid) return 'gone'+ if (rootPid === undefined) return { state: 'unknown' }+ if (!rootPid) return { state: 'gone' }const rows = await processRows()- if (!rows) return 'unknown'+ if (!rows) return { state: 'unknown' }const children = new Map()+ const byPid = new Map(rows.map((row) => [row.pid, row]))for (const row of rows) {const list = children.get(row.parentPid) || []list.push(row)children.set(row.parentPid, list)}- const queue = [rootPid]+ const queue = [{ pid: rootPid, depth: 0 }]+ let best = nullwhile (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)+ const current = queue.shift()+ const row = byPid.get(current.pid)+ const score = row ? processMatchScore(row, engine) : 0+ if (row && score > 0 && (!best || current.depth < best.depth || (current.depth === best.depth && score > best.score))) {+ 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 ? {+ state: 'alive',+ identity: { pid: best.row.pid, executable: best.row.executable, startMarker: best.row.startMarker },+ } : { state: 'gone' }+}++/**+ * Hermes delegation children execute the same pane-scoped hook as the visible CLI session. During+ * daemon downtime the regular hook server cannot apply its source guard, so consult Hermes' own store+ * before writing the offline registry. Unknown is deliberately fail-closed: the startup reconciler can+ * still create the process-owned agent and session repair can bind it once the daemon returns, whereas+ * accepting an unknown row can replace the parent's session with a child.+ */+async function hermesTopLevelSession(dbPath, sessionId) {+ if (!/^[0-9]{8}_[0-9]{6}_[0-9a-fA-F]{4,16}$/.test(String(sessionId || ''))) return false+ for (let attempt = 0; attempt < 4; attempt++) {+ if (attempt > 0) await sleep(75)+ const raw = await execFileText('sqlite3', [+ '-json', '-cmd', '.timeout 500', '-cmd', 'PRAGMA query_only=1', `file:${dbPath}?mode=ro`,+ `SELECT source FROM sessions WHERE id = '${sessionId}';`,+ ], 1000)+ if (raw === null) return false+ try {+ const rows = JSON.parse(raw.trim() || '[]')+ if (!Array.isArray(rows) || rows.length === 0) continue+ const source = typeof rows[0]?.source === 'string' ? rows[0].source : ''+ return source === '' || source === 'cli'+ } catch {+ return false+ }}- return 'gone'+ return false}function bootTimeSec() {@@ -421,7 +516,7 @@ async function clearCursorTasks(sessionId) {})}-async function fallbackRegister(input, engine, tmuxPane, launcherId) {+async function fallbackRegister(input, engine, tmuxPane) {const p = paths()const transcriptPath = typeof input.transcript_path === 'string' ? input.transcript_path : ''const rawSessionId = input.session_id || input.conversation_id@@ -429,27 +524,31 @@ async function fallbackRegister(input, engine, tmuxPane, launcherId) {? rawSessionId: (transcriptPath ? basename(transcriptPath).replace(/\.jsonl$/, '') : '')if (!sessionId || !/^%\d+$/.test(tmuxPane)) return- if (engine !== 'cursor' && !transcriptPath) return+ const transcriptOptional = ['cursor', 'opencode', 'kilo', 'pi', 'hermes', 'commandcode', 'devin', 'grok'].includes(engine)+ if (!transcriptOptional && !transcriptPath) returnif (transcriptPath && !validTranscriptPath(engine, transcriptPath, p)) return+ const process = await paneEngineProcess(tmuxPane, engine)+ if (process.state !== 'alive' || !process.identity) return+ if (engine === 'hermes' && !await hermesTopLevelSession(p.hermesDb, sessionId)) returnawait 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 sameRuntime = (s) => s && s.tmuxPane === tmuxPane && s.engine === engine+ && (!s.processIdentity || (s.processIdentity.pid === process.identity.pid && s.processIdentity.startMarker === process.identity.startMarker))+ const existingIndex = sessions.findIndex(sameRuntime)const existing = existingIndex >= 0 ? sessions[existingIndex] : null- if (existingIndex < 0) {- sessions = sessions.filter((s) => !s || s.tmuxPane !== tmuxPane)- }+ // A resumed session moves to this process agent; the previous process remains visible but unbound.+ sessions = sessions.map((s) => s && s.sessionId === sessionId && !sameRuntime(s)+ ? { ...s, sessionId: '', boundAt: null, transcriptPath: null, source: null, updatedAt: now }+ : s)+ if (existingIndex < 0) sessions = sessions.filter((s) => !s || s.tmuxPane !== tmuxPane)+ const agentId = typeof existing?.agentId === 'string' && existing.agentId ? existing.agentId : randomUUID()const entry = {+ agentId,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: engine === 'grok'@@ -463,7 +562,7 @@ async function fallbackRegister(input, engine, tmuxPane, launcherId) {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),+ processIdentity: process.identity,registeredAt: typeof existing?.registeredAt === 'number' ? existing.registeredAt : now,updatedAt: now,lastHookAt: now,@@ -476,17 +575,9 @@ async function fallbackRegister(input, engine, tmuxPane, launcherId) {}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)- })+ // SessionEnd is not process-lifetime authority. If the daemon is down, its startup scan will reconcile+ // the actual tmux process; deleting the offline record here would hide a still-running CLI.+ void sessionId; void reason; void engine; void tmuxPane}async function main() {@@ -503,11 +594,6 @@ async function main() {const event = input.hook_event_name || input.hookEventNameconst tmuxPane = process.env.TMUX_PANEif (!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) returnif (engine === 'cursor' && input.is_background_agent === true) returnif (engine === 'codex' && isCodexSubagent(input, paths())) return// Devin's documented user-level hook locations include ~/.claude.json and ~/.claude/settings.json, so a@@ -539,7 +625,6 @@ async function main() {if (grokEventName !== 'SessionStart' && grokEventName !== 'UserPromptSubmit') returnconst body = {engine,- launcherId,hookEvent: grokEventName,sessionId,transcriptPath,@@ -557,7 +642,7 @@ async function main() {transcript_path: transcriptPath,cwd,cli_version: input.cliVersion || input.version,- }, engine, tmuxPane, launcherId)+ }, engine, tmuxPane)}return}@@ -607,7 +692,7 @@ async function main() {cliVersion: input.cursor_version || input.version,}const registered = await post(port, '/api/hook/session-start', body)- if (!registered) await fallbackRegister(input, engine, tmuxPane, launcherId)+ if (!registered) await fallbackRegister(input, engine, tmuxPane)const stopped = await post(port, '/api/hook/turn-stop', {sessionId,status: input.status,@@ -641,7 +726,7 @@ async function main() {model: modelName(input.model),cliVersion: input.cli_version || input.version,})- if (!registered) await fallbackRegister(input, engine, tmuxPane, launcherId)+ if (!registered) await fallbackRegister(input, engine, tmuxPane)}await post(port, '/api/hook/turn-stop', {sessionId: input.session_id,@@ -667,7 +752,6 @@ async function main() {: input.transcript_pathconst body = {engine,- launcherId,hookEvent: event,sessionId: input.session_id || input.conversation_id,transcriptPath,@@ -680,7 +764,7 @@ async function main() {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)+ if (!ok) await fallbackRegister(input, engine, tmuxPane)}main()diff --git a/cli/package.json b/cli/package.jsonindex 9d8472f14..95c07d544 100644--- a/cli/package.json+++ b/cli/package.json@@ -13,6 +13,7 @@"start": "node dist/cli.js","test": "vitest run","test:cursor-e2e": "RUN_CURSOR_E2E=1 vitest run src/engines/cursor/localE2e.spec.ts",+ "test:tmux-real": "RUN_REAL_TMUX_DISCOVERY=1 vitest run src/lib/tmuxAgentDiscovery.real.spec.ts --reporter=verbose","release": "bash scripts/upload-cli.sh"},"dependencies": {diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 6beb926b6..1543abc7b 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -9,8 +9,8 @@* 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,+ * What runs: engine hooks/plugins (session metadata → localhost hook server → process registry),+ * transcript/store readers, tmux process discovery,* and the backend socket (events up / chat + RPCs down).*/@@ -26,24 +26,20 @@ import { VERSION } from './version.js'import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'import { installAmpPlugin, installCodexHooks, installCommandCodeHooks, installCursorHooks, installDevinHooks, installGrokHooks, installHermesHooks, installKiloPlugin, 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 { refuseDuplicateAgent } from './lib/duplicateAgent.js'-import { launcherSessions } from './lib/launcherSessions.js'+import { ENGINE_CLI_COMMANDS, ENGINES } from './lib/engineBin.js'import { clearDeleted, isRecentlyDeleted, markDeleted } from './lib/deletedSessions.js'import { terminateDeletedAgent } from './lib/deleteAgentFallback.js'import { findLiveSession } from './lib/sessionRepair.js'-import { launchEngine } from './lib/launch.js'import {- startTmuxReaper,sendToTmux,sendKeyToTmux,sendLiteralToTmux,validateSessionRuntime,+ checkSessionRuntime,captureTmuxPane,- discoverTmuxResumes,- resolvePaneEngineProcess,listPaneTitles,} from './lib/tmux.js'+import { TmuxAgentReconciler, type DiscoveredTmuxAgent } from './lib/tmuxAgentDiscovery.js'import { Watcher, type LineEvent } from './watcher/watcher.js'import { startHookServer } from './hookServer.js'import { BackendSocket } from './backendSocket.js'@@ -90,7 +86,7 @@ import {commandCodeRunErrorSummary,lastCommandCodeTurnText,} from './engines/commandcode/normalizer.js'-import { acceptsInputBeforeSession, SessionInputController } from './lib/sessionInput.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'@@ -107,10 +103,6 @@ import {// 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@@ -133,36 +125,21 @@ const DEVIN_DB = join(env.DEVIN_HOME, 'sessions.db')// 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. */+/** Between session-binding attempts for a process whose engine store is not resolvable yet. */const REPAIR_RETRY_MS = 60_000-/** …but a NEW agent is a different case: it is waiting for something that is about to happen. Muse makes+/** A NEW process is waiting for a session that is about to appear. Muse makes* this concrete — its session is only claimable once the user has typed, because a file with no turn in* it cannot be told apart from the ones muse opens for itself. Backing off a full minute there costs the* FIRST message: the pane answers while web and device show nothing. So keep sweeping for a while first,- * then settle into the slow rhythm for launchers that will never resolve. */+ * then settle into the slow rhythm for processes that will never resolve. */const REPAIR_EAGER_ATTEMPTS = 24 // ≈2 min at the 5s sweepfunction 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.- Kilo is the exception with no bypass at all: it offers one on 'kilo run', but its interactive TUI —- the thing harness starts — rejects the flag, so a kilo agent still stops at its own permission prompt.- You can answer that prompt remotely from the web or the device; it arrives as a question, not as a- tool card.+Agents — after "harness join", run the vendor CLI directly inside tmux. Harness discovers supported+top-level processes automatically; it does not launch them or change their permission flags:+${ENGINES.map((engine) => ` ${ENGINE_CLI_COMMANDS[engine]}`).join('\n')}Machine:harness join <token> connect this computer to an existing machine using the token from its machine page@@ -432,7 +409,7 @@ async function statBirthMs(path: string): Promise<number> {return Number.isFinite(birth) ? birth : 0}-/** The daemon body: the actual long-running adapter (hooks + watcher + reaper + backend socket). */+/** The daemon body: hooks + watcher + process discovery + backend socket. */async function runForeground(token: string): Promise<void> {installTimestampedConsole() // daemon-only: every machine.log line gets a wall-clock timestampconst startedAt = Date.now()@@ -455,30 +432,9 @@ async function runForeground(token: string): Promise<void> {})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.+ // Persisted records are not trusted blindly. The process reconciler below adopts a matching live+ // runtime, replaces it immediately when PID/start-marker changed, and requires two successful misses+ // before removing it. Probe errors leave the registry untouched.// Recap pool AND voice router share one sync: both need to know which engines the machine actually// runs, and a router warmed for an engine no agent uses is exactly the bug this rides along to fix.const syncRecapPool = (): void => {@@ -505,57 +461,13 @@ async function runForeground(token: string): Promise<void> {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.- */+ // New process observations, session bindings, runtime-profile changes, reconnects and periodic+ // reconciliation refresh web and device from the same authoritative snapshot. Device agent_synced is+ // idempotent and can upsert a sessionless tile, so re-announcing at bind is both safe and necessary.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()@@ -1067,34 +979,14 @@ async function runForeground(token: string): Promise<void> {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).- */+ /** Release a mutable session binding, or remove the process-owned agent everywhere. */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)+ if (opts.keepAgent) registry.unbindSession(sessionId)else if (doomed) registry.removeAgent(doomed.agentId)else registry.remove(sessionId)syncRecapPool()@@ -1123,267 +1015,153 @@ async function runForeground(token: string): Promise<void> {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 tabbackend.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- : candidate.engine === 'grok'- ? await findGrokTranscript(env.GROK_HOME, candidate.cwd, candidate.sessionId) ?? undefined- : undefined- if ((candidate.engine === 'cursor' || candidate.engine === 'grok') && !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+ type RegisteredMeta = {+ isNew: boolean+ evicted: string | null+ rebound: string | null+ hookEvent?: string+ }++ const handleRegistered = async (entry: RegisteredSession, meta: RegisteredMeta): Promise<void> => {+ if (meta.rebound) {+ registry.inheritName(meta.rebound, entry.sessionId)+ mirror.inheritSummary(meta.rebound, entry.sessionId)+ forgetSession(meta.rebound, { force: true, keepAgent: true })+ 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) {+ forgetSession(meta.evicted, { force: true })+ }+ const reset = meta.isNew || (entry.engine !== 'cursor' && meta.hookEvent === 'SessionStart')+ const bornAfterAgent = meta.isNew && !meta.rebound && entry.boundAt !== null+ && entry.boundAt - entry.registeredAt > 0+ && !!entry.transcriptPath+ && await statBirthMs(entry.transcriptPath) >= entry.registeredAt+ const attached = await attachSession(entry, reset, entry.engine === 'cursor', bornAfterAgent)+ if (!attached) {+ registry.unbindSession(entry.sessionId)+ announceSession(entry)+ return+ }+ syncRecapPool()+ if (!meta.isNew) return+ registry.inheritName(entry.agentId, entry.sessionId)+ announceSession(entry)+ backend.send({+ type: 'session_synced',+ payload: {+ sessionId: entry.sessionId,+ agentId: entry.agentId,+ title: projectDisplayName(entry),+ createdAt: new Date(entry.boundAt ?? Date.now()).toISOString(),+ },+ })}- /**- * 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>()- /** Attempts so far per agent — the first few run on every sweep, see REPAIR_EAGER_ATTEMPTS. */const repairAttempts = 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+ const bindObservedAgent = async (observed: DiscoveredTmuxAgent): Promise<void> => {+ const agent = registry.byPaneEngine(observed.tmuxPane, observed.engine)+ if (!agent || agent.sessionId) return++ let sessionId = observed.resumeSessionId+ let transcriptPath: string | undefined+ let source = 'tmux-resume'+ if (sessionId) {+ if (isRecentlyDeleted(sessionId)) return+ const owner = registry.bySession(sessionId)+ if (owner && owner.agentId !== agent.agentId) {+ const observedStarted = Date.parse(observed.processIdentity.startMarker)+ const ownerStarted = Date.parse(owner.processIdentity?.startMarker ?? '')+ if (Number.isFinite(ownerStarted) && (!Number.isFinite(observedStarted) || observedStarted <= ownerStarted)) return+ }+ transcriptPath = observed.engine === 'cursor'+ ? await findCursorTranscript(env.CURSOR_HOME, sessionId) ?? undefined+ : observed.engine === 'grok'+ ? await findGrokTranscript(env.GROK_HOME, observed.cwd, sessionId) ?? undefined+ : undefined+ if ((observed.engine === 'cursor' || observed.engine === 'grok') && !transcriptPath) return+ } else {const attempts = repairAttempts.get(agent.agentId) ?? 0- if (attempts >= REPAIR_EAGER_ATTEMPTS && Date.now() - attemptedAt < REPAIR_RETRY_MS) continue+ const lastAttempt = lastRepairAttempt.get(agent.agentId) ?? 0+ if (attempts >= REPAIR_EAGER_ATTEMPTS && Date.now() - lastAttempt < REPAIR_RETRY_MS) returnlastRepairAttempt.set(agent.agentId, Date.now())repairAttempts.set(agent.agentId, attempts + 1)- 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}`,- )+ const startedAtMs = Date.parse(observed.processIdentity.startMarker)+ if (!Number.isFinite(startedAtMs)) return+ const found = await findLiveSession(observed.engine, observed.cwd, startedAtMs, { bornOnly: true })+ if (!found || registry.has(found.sessionId) || isRecentlyDeleted(found.sessionId)) return+ sessionId = found.sessionId+ transcriptPath = found.transcriptPath+ source = 'process-repair'}- }- // 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.- // Turned away at the door, before hooks are installed or an engine is spawned — see the module for- // why muse alone cannot host two agents in one directory.- // Two filters, both learned the hard way: the registry is PERSISTED, so after a daemon restart it is- // full of agents that may no longer exist, and a launcher reconnecting arrives under the agent id it- // already owns. Without either guard the rule refused the very launchers it was meant to protect —- // measured: a restart killed both live muse panes, because each was turned away by its own saved entry.- refuseLauncher: ({ engine, cwd, launcherId, isLive }) =>- refuseDuplicateAgent(registry.list(), engine, cwd, { selfId: launcherId, isLive }),- 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,+ const previousOwner = registry.bySession(sessionId)+ const result = registry.register({+ engine: observed.engine,+ sessionId,+ transcriptPath,+ cwd: observed.cwd,+ source,+ tmuxPane: observed.tmuxPane,+ processIdentity: observed.processIdentity,+ hookEvent: source === 'tmux-resume' ? 'TmuxResumeDiscovery' : 'ProcessRepair',+ })+ if (!result || !result.isNew) return+ if (previousOwner && previousOwner.agentId !== result.entry.agentId) {+ input.forget(previousOwner.agentId)+ announceSession(previousOwner)+ }+ lastRepairAttempt.delete(agent.agentId)+ repairAttempts.delete(agent.agentId)+ await handleRegistered(result.entry, result)+ console.log(`[discovery] bound ${observed.engine} session ${sid(result.entry.sessionId)} on ${observed.tmuxPane}`)+ }++ const agentReconciler = new TmuxAgentReconciler({+ current: () => registry.list(),+ onDiscovered: async (observed) => {+ const opened = registry.openProcessAgent({+ engine: observed.engine,+ tmuxPane: observed.tmuxPane,+ cwd: observed.cwd,+ processIdentity: observed.processIdentity,})- 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}`)+ if (!opened) return+ if (opened.evicted) console.log(`[discovery] ${observed.tmuxPane} replaced ${sid(opened.evicted)}`)+ if (opened.isNew) {+ console.log(`[discovery] ${sid(opened.entry.agentId)} opened · engine=${observed.engine} · pane=${observed.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?.()+ await bindObservedAgent(observed)},- 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)- }- })+ onObserved: async (observed, current) => {+ registry.updateProcessIdentity(current.agentId, observed.processIdentity)+ await bindObservedAgent(observed)},+ onRemoved: (agent, reason) => {+ console.log(`[discovery] ${sid(agent.agentId)} removed · ${reason}`)+ forgetSession(agent.agentId, { force: true })+ },+ })++ // SessionEnd describes the mutable engine session, never process lifetime. Reconcile now; discovery+ // decides whether the agent still exists from tmux + ps.+ const onSessionEnd = (_sessionId: string, _reason: string | undefined): void => {+ void agentReconciler.trigger()+ }++ const { server: hookServer, port: hookPort } = await startHookServer(env.PORT, {+ resolveHookAgent: async ({ engine, tmuxPane }) => {+ await agentReconciler.trigger()+ return registry.byPaneEngine(tmuxPane, engine) ?? null+ },+ onRegistered: handleRegistered,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@@ -1553,9 +1331,8 @@ async function runForeground(token: string): Promise<void> {installOpencodePlugin(hookPort)installKiloPlugin(hookPort)installPiExtension(hookPort)- // Amp belongs here with the other plugin-based engines, and it was missed. It matters most after a- // SELF-UPDATE: the daemon restarts, and this is what puts the new plugin on disk immediately rather- // than leaving it until someone next runs `harness amp`.+ // A self-update refreshes plugin files here; running engine processes pick them up according to each+ // vendor's own plugin reload lifecycle.installAmpPlugin(hookPort)installHermesHooks(hookPort)installDevinHooks(hookPort)@@ -1630,8 +1407,8 @@ async function runForeground(token: string): Promise<void> {}})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+ // An UNBOUND process agent has no transcript to attach to yet. Discovery keeps it visible and the+ // hook/store repair path binds it as soon as the engine reports a session. Attaching an// empty session id here would tear down an agent the user can see running in their pane, which is// exactly what a self-update restart must never do.if (!session.sessionId) continue@@ -1657,12 +1434,7 @@ async function runForeground(token: string): Promise<void> {}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)+ agentReconciler.start(env.TMUX_REAP_INTERVAL_MS)for (const task of await loadCursorPendingTasks(env.ADAPTER_DATA_DIR)) {onCursorTaskStart(task.sessionId, task.toolUseId, task.input)}@@ -1778,9 +1550,8 @@ async function runForeground(token: string): Promise<void> {* 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).+ * that pane was the last one. The pane is the user's; only the exact discovered engine process is+ * signalled. Its PID and start marker are re-validated before SIGTERM/SIGKILL.** `registry.remove` + `mirror.forget` keep the recap AND the agent-name override for a later resume.*/@@ -1789,23 +1560,23 @@ async function runForeground(token: string): Promise<void> {// 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 */ }+ if (s?.processIdentity) {+ agentReconciler.suppress({ engine: s.engine, tmuxPane: s.tmuxPane, processIdentity: s.processIdentity })}forgetSession(sessionId, { force: true })if (!s) returnvoid terminateDeletedAgent(s, {- isAlive: validateSessionRuntime,+ checkRuntime: checkSessionRuntime,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) => {+ }, 0).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)+ void agentReconciler.trigger()}).catch((err) => {- console.error('[delete] fallback failed:', err instanceof Error ? err.message : err)+ console.error('[delete] process termination failed:', err instanceof Error ? err.message : err)})}@@ -1822,19 +1593,9 @@ async function runForeground(token: string): Promise<void> {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 && !acceptsInputBeforeSession(record.engine)) {- 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.@@ -1843,11 +1604,6 @@ async function runForeground(token: string): Promise<void> {}, 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 sessions for ${ENGINES.length} engines`)@@ -1870,23 +1626,12 @@ async function runForeground(token: string): Promise<void> {const restartForUpdate = async (newVersion: string): Promise<void> => {if (restarting) returnrestarting = 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)+ agentReconciler.stop()clearInterval(logTrimTimer)clearInterval(runtimeReconcileTimer)- clearInterval(tmuxResumeDiscoveryTimer)clearInterval(paneTitleSyncTimer)questionWatcher.stopAll()for (const t of heartbeats.values()) clearInterval(t)@@ -1899,13 +1644,8 @@ async function runForeground(token: string): Promise<void> {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.+ // Release the fixed hook port before the child binds. Process-owned agents stay in the persisted+ // registry and are revalidated by the new daemon's first discovery passes.hookServer.close()shutdownSummaryPool()shutdownVoiceRouter()@@ -1983,10 +1723,9 @@ async function runForeground(token: string): Promise<void> {const shutdown = async (signal: string): Promise<void> => {console.log(`\n[cli] ${signal} — shutting down`)updater?.stop()- clearInterval(reaper)+ agentReconciler.stop()clearInterval(logTrimTimer)clearInterval(runtimeReconcileTimer)- clearInterval(tmuxResumeDiscoveryTimer)clearInterval(paneTitleSyncTimer)questionWatcher.stopAll()for (const t of heartbeats.values()) clearInterval(t)@@ -2152,7 +1891,7 @@ async function waitForReady(sinceOffset: number, timeoutMs = 8000): Promise<Readreturn { state: 'unreachable', detail: lastTransient ?? `no connection within ${timeoutMs / 1000}s` }}-// ── launcher / stop / status ───────────────────────────────────────────────────────────────────+// ── daemon start / 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. */@@ -2515,16 +2254,6 @@ switch (cmd) {updateCommand().catch(onError)breakdefault:- // `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/engines/README.md b/cli/src/engines/README.mdindex 62887f06a..f8f232c75 100644--- a/cli/src/engines/README.md+++ b/cli/src/engines/README.md@@ -43,12 +43,11 @@ against 4 waits in a single observed session — and an unclosed sub-agent row *That pinned the device tile on "Processing" every 5 seconds forever and meant no recap was everproduced. No amount of invented fixture data would have surfaced that; one real session did.-The rule also forbids concluding that something is *absent*. Amp's `--help` lists no permission-bypass, so its table was first written with none — and the binary's strings hold-`--dangerously-allow-all`, which is real and load-bearing: with a permission rule set to `ask` and no-flag, Amp does not stop and wait for a human, it refuses the tool mid-turn and carries on, so an-unattended agent produces a turn that quietly did nothing. Grep the binary before you write "this-agent has no X".+The rule also forbids concluding that something is *absent*. Amp's `--help` once appeared to show no+permission bypass, while the binary strings exposed one. Harness no longer launches interactive agent+processes or supplies permission flags, so the user's normal CLI configuration owns that behavior; the+recording still matters because refused tools change the transcript and turn boundary. Grep the binary+before you write "this agent has no X".The same lesson is already written into `CONTRIBUTING.md` for the example provider: two real bugswere invisible to hand-written fixtures and obvious the moment a recorded turn was replayed. Record@@ -75,11 +74,9 @@ fails silently if inherited unchanged:- **The pane footer.** Opencode's resolver anchors on its `Build`/`Plan` agent names. Kilo's agent is`code`, so the inherited function matched nothing and returned null forever: a blank model chip, noerror anywhere. It had to be rewritten, not renamed.-- **The permission flag.** Opencode takes `--auto`. Kilo documents `--auto` on its `run` subcommand- but its TUI *rejects* it — so inheriting the flag would not have loosened permissions, it would have- stopped the agent from starting. Note that a non-TTY check cannot tell you this: with stdin closed,- a real flag and an invented one both print the same usage block. Test permission flags on a real TTY- inside tmux, with a control run.+- **The permission behavior.** Kilo's interactive TUI and its non-interactive `run` subcommand do not+ accept the same flags. Harness never adds a flag to the user's TUI process, but its private recap+ worker uses `run`; keep those two paths separate and measure each on the real binary.- **The ask-the-user dialog.** Opencode draws Claude's numbered dialog inside a box. Kilo draws anunnumbered row of options laid out *horizontally*, sharing its line with the key hints, and walkedwith `Right` rather than `Down`. Same product lineage, completely different parser.@@ -113,8 +110,8 @@ Three things that pattern gets wrong if nobody warns you, all found by running i- **A plugin's working directory is the plugin's own.** Amp's reported `<project>/.amp/plugins`, notthe agent's directory. The `cwd` recorded in the transcript is what re-binds a session after a- daemon restart, so a wrong one means an agent that can never be found again. The launcher exports- the real directory instead (`HARNESS_AGENT_CWD`).+ daemon restart, so a wrong one means an agent that can never be found again. Read the real directory+ from the plugin's host context or the discovered pane metadata.- **Your events may not carry assistant text.** None of Amp's five do. The text has to be read fromthe thread handle the plugin already holds — and because that handle already contains thein-flight message when a tool is called, snapshotting there emits a message's prose *before* the@@ -145,7 +142,7 @@ The real Grok recording exposed five details that are easy to get wrong by copyi- Session directories usually encode the cwd as one URL component. Long paths live under a hash instead,with the original cwd in `.cwd`; discovery and restart repair must handle both layouts.- Grok creates no session when the TUI merely opens. The first prompt creates it and fires the hooks, so- a remote first prompt must be injected into the launcher's pane before a session id exists. Holding it+ a remote first prompt must be injected into the discovered process pane before a session id exists. Holding ituntil registration deadlocks on the very `UserPromptSubmit` event that registration needs.The recorded envelope is `{timestamp, method, params:{sessionId, update, _meta}}`. Keep its fixture as a@@ -177,7 +174,7 @@ Mechanical. Three files, no judgment required.| File | What to add ||---|---|| `engines/types.ts` | Your name in the `AgentEngine` union. This is the source of truth; TypeScript will now tell you most of the remaining work |-| `lib/engineBin.ts` | The binary name, the `<ENGINE>_PATH` env override, and what to print as `harness <cmd>`. Add aliases if your CLI has more than one spelling — a user reaching for the name they know should not get "unknown command" |+| `lib/engineBin.ts` | The canonical vendor command, the `<ENGINE>_PATH` env override, and the ordered discovery list. Harness observes this command in tmux; it never dispatches `harness <engine>` || `config/env.ts` | `<ENGINE>_HOME` and `<ENGINE>_CONFIG_DIR` defaults, so a user with a non-standard install can point Harness at it |After Stage A, run `npm run typecheck`. The errors it prints are a good first map of Stages B–E.@@ -219,7 +216,7 @@ Either way, two more files:| `lib/registry.ts` | Where your transcripts live, and your name in the two `engine === …` accept-lists so the wire protocol will carry it || `lib/tmux.ts` | How to recognise your process in a pane, and your resume flags so a session id can be recovered from the command line |-`lib/tmux.ts` deserves care. If your launcher `exec`s a differently-named real binary, the pane+`lib/tmux.ts` deserves care. If the vendor command `exec`s a differently-named real binary, the paneprocess is not the name the user typed — Muse's pane shows `muse-bin-<version>`, and matching onlythe bare name silently finds nothing.@@ -270,9 +267,7 @@ Only needed for the capabilities your agent actually has. Skip what does not app| File | What to add ||---|---|-| `lib/launch.ts` | How to start it, and any environment that must be pinned. Muse forks a background self-update on every invocation that can replace the binary mid-session, so `MUSE_NO_AUTO_UPDATE=1` is set — **an agent must not change under the person using it** || `lib/sessionInput.ts` | How text is submitted, and how long to wait before deciding the submit failed. Muse writes its `started` record as soon as it accepts a prompt, so 6 seconds is enough; a slower agent needs a longer window |-| `lib/enginePermissions.ts` | The flag that turns off approval prompts, plus the finer flags you *own*. Listing owned flags is what lets a user who passes one of them keep their choice instead of getting ours on top. Flags are the whole mechanism — Harness will not edit your config file to get past a gate, so if trust lives only in config, that prompt stays with the user. Check the binary for the flag before concluding there isn't one: Amp's is undocumented || `lib/sessionRepair.ts` | Rebinding a pane to its session after a restart || `lib/oneshot.ts` | Running a single prompt outside an interactive session |diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.tsindex 90590a8b1..f77e1294b 100644--- a/cli/src/hookNotify.spec.ts+++ b/cli/src/hookNotify.spec.ts@@ -18,15 +18,22 @@ afterEach(async () => {interface RunHookOpts {port: numbertmuxPane?: 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). */+ /** Legacy environment noise: process-owned hooks must behave the same with or without it. */launcherId?: string | null- engine?: 'claude' | 'codex' | 'cursor' | 'devin' | 'commandcode' | 'grok'+ /** Install deterministic tmux/ps fixtures so an offline fallback can prove process ownership. */+ processEngine?: 'claude' | 'codex' | 'cursor' | 'hermes' | 'devin' | 'commandcode' | 'grok'+ /** Override the fixture's ps `comm` and full argv to exercise install-root-independent matching. */+ processExecutable?: string+ processArgs?: string+ engine?: 'claude' | 'codex' | 'cursor' | 'hermes' | 'devin' | 'commandcode' | 'grok'env?: Record<string, string>dataDir?: stringclaudeProjectsDir?: stringcodexHome?: stringcursorHome?: string+ hermesHome?: string+ /** Fake Hermes SQLite source; null means the session row has not appeared. */+ hermesSource?: 'cli' | 'subagent' | nullgrokHome?: stringdevinHome?: stringinput?: Record<string, unknown>@@ -40,12 +47,26 @@ function runHook(opts: RunHookOpts): Promise<string> {if (opts.tmuxPane) env.TMUX_PANE = opts.tmuxPanedelete env.MACHINE_IDif (opts.launcherId !== null) env.MACHINE_ID = opts.launcherId ?? '11111111-2222-4333-8444-555555555555'+ if (opts.processEngine) {+ const binDir = mkdtempSync(join(tmpdir(), 'adapter-hook-bin-'))+ tmpDirs.push(binDir)+ const executable = opts.processExecutable ?? (opts.processEngine === 'cursor' ? 'agent' : opts.processEngine)+ const processArgs = opts.processArgs ?? executable+ writeFileSync(join(binDir, 'tmux'), '#!/bin/sh\necho 7000\n', { mode: 0o755 })+ writeFileSync(join(binDir, 'ps'), `#!/bin/sh\nprintf '%s\\n' '7000 1 zsh Mon Aug 10 10:00:00 2026 -zsh' '7001 7000 ${executable} Mon Aug 10 10:00:01 2026 ${processArgs}'\n`, { mode: 0o755 })+ if (opts.hermesSource !== undefined) {+ const rows = opts.hermesSource === null ? '[]' : JSON.stringify([{ source: opts.hermesSource }])+ writeFileSync(join(binDir, 'sqlite3'), `#!/bin/sh\nprintf '%s\\n' '${rows}'\n`, { mode: 0o755 })+ }+ env.PATH = `${binDir}:${env.PATH ?? ''}`+ }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.hermesHome) args.push('--hermes-home', opts.hermesHome)if (opts.grokHome) args.push('--grok-home', opts.grokHome)if (opts.devinHome) args.push('--devin-home', opts.devinHome)const child = spawn(process.execPath, args, {@@ -219,7 +240,7 @@ describe('hook notify tmux scope', () => {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 () => {+ it('forwards tmux events regardless of legacy MACHINE_ID', async () => {const requests: Array<{ url: string; body: Record<string, unknown> }> = []const server = createServer((req, res) => {let raw = ''@@ -234,14 +255,12 @@ describe('hook notify tmux scope', () => {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([])+ expect(requests).toHaveLength(1)- // 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')+ expect(requests).toHaveLength(2)+ expect(requests.map((request) => request.url)).toEqual(['/api/hook/session-end', '/api/hook/session-end'])})it('drops standalone SessionEnd but forwards tmux SessionEnd', async () => {@@ -281,6 +300,7 @@ describe('hook notify tmux scope', () => {await runHook({port: 9,tmuxPane: '%7',+ processEngine: 'claude',dataDir,claudeProjectsDir,input: {@@ -321,6 +341,9 @@ describe('hook notify tmux scope', () => {port: 9,tmuxPane: '%8',engine: 'codex',+ processEngine: 'codex',+ processExecutable: 'node',+ processArgs: 'node /nix/store/codex-cli/lib/node_modules/@openai/codex/bin/codex.js',dataDir,codexHome,input: {@@ -335,6 +358,70 @@ describe('hook notify tmux scope', () => {expect(registry).toMatchObject([{ sessionId: 'codex-session', engine: 'codex', tmuxPane: '%8' }])})+ it('does not treat engine names in unrelated process arguments as an offline agent', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-process-false-positive-'))+ tmpDirs.push(dir)+ const claudeProjectsDir = join(dir, 'claude-projects')+ const dataDir = join(dir, 'data')+ const transcriptPath = join(claudeProjectsDir, 'demo', 'session-false.jsonl')+ mkdirSync(join(transcriptPath, '..'), { recursive: true })+ writeFileSync(transcriptPath, '{}\n')++ await runHook({+ port: 9,+ tmuxPane: '%81',+ processEngine: 'claude',+ processExecutable: 'python3',+ processArgs: 'python3 /work/runner.py compare claude codex agent hermes',+ dataDir,+ claudeProjectsDir,+ input: {+ hook_event_name: 'SessionStart',+ session_id: 'session-false',+ transcript_path: transcriptPath,+ },+ })++ expect(() => readFileSync(join(dataDir, 'registry.json'), 'utf8')).toThrow()+ })++ it('offline Hermes fallback binds only source=cli and rejects delegation children or unknown rows', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-hermes-source-'))+ tmpDirs.push(dir)+ const hermesHome = join(dir, 'hermes')+ const cliData = join(dir, 'cli-data')+ const common = {+ port: 9,+ tmuxPane: '%82',+ engine: 'hermes' as const,+ processEngine: 'hermes' as const,+ processExecutable: 'python3',+ processArgs: 'python3 /opt/venvs/hermes/lib/python3.12/site-packages/hermes-agent/hermes',+ hermesHome,+ }++ await runHook({+ ...common,+ dataDir: cliData,+ hermesSource: 'cli',+ input: { hook_event_name: 'on_session_start', session_id: '20260810_120000_a1b2c3' },+ })+ expect(JSON.parse(readFileSync(join(cliData, 'registry.json'), 'utf8'))).toMatchObject([{+ sessionId: '20260810_120000_a1b2c3', engine: 'hermes', tmuxPane: '%82',+ }])++ for (const [name, source] of [['child', 'subagent'], ['unknown', null]] as const) {+ const dataDir = join(dir, `${name}-data`)+ await runHook({+ ...common,+ dataDir,+ hermesSource: source,+ input: { hook_event_name: 'on_session_start', session_id: `20260810_12000${name === 'child' ? '1' : '2'}_a1b2c3` },+ })+ expect(() => readFileSync(join(dataDir, 'registry.json'), 'utf8')).toThrow()+ }+ })+it('does not fallback when the adapter accepts the hook event', async () => {const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-online-'))tmpDirs.push(dir)@@ -399,7 +486,7 @@ describe('hook notify tmux scope', () => {expect(() => readFileSync(join(dataDir, 'registry.json'), 'utf-8')).toThrow()})- it('removes fallback registry entries on offline SessionEnd except clear', async () => {+ it('leaves offline registry ownership unchanged on SessionEnd', async () => {const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-end-'))tmpDirs.push(dir)const dataDir = join(dir, 'data')@@ -412,7 +499,7 @@ describe('hook notify tmux scope', () => {dataDir,input: { hook_event_name: 'SessionEnd', session_id: 'ended', reason: 'logout' },})- expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))).toEqual([{ sessionId: 'keep' }])+ expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))).toEqual([{ sessionId: 'keep' }, { sessionId: 'ended' }])await runHook({port: 9,@@ -420,7 +507,7 @@ describe('hook notify tmux scope', () => {dataDir,input: { hook_event_name: 'SessionEnd', session_id: 'keep', reason: 'clear' },})- expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))).toEqual([{ sessionId: 'keep' }])+ expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))).toEqual([{ sessionId: 'keep' }, { sessionId: 'ended' }])})it('keeps fallback registry entries when SessionEnd cannot prove the tmux app exited', async () => {@@ -459,6 +546,7 @@ describe('hook notify tmux scope', () => {await runHook({port: 9,tmuxPane: '%12',+ processEngine: 'claude',dataDir,claudeProjectsDir,input: {@@ -520,7 +608,7 @@ describe('hook notify Grok lifecycle', () => {writeFileSync(transcript, '{}\n')await runHook({- port: 9, tmuxPane: '%45', engine: 'grok', grokHome, dataDir,+ port: 9, tmuxPane: '%45', engine: 'grok', processEngine: 'grok', grokHome, dataDir,input: { hookEventName: 'session_start', sessionId, cwd },})expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))).toMatchObject([{diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.tsnew file mode 100644index 000000000..0768de3d7--- /dev/null+++ b/cli/src/hookServer.spec.ts@@ -0,0 +1,72 @@+import type { Server } from 'node:http'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { startHookServer, type HookServerHandlers } from './hookServer.js'++let server: Server | null = null++afterEach(async () => {+ if (!server) return+ await new Promise<void>((resolve) => server!.close(() => resolve()))+ server = null+})++async function start(overrides: Partial<HookServerHandlers> = {}) {+ const handlers: HookServerHandlers = {+ onRegistered: vi.fn(),+ onSessionEnd: vi.fn(),+ ...overrides,+ }+ const started = await startHookServer(0, handlers)+ server = started.server+ return { handlers, base: `http://127.0.0.1:${started.port}` }+}++describe('process-owned hook server', () => {+ it('runs targeted resolution and rejects a hook without a matching pane engine process', async () => {+ const resolveHookAgent = vi.fn(async () => null)+ const { handlers, base } = await start({ resolveHookAgent })+ const response = await fetch(`${base}/api/hook/session-start`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ engine: 'codex',+ tmuxPane: '%41',+ sessionId: '019fea92-e31a-7692-9c35-f616e9d458b7',+ cwd: '/work/demo',+ }),+ })++ expect(await response.json()).toEqual({ ignored: true, reason: 'no_matching_engine_process' })+ expect(resolveHookAgent).toHaveBeenCalledWith({ engine: 'codex', tmuxPane: '%41' })+ expect(handlers.onRegistered).not.toHaveBeenCalled()+ })++ it('rejects hooks outside tmux before attempting process resolution', async () => {+ const resolveHookAgent = vi.fn(async () => null)+ const { handlers, base } = await start({ resolveHookAgent })+ const response = await fetch(`${base}/api/hook/session-start`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ engine: 'claude', sessionId: 'session-1', cwd: '/work/demo' }),+ })++ expect(await response.json()).toEqual({ ignored: true, reason: 'not_in_tmux' })+ expect(resolveHookAgent).not.toHaveBeenCalled()+ expect(handlers.onRegistered).not.toHaveBeenCalled()+ })++ it('treats SessionEnd as a reconciliation hint and exposes no launcher websocket endpoint', async () => {+ const onSessionEnd = vi.fn()+ const { base } = await start({ onSessionEnd })+ const ended = await fetch(`${base}/api/hook/session-end`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ sessionId: 'session-1', reason: 'clear' }),+ })+ expect(await ended.json()).toEqual({ ok: true })+ expect(onSessionEnd).toHaveBeenCalledWith('session-1', 'clear')++ const legacy = await fetch(`${base}/api/machine-ws`)+ expect(legacy.status).toBe(404)+ })+})diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.tsindex f4efbbd95..d9f72c8b6 100644--- a/cli/src/hookServer.ts+++ b/cli/src/hookServer.ts@@ -8,22 +8,14 @@ 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@@ -32,26 +24,13 @@ export interface PairOutcome {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). */+ /** SessionEnd — a reconciliation hint only; it is never process-lifetime authority. */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- /** Turn a launcher away before it spawns anything; the string returned is shown to the person in the- * pane. Used for engines that cannot have two agents in one directory (see `refuseDuplicateAgent`). */- refuseLauncher?: (session: {+ /** Ensure a matching process-owned agent exists before a hook binds its mutable engine session. */+ resolveHookAgent?: (session: {engine: RegisteredSession['engine']- cwd?: string | null- /** This launcher's own agent id — it RECONNECTS under the same one, so it must never block itself. */- launcherId: string- /** Whether an agent id still has a launcher on the socket; a persisted entry alone proves nothing. */- isLive: (agentId: string) => boolean- }) => string | null+ tmuxPane: string+ }) => Promise<RegisteredSession | null>/** A turn is now running (Command Code's PreToolUse — its only live turn-open signal). Idempotent:* it fires once per tool call, and every call after the first in a turn must be a no-op. */onTurnStart?: (body: { sessionId: string }) => void@@ -115,7 +94,8 @@ const TRANSCRIPT_WAIT_TRIES = 20async 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+ const engine = body.engine ?? 'claude'+ if (!body.tmuxPane || !registry.byPaneEngine(body.tmuxPane, engine)) returnif (isRecentlyDeleted(body.sessionId)) returnif (!body.transcriptPath || !existsSync(body.transcriptPath)) continueconst result = registry.register(body)@@ -137,7 +117,7 @@ async function awaitHermesKind(body: RegisterInput, handlers: HookServerHandlersconst 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 (!body.tmuxPane || !registry.byPaneEngine(body.tmuxPane, 'hermes')) returnif (isRecentlyDeleted(body.sessionId)) returnconst source = await hermesSessionSource(dbPath, body.sessionId ?? '')if (source === null) continue@@ -170,10 +150,8 @@ export function startHookServer(// 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+ json(200, { ok: true, version: VERSION }); return}// Local dashboard (self-contained page) + its read-only status/logs.@@ -215,12 +193,15 @@ export function startHookServer(+ ` but this machine is v${VERSION} — that pane loaded an older copy.`)console.warn('[hooks] restart the pane (or reload its plugins) to pick up the current build')}- // 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 }+ const engine = body.engine ?? 'claude'+ const processAgent = handlers.resolveHookAgent+ ? await handlers.resolveHookAgent({ engine, tmuxPane: body.tmuxPane })+ : registry.byPaneEngine(body.tmuxPane, engine) ?? null+ if (!processAgent || processAgent.engine !== engine) { ignore('no_matching_engine_process'); return }+ // The process scanner is authoritative. Never accept a hook's legacy launcher id or a stale PID.+ body.processIdentity = processAgent.processIdentity ?? undefined// 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+ // hook still fires — and the exact process may remain alive during SIGTERM grace. Without// this the tile the user just deleted re-registers itself and comes back.if (isRecentlyDeleted(body.sessionId)) { ignore('deleted'); return }if (body.engine === 'codex' && body.transcriptPath && readCodexRolloutMeta(body.transcriptPath)?.isSubagent) {@@ -249,7 +230,7 @@ export function startHookServer(return}if (!result) {- console.warn(`[hooks] ${sid(body.sessionId ?? '?')} REJECTED · engine=${body.engine} pane=${body.tmuxPane} machine=${sid(body.launcherId ?? '?')}`)+ console.warn(`[hooks] ${sid(body.sessionId ?? '?')} REJECTED · engine=${body.engine} pane=${body.tmuxPane}`)json(400, { error: 'invalid session registration' })return}@@ -358,8 +339,6 @@ export function startHookServer(})()})- 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@@ -380,126 +359,3 @@ export function startHookServer(})})}--// ── 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.- // Before anything is installed or spawned: some engines cannot have two agents in one directory,- // because nothing in what they write says which of the two a session belongs to. `exit` — not- // `error` — is what carries this: a launcher that predates this rule ignores an unknown `error`- // reason and runs on regardless, while `exit` has always meant "stop this agent", so the rule holds- // on old builds too. A new launcher acts on it before it spawns the engine at all.- const refusal = handlers.refuseLauncher?.({- engine: opened.engine,- cwd: opened.cwd ?? null,- launcherId: opened.launcherId,- isLive: (agentId) => launcherSessions.has(agentId),- })- if (refusal) {- console.warn(`[machine] refused ${sid(opened.launcherId)} · engine=${opened.engine} · ${refusal}`)- send({ t: 'exit', reason: refusal })- try { ws.close() } catch { /* ignore */ }- return- }-- 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.tsdeleted file mode 100644index b43c75355..000000000--- a/cli/src/launcherProtocol.spec.ts+++ /dev/null@@ -1,170 +0,0 @@-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.tsdeleted file mode 100644index 4401fc289..000000000--- a/cli/src/launcherWs.spec.ts+++ /dev/null@@ -1,185 +0,0 @@-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/commander.ts b/cli/src/lib/commander.tsindex 8745debf6..ff11495a2 100644--- a/cli/src/lib/commander.ts+++ b/cli/src/lib/commander.ts@@ -614,15 +614,11 @@ export class CommanderMirror {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.+ * Move the stored recap to a new session id, for a rotation (`/clear`) inside the same live process agent.** 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.+ * the agent, its pane and its engine process never went anywhere.*/inheritSummary(fromSessionId: string, toSessionId: string): void {const summary = this.summaries.get(fromSessionId)@@ -631,6 +627,10 @@ export class CommanderMirror {this.save()}+ /** Session metadata was unbound or its process agent was removed: abort any in-flight recap and drop+ * the EPHEMERAL live state, but KEEP the persisted summary. A later resume of the same engine session+ * can reuse it via recent()/project_recent instead of losing the last device recap. SessionEnd alone+ * does not call this; process discovery owns lifetime. */forget(sessionId: string): void {const st = this.states.get(sessionId)st?.abort?.abort()diff --git a/cli/src/lib/daemonState.ts b/cli/src/lib/daemonState.tsindex 9be03a005..22671dde9 100644--- a/cli/src/lib/daemonState.ts+++ b/cli/src/lib/daemonState.ts@@ -2,9 +2,8 @@* 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).+ * Kept in its own module so management commands can inspect daemon state without importing `cli.ts`,+ * which would execute the command dispatcher.*/import { existsSync, readFileSync } from 'fs'diff --git a/cli/src/lib/deleteAgentFallback.spec.ts b/cli/src/lib/deleteAgentFallback.spec.tsindex 32f5a0723..98e565dbc 100644--- a/cli/src/lib/deleteAgentFallback.spec.ts+++ b/cli/src/lib/deleteAgentFallback.spec.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest'import { terminateDeletedAgent, type TerminateDeps } from './deleteAgentFallback.js'import type { RegisteredSession } from './registry.js'+import type { RuntimeCheck } from './tmux.js'/*** The one place in the adapter that signals somebody else's process. Everything here is about NOT hitting@@ -15,6 +16,10 @@ const SESSION = {processIdentity: { pid: 4242, executable: 'claude', startMarker: 'Mon Aug 3 09:00:00 2026' },} as unknown as RegisteredSession+const runtime = (alive: boolean): RuntimeCheck => alive+ ? { state: 'alive' }+ : { state: 'gone', reason: 'process exited' }+/** 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]> = []@@ -22,7 +27,7 @@ function deps(over: Partial<TerminateDeps> = {}): TerminateDeps & { kills: Arrayreturn {kills,logs,- isAlive: async () => true,+ checkRuntime: async () => runtime(true),kill: (pid, signal) => { kills.push([pid, signal]) },sleep: async () => { /* instant */ },log: (m) => { logs.push(m) },@@ -30,17 +35,16 @@ function deps(over: Partial<TerminateDeps> = {}): TerminateDeps & { kills: Array}}-describe('delete-agent fallback', () => {+describe('delete-agent process termination', () => {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 })+ const d = deps({ checkRuntime: async () => runtime(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]) } })+ const d = deps({ checkRuntime: async () => runtime(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']])})@@ -49,7 +53,7 @@ describe('delete-agent fallback', () => {// Some CLIs trap SIGTERM for a "press again to quit" prompt. Delete has to mean deleted.let alive = trueconst d = deps({- isAlive: async () => alive,+ checkRuntime: async () => runtime(alive),kill: (pid, signal) => { if (signal === 'SIGKILL') alive = false; d.kills.push([pid, signal]) },})await expect(terminateDeletedAgent(SESSION, d)).resolves.toBe('killed')@@ -58,8 +62,8 @@ describe('delete-agent fallback', () => {})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 })+ // checkRuntime compares pid AND start time, so a recycled pid reads as gone — the pid-reuse guard.+ const d = deps({ checkRuntime: async () => runtime(false) })await terminateDeletedAgent({ ...SESSION, processIdentity: { pid: 4242, executable: 'x', startMarker: 'later' } } as RegisteredSession, d)expect(d.kills).toEqual([])})@@ -84,7 +88,7 @@ describe('delete-agent fallback', () => {it('treats a process that vanished mid-signal as gone, not as a failure', async () => {let alive = trueconst d = deps({- isAlive: async () => alive,+ checkRuntime: async () => runtime(alive),kill: () => { alive = false; throw Object.assign(new Error('no such process'), { code: 'ESRCH' }) },})await expect(terminateDeletedAgent(SESSION, d)).resolves.toBe('gone')@@ -97,22 +101,21 @@ describe('delete-agent fallback', () => {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.+ it('signals immediately without a launcher wait', async () => {const waits: number[] = []- const d = deps({ isAlive: async () => false, sleep: async (ms) => { waits.push(ms) } })+ const d = deps({ checkRuntime: async () => runtime(false), sleep: async (ms) => { waits.push(ms) } })await terminateDeletedAgent(SESSION, d)- expect(waits[0]).toBeGreaterThan(3_000) // LAUNCHER_EXIT_GRACE_MS in launch.ts+ expect(waits[0]).toBe(0)})- 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')+ it('keeps the runtime suppressed when identity validation is unknown', async () => {+ const d = deps({ checkRuntime: async () => { throw new Error('tmux is unavailable') } })+ await expect(terminateDeletedAgent(SESSION, d)).resolves.toBe('failed')+ expect(d.logs.join('\n')).toContain('could not validate')})})-describe('delete-agent fallback timing', () => {+describe('delete-agent process termination 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.@@ -120,7 +123,7 @@ describe('delete-agent fallback timing', () => {const sleeps: number[] = []let calls = 0const d = deps({- isAlive: async () => { calls += 1; if (calls > 3) alive = false; return alive },+ checkRuntime: async () => { calls += 1; if (calls > 3) alive = false; return runtime(alive) },sleep: async (ms) => { sleeps.push(ms) },})await expect(terminateDeletedAgent(SESSION, d)).resolves.toBe('terminated')@@ -129,18 +132,18 @@ describe('delete-agent fallback timing', () => {it('honours caller-supplied budgets', async () => {const sleeps: number[] = []- const d = deps({ isAlive: async () => false, sleep: async (ms) => { sleeps.push(ms) } })+ const d = deps({ checkRuntime: async () => runtime(false), sleep: async (ms) => { sleeps.push(ms) } })await terminateDeletedAgent(SESSION, d, 10, 20)expect(sleeps[0]).toBe(10)})})-describe('delete-agent fallback wiring', () => {+describe('delete-agent process termination 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 } })+ const d = deps({ checkRuntime: async (s) => { seen.push(s); return runtime(false) } })await terminateDeletedAgent(SESSION, d)expect(seen[0]).toBe(SESSION)})diff --git a/cli/src/lib/deleteAgentFallback.ts b/cli/src/lib/deleteAgentFallback.tsindex 6ab7acf00..1bef4c460 100644--- a/cli/src/lib/deleteAgentFallback.ts+++ b/cli/src/lib/deleteAgentFallback.ts@@ -1,36 +1,16 @@-/**- * 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.- */+/** Stop the exact discovered engine process while leaving the user's tmux pane and shell alive. */import type { RegisteredSession } from './registry.js'+import type { RuntimeCheck } from './tmux.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+/** Delete has already removed the UI entry; signal the saved process immediately. */+export const TERMINATE_CHECK_MS = 0/** After SIGTERM. Matches the daemon's own stop sequence rather than inventing a tighter one. */export const FALLBACK_KILL_GRACE_MS = 3_000const POLL_MS = 250export type TerminateOutcome =- /** It left on its own — the launcher did its job, or the user closed it. */+ /** It left before or during signalling. */| 'gone'/** SIGTERM was enough. */| 'terminated'@@ -42,8 +22,8 @@ export type TerminateOutcome =| 'failed'export interface TerminateDeps {- /** `validateSessionRuntime`: the pane still holds THIS session's engine (pid + start time match). */- isAlive: (session: RegisteredSession) => Promise<boolean>+ /** Three-valued exact identity check. Probe failure is not evidence that the process is gone. */+ checkRuntime: (session: RegisteredSession) => Promise<RuntimeCheck>/** `process.kill`. Throws on EPERM/ESRCH like the real one. */kill: (pid: number, signal: NodeJS.Signals) => voidsleep: (ms: number) => Promise<void>@@ -51,7 +31,7 @@ export interface TerminateDeps {}/**- * Wait out the launcher, then stop the engine if it is still there. Never throws.+ * Validate the saved PID/start marker, 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.@@ -59,14 +39,23 @@ export interface TerminateDeps {export async function terminateDeletedAgent(session: RegisteredSession,deps: TerminateDeps,- checkAfterMs = FALLBACK_CHECK_MS,+ checkAfterMs = TERMINATE_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 check = async (): Promise<RuntimeCheck> => {+ try { return await deps.checkRuntime(session) }+ catch (err) { return { state: 'unknown', reason: err instanceof Error ? err.message : String(err) } }+ }+ // PID + start marker validation is what prevents a recycled PID from receiving our signal. Unknown+ // means we cannot prove the target and must leave the runtime suppressed rather than call it gone.+ const initial = await check()+ if (initial.state === 'gone') return 'gone'+ if (initial.state === 'unknown') {+ deps.log(`[delete] could not validate ${session.engine} runtime: ${initial.reason}`)+ return 'failed'+ }const pid = session.processIdentity?.pidif (!pid) return 'not-ours'@@ -84,17 +73,17 @@ export async function terminateDeletedAgent(}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'+ if (!signal('SIGTERM')) return (await check()).state === 'gone' ? 'gone' : 'failed'for (let waited = 0; waited < killGraceMs; waited += POLL_MS) {await deps.sleep(POLL_MS)- if (!await deps.isAlive(session).catch(() => false)) return 'terminated'+ if ((await check()).state === 'gone') return 'terminated'}deps.log(`[delete] ${session.engine} ignored SIGTERM — SIGKILL pid ${pid}`)- if (!signal('SIGKILL')) return await deps.isAlive(session).catch(() => false) ? 'failed' : 'gone'+ if (!signal('SIGKILL')) return (await check()).state === 'gone' ? 'gone' : 'failed'await deps.sleep(POLL_MS)- if (await deps.isAlive(session).catch(() => false)) {+ if ((await check()).state !== 'gone') {deps.log(`[delete] ${session.engine} pid ${pid} is STILL running after SIGKILL`)return 'failed'}diff --git a/cli/src/lib/deletedSessions.ts b/cli/src/lib/deletedSessions.tsindex b83ec9578..669e3a5c7 100644--- a/cli/src/lib/deletedSessions.ts+++ b/cli/src/lib/deletedSessions.ts@@ -4,7 +4,7 @@* 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+ * while the exact engine process is still alive — 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 asdiff --git a/cli/src/lib/discoveryScripts.spec.ts b/cli/src/lib/discoveryScripts.spec.tsindex 0dfb32818..59020790b 100644--- a/cli/src/lib/discoveryScripts.spec.ts+++ b/cli/src/lib/discoveryScripts.spec.ts@@ -3,14 +3,7 @@ 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.- */+/** Pi and OpenCode register through generated source, so pin its process-owned wire contract directly. */const dirs: string[] = []afterEach(() => {for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })@@ -24,7 +17,7 @@ function scratch(): string {}describe('generated discovery scripts', () => {- it('makes the Pi extension carry the launcher id', async () => {+ it('lets the Pi extension post from any tmux pane without launcher metadata', async () => {const piHome = scratch()vi.resetModules()process.env.PI_HOME = piHome@@ -32,12 +25,12 @@ describe('generated discovery scripts', () => {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+ expect(src).toContain('process.env.TMUX_PANE')+ expect(src).not.toContain('MACHINE_ID')+ expect(src).not.toContain('launcherId')})- it('makes the OpenCode plugin carry the launcher id', async () => {+ it('lets the OpenCode plugin post from any tmux pane without launcher metadata', async () => {const pluginDir = scratch()vi.resetModules()process.env.OPENCODE_PLUGIN_DIR = pluginDir@@ -45,9 +38,9 @@ describe('generated discovery scripts', () => {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/)+ expect(src).toContain('process.env.TMUX_PANE')+ expect(src).not.toContain('MACHINE_ID')+ expect(src).not.toContain('launcherId')+ expect(src).toMatch(/if \(!pane/)})})diff --git a/cli/src/lib/duplicateAgent.spec.ts b/cli/src/lib/duplicateAgent.spec.tsdeleted file mode 100644index b2e4a53e8..000000000--- a/cli/src/lib/duplicateAgent.spec.ts+++ /dev/null@@ -1,87 +0,0 @@-import { describe, expect, it } from 'vitest'-import { mkdtempSync, rmSync, symlinkSync } from 'fs'-import { tmpdir } from 'os'-import { join } from 'path'-import { refusalMessage, refuseDuplicateAgent, sameDirSync } from './duplicateAgent.js'--/**- * The rule exists because muse gives repair nothing to tell two agents in one directory apart, so the- * second one could never stream. Refusing a launch is a heavy hammer — the daemon answers `exit`, and a- * launcher acting on that ends the engine — so most of these tests are about what it must NOT block.- */-describe('one agent per directory', () => {- const CWD = '/Users/demo/work/project'- const SELF = 'agent-self'- const all = { selfId: SELF, isLive: () => true }- const agent = (agentId: string, engine: string, cwd: string | null = CWD) => ({ agentId, engine, cwd })-- it('turns away a second muse agent in the same directory', () => {- const reason = refuseDuplicateAgent([agent('agent-1', 'muse')], 'muse', CWD, all)- expect(reason).toContain(CWD)- expect(reason).toMatch(/one muse agent per directory/)- })-- it('lets the FIRST muse agent in — a directory is only taken once someone is there', () => {- expect(refuseDuplicateAgent([], 'muse', CWD, all)).toBeNull()- expect(refuseDuplicateAgent([agent('agent-1', 'claude')], 'muse', CWD, all)).toBeNull()- })-- it('lets muse run in a different directory', () => {- expect(refuseDuplicateAgent([agent('agent-1', 'muse', '/Users/demo/other')], 'muse', CWD, all)).toBeNull()- })-- it('never lets a launcher block itself', () => {- // A reconnect arrives under the agent id it already owns — the registry entry it is about to reclaim.- expect(refuseDuplicateAgent([agent(SELF, 'muse')], 'muse', CWD, all)).toBeNull()- })-- it('ignores an agent whose launcher is gone', () => {- // MEASURED failure: the registry is persisted, so a restarted daemon starts out holding agents that- // may no longer exist. Treating those as occupancy killed two live muse panes — each refused by its- // own saved entry. Only an agent still on the socket counts.- const dead = { selfId: SELF, isLive: () => false }- expect(refuseDuplicateAgent([agent('agent-1', 'muse')], 'muse', CWD, dead)).toBeNull()- })-- it('applies to muse ONLY — every other engine may share a directory', () => {- // The other eight report their session id, so two of them in one folder are still told apart.- for (const engine of ['claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin']) {- expect(refuseDuplicateAgent([agent('agent-1', engine)], engine, CWD, all)).toBeNull()- }- })-- it('does not refuse on an unknown directory', () => {- // A launcher that reports no cwd must never be blocked by a rule about directories.- expect(refuseDuplicateAgent([agent('agent-1', 'muse')], 'muse', null, all)).toBeNull()- expect(refuseDuplicateAgent([agent('agent-1', 'muse', null)], 'muse', CWD, all)).toBeNull()- })-- it('tells the person in the pane what happened and what to do', () => {- // A refusal that prints nothing reads as a broken CLI — which is exactly what shipped first: the- // launcher exited 0 in silence, because the daemon closes the socket ~2ms after the `exit` frame and- // the close path ended the process before the post-ack check could run.- const reason = refuseDuplicateAgent([agent('agent-1', 'muse')], 'muse', CWD, all)- const lines = refusalMessage(reason ?? undefined)- expect(lines[0]).toContain(CWD) // what, and where- expect(lines.join('\n')).toMatch(/different directory/) // and the way out- expect(lines).toHaveLength(3)- })-- it('still says something useful when the daemon sends no reason', () => {- expect(refusalMessage(undefined)[0]).toMatch(/refused/)- })-- it('sees through a symlink, so one directory under two names is still one directory', () => {- // `/tmp` is itself a symlink to `/private/tmp` on macOS, which is why string equality is not enough.- const real = mkdtempSync(join(tmpdir(), 'dup-'))- const link = `${real}-link`- try {- symlinkSync(real, link)- expect(sameDirSync(real, link)).toBe(true)- expect(refuseDuplicateAgent([agent('agent-1', 'muse', real)], 'muse', link, all)).not.toBeNull()- } finally {- rmSync(link, { force: true })- rmSync(real, { recursive: true, force: true })- }- })-})diff --git a/cli/src/lib/duplicateAgent.ts b/cli/src/lib/duplicateAgent.tsdeleted file mode 100644index 54d145c2c..000000000--- a/cli/src/lib/duplicateAgent.ts+++ /dev/null@@ -1,78 +0,0 @@-/**- * One muse agent per directory.- *- * Muse is the only engine that hands back NO identity for the session it opens. Measured, and every other- * channel ruled out: no hook fires (in `exec` or the TUI); `MUSE_CURRENT_SESSION_LOG` is something muse- * sets for its own children, not something it reads from us; `MUSE_SESSIONS` moves nothing; `--workspace`- * is realpath'd before it is recorded, so handing each agent its own symlink collapses to one string.- *- * So binding rests entirely on `workspace_root`, and two muse agents in one directory make it ambiguous- * forever: `fileEngineSession` sees two equally valid candidates and — correctly — refuses both, leaving- * NEITHER agent able to stream. The alternative was a per-agent `XDG_DATA_HOME`, the one thing that does- * isolate muse; it was rejected because an agent id is minted fresh on every launch, so each relaunch- * would open an empty history and strand the previous one's sessions, memory and cron.- *- * Turning the second agent away is the honest trade: nothing that worked stops working, and the user gets- * a sentence instead of an agent that silently never streams.- */--import { realpathSync } from 'fs'-import type { AgentEngine } from '../engines/types.js'--/** Engines that cannot tell two agents in one directory apart. Deliberately a list of one. */-const ONE_PER_DIRECTORY: ReadonlySet<string> = new Set<AgentEngine>(['muse'])--/** `sameDir` from sessionRepair without the await — the launcher handshake is synchronous, and this runs- * once per launch. `/tmp` vs `/private/tmp` is the case raw string equality misses. */-export function sameDirSync(a: string, b: string): boolean {- if (a === b) return true- const real = (p: string): string => { try { return realpathSync(p) } catch { return p } }- return real(a) === real(b)-}--/**- * What the person in the pane reads when their launch is turned away.- *- * The REASON comes from the daemon (it owns the rule); the launcher only adds what to do about it. Three- * lines, because a bare refusal reads like a broken CLI: what happened, why it has to be that way, and- * the way forward.- */-export function refusalMessage(reason: string | undefined): string[] {- return [- `harness: ${reason || 'this agent was refused by the machine'}`,- ' Two agents in one directory cannot be told apart, so only one can run here.',- ' Close the other one, or start this agent in a different directory.',- ]-}--export interface AgentLocation { agentId: string; engine: string; cwd?: string | null }--export interface DuplicateCheck {- /** The asking launcher's own agent id. It RECONNECTS under the same one, so it must never block itself. */- selfId: string- /** Whether an agent id still has a launcher on the socket. */- isLive: (agentId: string) => boolean-}--/**- * The message to turn a launcher away with, or null to let it through.- *- * `known` is the registry as-is. Both filters below are load-bearing, and were learned by breaking it:- * the registry is PERSISTED, so a restarted daemon starts out holding agents that may be long gone, and a- * launcher reconnects under the id it already owns. Reading that list literally refused the very- * launchers the rule exists to protect — measured: a daemon restart killed two live muse panes, each- * turned away by its own saved entry, because `exit` means exactly what it says.- */-export function refuseDuplicateAgent(- known: readonly AgentLocation[],- engine: string,- cwd: string | null | undefined,- { selfId, isLive }: DuplicateCheck,-): string | null {- if (!ONE_PER_DIRECTORY.has(engine) || !cwd) return null- const taken = known.some((agent) => agent.engine === engine- && agent.agentId !== selfId- && isLive(agent.agentId)- && agent.cwd && sameDirSync(agent.cwd, cwd))- return taken ? `a ${engine} agent is already running in ${cwd} — one ${engine} agent per directory` : null-}diff --git a/cli/src/lib/engineBin.spec.ts b/cli/src/lib/engineBin.spec.tsindex edf9e91fd..8fedab72f 100644--- a/cli/src/lib/engineBin.spec.ts+++ b/cli/src/lib/engineBin.spec.ts@@ -1,34 +1,21 @@import { describe, expect, it } from 'vitest'-import { ENGINES, aliasesFor, engineCommand, resolveEngine } from './engineBin.js'+import { ENGINE_CLI_COMMANDS, ENGINES } 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'])+describe('canonical engine CLI commands', () => {+ it('keeps the user-facing 12-engine command contract exact and ordered', () => {+ expect(ENGINES.map((engine) => [engine, ENGINE_CLI_COMMANDS[engine]])).toEqual([+ ['claude', 'claude'],+ ['codex', 'codex'],+ ['cursor', 'agent'],+ ['opencode', 'opencode'],+ ['pi', 'pi'],+ ['hermes', 'hermes'],+ ['commandcode', 'cmd'],+ ['devin', 'devin'],+ ['muse', 'muse'],+ ['amp', 'amp'],+ ['kilo', 'kilo'],+ ['grok', 'grok'],+ ])})})diff --git a/cli/src/lib/engineBin.ts b/cli/src/lib/engineBin.tsindex 7c06cce43..8c1abb620 100644--- a/cli/src/lib/engineBin.ts+++ b/cli/src/lib/engineBin.ts@@ -1,6 +1,6 @@/*** 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`).+ * (`oneshot.ts`) plus process discovery and user-facing command hints.** 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@@ -10,82 +10,42 @@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. */+/** Every engine the adapter can discover and drive. */export const ENGINES: readonly AgentEngine[] = ['claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin', 'muse', 'amp', 'kilo', 'grok',] 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 — `harness cmd` must mean Command Code, not "unknown command".- * Verified on disk: command-code ships `commandcode`/`command-code`/`cmd`/`cmdc` (all the same file),- * Cursor's CLI is installed as `agent` / `cursor-agent`, and `@kilocode/cli` declares- * `bin: { kilo, kilocode }` — two names for one file, with `kilo` first and used throughout its help.- */-const ENGINE_ALIASES: Readonly<Record<string, AgentEngine>> = {- cmd: 'commandcode',- cmdc: 'commandcode',- 'command-code': 'commandcode',- agent: 'cursor',- 'cursor-agent': 'cursor',- kilocode: 'kilo',-}--/**- * 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 `harness cmd`.- */-const PRIMARY_COMMAND: Partial<Record<AgentEngine, string>> = {+/** Public vendor command shown to users and matched by the real-binary smoke matrix. */+export const ENGINE_CLI_COMMANDS: Readonly<Record<AgentEngine, string>> = {+ claude: 'claude',+ codex: 'codex',+ cursor: 'agent',+ opencode: 'opencode',+ pi: 'pi',+ hermes: 'hermes',commandcode: 'cmd',-}--/** What to print as `harness <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)+ devin: 'devin',+ muse: 'muse',+ amp: 'amp',+ kilo: 'kilo',+ grok: 'grok',}export function engineBin(engine: AgentEngine): string {switch (engine) {- case 'claude': return env.CLAUDE_PATH || 'claude'- case 'codex': return process.env.CODEX_PATH || 'codex'+ case 'claude': return env.CLAUDE_PATH || ENGINE_CLI_COMMANDS.claude+ case 'codex': return process.env.CODEX_PATH || ENGINE_CLI_COMMANDS.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'- case 'muse': return env.MUSE_PATH || 'muse'- case 'amp': return env.AMP_PATH || 'amp'- case 'kilo': return env.KILO_PATH || 'kilo'- case 'grok': return env.GROK_PATH || 'grok'+ case 'cursor': return env.CURSOR_PATH || ENGINE_CLI_COMMANDS.cursor+ case 'opencode': return env.OPENCODE_PATH || ENGINE_CLI_COMMANDS.opencode+ case 'pi': return env.PI_PATH || ENGINE_CLI_COMMANDS.pi+ case 'hermes': return env.HERMES_PATH || ENGINE_CLI_COMMANDS.hermes+ // command-code's package `bin` lists `cmd` first and its README uses it.+ case 'commandcode': return env.COMMANDCODE_PATH || ENGINE_CLI_COMMANDS.commandcode+ case 'devin': return env.DEVIN_PATH || ENGINE_CLI_COMMANDS.devin+ case 'muse': return env.MUSE_PATH || ENGINE_CLI_COMMANDS.muse+ case 'amp': return env.AMP_PATH || ENGINE_CLI_COMMANDS.amp+ case 'kilo': return env.KILO_PATH || ENGINE_CLI_COMMANDS.kilo+ case 'grok': return env.GROK_PATH || ENGINE_CLI_COMMANDS.grok}}diff --git a/cli/src/lib/enginePermissions.spec.ts b/cli/src/lib/enginePermissions.spec.tsdeleted file mode 100644index 1f1b893b2..000000000--- a/cli/src/lib/enginePermissions.spec.ts+++ /dev/null@@ -1,80 +0,0 @@-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'],- // Muse's `--yolo` also trusts the workspace for the run, so one flag clears approval, sandbox and- // trust in one go — measured from `muse --help`, 0.1.0-R708.1.- muse: ['--yolo'],- // Amp's flag is UNDOCUMENTED — not in `--help`, found in the binary — and verified three ways on- // 0.0.1786064749: an unknown flag is rejected while this one is accepted, an `ask` rule blocks the- // tool without it ("blocked by a permissions rule"), and the same command runs with it.- amp: ['--dangerously-allow-all'],- // Kilo adds NOTHING, and the empty array is the assertion — it is a measurement, not an omission.- // `kilo run` documents `--auto` and `--dangerously-skip-permissions`, but the launcher starts the- // TUI, and on a real TTY (with a control: bare `kilo` starts, `kilo --auto` prints usage and exits)- // the root command rejects both. Adding either would stop the agent starting at all. The recap- // one-shot DOES pass `--auto`, because it invokes the `run` subcommand — see lib/oneshot.ts.- kilo: [],- // Documented by Grok 1.0.0 and reflected in the live TUI footer as `always-approve`.- grok: ['--always-approve'],- })- })-- 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([])- expect(permissionArgsFor('grok', ['--permission-mode', 'auto'])).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.tsdeleted file mode 100644index 297cabc57..000000000--- a/cli/src/lib/enginePermissions.ts+++ /dev/null@@ -1,181 +0,0 @@-/**- * 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'] },- },- /**- * Kilo adds NOTHING, and this is the one place it diverges hardest from the opencode it forked.- *- * `kilo run` documents BOTH `--auto` and `--dangerously-skip-permissions`, so the flags exist on the- * binary — but they belong to the `run` subcommand, and the launcher starts the TUI (`kilo`), not `run`.- * Measured on a real TTY inside tmux, with a control: bare `kilo` starts the TUI, while `kilo --auto`- * prints the usage block and exits. Adding the flag anyway would not loosen permissions, it would stop- * the agent from starting at all.- *- * Note the non-TTY form cannot answer this question: with stdin closed, `kilo --auto`,- * `kilo --dangerously-skip-permissions` and an invented flag all print byte-identical usage, so the- * usual unknown-flag test reads as "rejected" for real flags too. The TTY is the only place it shows.- *- * `owned` still lists both spellings: a user who types one has chosen the axis, and nothing should be- * appended on top of that if this table ever gains an `add`.- */- kilo: {- add: [],- owned: { permission: ['--auto', '--dangerously-skip-permissions'] },- },- // 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'] },- },- // `--yolo` is muse's own name for the same thing, and it does three jobs at once: no approval prompts,- // no sandbox, and trust this workspace for the run. The finer flags are listed as owned so a user who- // passes one of them keeps their choice instead of getting ours on top.- muse: {- add: [{ axis: 'permission', args: ['--yolo'] }],- owned: { permission: ['--yolo', '--disable-approval', '--disable-sandbox', '--trust-workspace', '--approval-mode'] },- },- // `--dangerously-allow-all` is UNDOCUMENTED — absent from `--help`, found in the binary's strings — and- // it is real. Measured all three ways on 0.0.1786064749: an unknown flag is rejected outright- // (`error: unknown option`) while this one is accepted; with an `ask shell_command` rule in settings and- // no flag the tool is refused mid-turn ("blocked by a permissions rule … rule 0: ask shell_command");- // with the flag the same command runs and returns its output.- //- // That refusal is why the flag matters: Amp does not stall waiting for someone, it tells the model no- // and carries on, so an unattended agent produces a turn that quietly did nothing. There is no config- // edit here either — the rules live in `amp.permissions` in settings.json, which this launcher leaves- // alone. A user who passes the flag themselves keeps their own choice.- amp: {- add: [{ axis: 'permission', args: ['--dangerously-allow-all'] }],- owned: { permission: ['--dangerously-allow-all'] },- },- // `--always-approve` is Grok's documented unattended mode. The other policy switches are owned so- // an explicit user choice is never overridden by the launcher default.- grok: {- add: [{ axis: 'permission', args: ['--always-approve'] }],- owned: {- permission: [- '--always-approve', '--permission-mode', '--allow', '--deny', '--tools', '--disallowed-tools',- ],- },- },-}--/** 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/hooks.ts b/cli/src/lib/hooks.tsindex b4124eed9..d602c1c74 100644--- a/cli/src/lib/hooks.ts+++ b/cli/src/lib/hooks.ts@@ -11,7 +11,6 @@ import { homedir } from 'os'import { fileURLToPath } from 'url'import { env } from '../config/env.js'import { VERSION } from '../version.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')@@ -27,9 +26,9 @@ 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.+// SessionStart/UserPromptSubmit bind mutable engine-session metadata to the process agent. SessionEnd+// only asks discovery to reconcile: the process, not the hook, owns the tile lifetime. UserPromptSubmit+// is the CATCH hook, so a SessionStart missed because the adapter started late is repaired on first input.// 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).@@ -60,6 +59,7 @@ function command(port: number, engine: 'claude' | 'codex' | 'cursor' | 'hermes''--codex-home', shellQuote(env.CODEX_HOME),'--grok-home', shellQuote(env.GROK_HOME),'--cursor-home', shellQuote(env.CURSOR_HOME),+ '--hermes-home', shellQuote(env.HERMES_HOME),'--commandcode-home', shellQuote(env.COMMANDCODE_HOME),'--devin-home', shellQuote(env.DEVIN_HOME),...(engine !== 'claude' ? ['--engine', engine] : []),@@ -282,18 +282,13 @@ const KILO_PLUGIN_PATH = join(env.KILO_PLUGIN_DIR, 'launcher-register.js')*/function forkPluginSource(engine: 'opencode' | 'kilo', port: number): string {const product = engine === 'kilo' ? 'Kilo' : 'OpenCode'- return `// launcher-register — auto-installed by the machine adapter. Registers this ${product} session with the+ return `// session-register — auto-installed by the machine adapter. Binds this ${product} session to the// local machine daemon (127.0.0.1:${port}) so it can be mirrored to web/device. No-op if machine isn't running.export const MachineRegister = async ({ directory, worktree, project }) => {const seen = new Set()const post = async (sessionID) => {const pane = process.env.TMUX_PANE- // The launcher (\`harness ${engine}\`) 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+ if (!pane || !sessionID || seen.has(sessionID)) returnseen.add(sessionID)try {await fetch("http://127.0.0.1:${port}/api/hook/session-start", {@@ -302,7 +297,6 @@ export const MachineRegister = async ({ directory, worktree, project }) => {body: JSON.stringify({engine: "${engine}",pluginVersion: ${JSON.stringify(VERSION)},- launcherId,sessionId: sessionID,cwd: directory || worktree || (project && project.worktree) || null,tmuxPane: pane,@@ -556,7 +550,7 @@ const PI_EXTENSION_PATH = join(env.PI_HOME, 'agent', 'extensions', 'launcher-reg* `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+ return `// session-register — auto-installed by the machine adapter. Binds this Pi session to the local// machine daemon (127.0.0.1:${port}) so it can be mirrored to web/device. No-op if machine isn't running.import { existsSync } from "node:fs";import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";@@ -568,12 +562,6 @@ export default function (pi: ExtensionAPI) {const register = async (ctx: any) => {const pane = process.env.TMUX_PANE;if (!pane) return; // tmux-only, like every other engine- // 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.@@ -589,7 +577,6 @@ export default function (pi: ExtensionAPI) {body: JSON.stringify({engine: "pi",pluginVersion: ${JSON.stringify(VERSION)},- launcherId,sessionId,transcriptPath: ready ? file : undefined,cwd: ctx?.cwd ?? undefined,@@ -656,12 +643,13 @@ const AMP_PLUGIN_PATH = join(env.AMP_PLUGIN_DIR, 'launcher-register.ts')* messages, so without that key every event would re-emit the whole tail of the conversation.** Being a SYSTEM plugin it loads in every `amp` the user runs, including ones this adapter knows nothing- * about. The `TMUX_PANE` + `MACHINE_ID` guard is what keeps it inert there — same rule as pi/opencode.+ * about. The `TMUX_PANE` guard keeps standalone sessions inert; the daemon additionally proves that the+ * pane contains the matching top-level Amp process before accepting a binding.*/function ampPluginSource(port: number, sessionsDir: string): string {- return `// launcher-register — auto-installed by the machine adapter. Registers this Amp thread with the local+ return `// session-register — auto-installed by the machine adapter. Binds this Amp thread to the local// machine daemon (127.0.0.1:${port}) and writes the transcript the daemon tails, because Amp keeps none-// on disk. No-op unless started by \`harness amp\` (MACHINE_ID) inside tmux.+// on disk. No-op outside tmux.import { appendFileSync, existsSync, mkdirSync } from 'node:fs'import { join } from 'node:path'@@ -671,17 +659,11 @@ const SESSIONS_DIR = ${JSON.stringify(sessionsDir)}export default function (amp: any) {const pane = process.env.TMUX_PANE- // The launcher (\`harness amp\`) 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. An amp started outside- // the launcher inherits neither variable, which is exactly when this plugin must do nothing at all.- const launcherId = process.env.MACHINE_ID- if (!pane || !launcherId) return+ if (!pane) return// NOT \`process.cwd()\`: Bun runs a plugin with the PLUGIN's directory as its cwd, so that reports- // \`<project>/.amp/plugins\` (measured). \`harness amp\` exports the real one; \`PWD\` from the launching- // shell is the fallback for an amp the launcher did not start — which the MACHINE_ID guard above has- // already excluded, so it is only ever a belt-and-braces third choice.- const workdir = process.env.HARNESS_AGENT_CWD || process.env.PWD || process.cwd()+ // \`<project>/.amp/plugins\` (measured). \`PWD\` is inherited from the shell that launched plain Amp.+ const workdir = process.env.PWD || process.cwd()const emitted = new Set()// Turn ids already opened/closed. Amp re-dispatches a message it could not deliver, firing agent.start@@ -722,7 +704,6 @@ export default function (amp: any) {body: JSON.stringify({engine: 'amp',pluginVersion: ${JSON.stringify(VERSION)},- launcherId,sessionId: threadId,transcriptPath: file,cwd: workdir,@@ -901,30 +882,3 @@ function installForkPlugin(engine: 'opencode' | 'kilo', path: string, product: sconsole.error(`[hooks] failed to write ${product} 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 'kilo': installKiloPlugin(port); break- case 'pi': installPiExtension(port); break- case 'hermes': installHermesHooks(port); break- case 'commandcode': installCommandCodeHooks(port); break- case 'devin': installDevinHooks(port); break- case 'amp': installAmpPlugin(port); break- case 'grok': installGrokHooks(port); break- }-}diff --git a/cli/src/lib/kiloOneShot.spec.ts b/cli/src/lib/kiloOneShot.spec.tsindex a5d0908a0..568106685 100644--- a/cli/src/lib/kiloOneShot.spec.ts+++ b/cli/src/lib/kiloOneShot.spec.ts@@ -46,8 +46,7 @@ describe('kilo recap worker containment', () => {/*** `--auto` is required: without it a recap whose model reaches for any tool dies on kilo's own* auto-rejection ("run ended with an auto-rejected permission") and returns no text at all. It is valid- * on the `run` SUBCOMMAND only — the interactive TUI rejects it, which is why `enginePermissions` adds- * nothing for kilo.+ * on the `run` SUBCOMMAND only — Harness never applies it to the user's interactive TUI process.*/it('runs autonomously and asks for machine-readable output', () => {const { args } = kiloOneShotSpawn(undefined, {}, SCRATCH)diff --git a/cli/src/lib/launch.spec.ts b/cli/src/lib/launch.spec.tsdeleted file mode 100644index 93d7e1bd4..000000000--- a/cli/src/lib/launch.spec.ts+++ /dev/null@@ -1,563 +0,0 @@-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.tsdeleted file mode 100644index dcc26897a..000000000--- a/cli/src/lib/launch.ts+++ /dev/null@@ -1,525 +0,0 @@-/**- * `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 { refusalMessage } from './duplicateAgent.js'-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, engineCommand } 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 ✗ harness ${engineCommand(engine)} must run inside tmux.`,- '',- ' Start one, then run it again:',- ' tmux new -s work',- ` harness ${engineCommand(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 ${engineCommand(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 ${engineCommand(engine)}`)- }-- // A refusal has to be acted on the INSTANT it lands, not after the ack wait: the daemon closes the- // socket ~2ms behind the `exit` frame, and the close path ends this process — measured, the launcher- // exited 0 in silence with the check below never reached. Nothing has spawned yet at this point, so- // saying so and leaving IS the whole handling; once the engine exists, line ~478 takes this over with- // the teardown that stops it.- link.onExitRequested = (reason: string | undefined): never => fail(refusalMessage(reason))-- 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)- // The daemon can turn a launch away outright — today only "one muse agent per directory", where a- // second agent could never be told apart from the first. It arrives as `exit` in place of the ack, so- // there is no `opened` and `waitForAck` simply times out. Bail HERE, in the gap before the spawn: the- // engine has not started, so the pane returns to the shell instead of flashing a CLI that something- // else kills a moment later (which is what an older launcher, acting on this only after spawning, does).- if (link.exitRequested !== false) fail(refusalMessage(link.exitRequested || undefined))- 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,- // Muse's launcher forks a background self-update on every invocation and can replace both the- // script and the binary while the user is mid-session. Pin it: an agent must not change under- // the person using it.- ...(engine === 'muse' ? { MUSE_NO_AUTO_UPDATE: '1' } : {}),- // Amp's plugin runs under Bun with its own directory as `process.cwd()` — measured: it reported- // `<project>/.amp/plugins`, not the project. The transcript's `cwd` is what re-binds a session- // after a restart, so a wrong one there means an agent that can never be re-found. The launcher is- // standing in the right directory, so it simply says which one.- ...(engine === 'amp' ? { HARNESS_AGENT_CWD: process.cwd() } : {}),- },- })-- 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.tsdeleted file mode 100644index 6d068c4c8..000000000--- a/cli/src/lib/launcherProtocol.ts+++ /dev/null@@ -1,118 +0,0 @@-/**- * 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.tsdeleted file mode 100644index 237a3f6e6..000000000--- a/cli/src/lib/launcherSessions.ts+++ /dev/null@@ -1,145 +0,0 @@-/**- * 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/oneshot.ts b/cli/src/lib/oneshot.tsindex db00517bc..573d24149 100644--- a/cli/src/lib/oneshot.ts+++ b/cli/src/lib/oneshot.ts@@ -32,7 +32,7 @@ function claudeBin(): string {* 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.+ * itself, is left alone. The interactive vendor CLI does NOT use this — its pane can ask.*/export function trustDevinWorkspace(dir: string, onError?: (message: string) => void): void {const file = join(env.DEVIN_HOME, 'trusted_workspaces.json')@@ -640,13 +640,13 @@ class KiloWorker extends ProcessWorker {// prompt later. `--pure` skips external plugins (so the discovery plugin never self-registers this// ephemeral recap session). `--format json` streams one JSON envelope per line.//- // `--auto` is REQUIRED here and is not the same question as the launcher's permission table. Measured:+ // `--auto` is REQUIRED for this disposable worker only. Measured:// without it a recap run whose model reaches for any tool dies outright — kilo auto-rejects the// permission and ends the run (`run ended with an auto-rejected permission; pass --auto for// autonomous use`), emitting an `error` envelope and NO text. A summariser has no user to ask, and a// recap that returns nothing is the failure this flag prevents. Note the asymmetry that makes this// easy to get wrong: `--auto` is a valid flag of the `run` SUBCOMMAND, while the bare TUI rejects it- // — see `enginePermissions.ts`, where kilo therefore adds nothing.+ // — the interactive TUI remains entirely under the user's own permission configuration.mkdirSync(KILO_RECAP_DATA_DIR, { recursive: true })// `--dir` pins the workspace explicitly. Do NOT rely on the spawn `cwd` alone: kilo resolves its// project from `$PWD`, and `spawn({cwd})` does not rewrite that variable — the child inherits thediff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.tsindex 2641a3f87..3d56183e6 100644--- a/cli/src/lib/registry.spec.ts+++ b/cli/src/lib/registry.spec.ts@@ -2,9 +2,50 @@ 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'+import type { AgentEngine } from '../engines/types.js'+import type { ProcessIdentity, RegisteredSession, RegisterInput } from './registry.js'let dataDir = ''+const processIdentity = (pid: number) => ({+ pid,+ executable: 'claude',+ startMarker: `Mon Aug 10 10:00:${String(pid % 60).padStart(2, '0')} 2026`,+})++function registerProcess(+ registry: {+ byPaneEngine: (pane: string, engine: AgentEngine) => RegisteredSession | undefined+ openProcessAgent: (input: {+ agentId?: string+ engine: AgentEngine+ tmuxPane: string+ cwd?: string | null+ processIdentity: ProcessIdentity+ }) => unknown+ register: (input: RegisterInput) => {+ entry: RegisteredSession+ isNew: boolean+ evicted: string | null+ rebound: string | null+ } | null+ },+ input: RegisterInput,+) {+ const pane = String(input.tmuxPane ?? '')+ const engine = input.engine ?? 'claude'+ if (pane && !registry.byPaneEngine(pane, engine)) {+ registry.openProcessAgent({+ agentId: input.launcherId,+ engine,+ tmuxPane: pane,+ cwd: input.cwd,+ processIdentity: processIdentity(100 + Number(pane.slice(1) || 0)),+ })+ }+ return registry.register(input)+}+async function loadRegistryModule() {vi.resetModules()process.env.ADAPTER_DATA_DIR = dataDir@@ -35,7 +76,7 @@ describe('registry remote display names', () => {const { registry, projectDisplayName } = await loadRegistryModule()registry.load()- const registered = registry.register({ launcherId: 'h1', sessionId: 'session-1', transcriptPath, tmuxPane: '%1', cwd: '/tmp/demo' })+ const registered = registerProcess(registry, { 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 },@@ -91,7 +132,7 @@ describe('registry remote display names', () => {const { registry, projectDisplayName } = await loadRegistryModule()registry.load()- const registered = registry.register({+ const registered = registerProcess(registry, {launcherId: 'h1',sessionId: 'session-title',transcriptPath,@@ -125,7 +166,7 @@ describe('registry remote display names', () => {const { registry } = await loadRegistryModule()registry.load()- registry.register({ launcherId: 'h1', sessionId: 'session-3', transcriptPath, tmuxPane: '%3', cwd: '/tmp/demo' })+ registerProcess(registry, { 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({@@ -142,7 +183,7 @@ describe('registry remote display names', () => {const { registry } = await loadRegistryModule()registry.load()- registry.register({+ registerProcess(registry, {launcherId: 'h1',engine: 'codex',sessionId: 'codex-session',@@ -205,7 +246,7 @@ describe('registry remote display names', () => {expect(registry.get(parentId)?.transcriptPath).toBe(parentPath)expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))[0].transcriptPath).toBe(parentPath)- expect(registry.register({+ expect(registerProcess(registry, {launcherId: 'h1',engine: 'codex',sessionId: parentId,@@ -214,7 +255,7 @@ describe('registry remote display names', () => {})).toBeNull()})- it('clears stale process identity for lowercase Cursor sessionStart hooks', async () => {+ it('keeps the discovered process identity when a Cursor sessionStart omits it', async () => {const sessionId = '53d3843c-724e-47ff-ae3a-9fedfa328bba'const transcriptPath = join(dataDir,@@ -228,7 +269,7 @@ describe('registry remote display names', () => {writeFileSync(transcriptPath, '{}\n')const { registry } = await loadRegistryModule()registry.load()- registry.register({+ registerProcess(registry, {launcherId: 'h1',engine: 'cursor',sessionId,@@ -238,7 +279,7 @@ describe('registry remote display names', () => {hookEvent: 'beforeSubmitPrompt',})- const resumed = registry.register({+ const resumed = registerProcess(registry, {launcherId: 'h1',engine: 'cursor',sessionId,@@ -247,13 +288,13 @@ describe('registry remote display names', () => {hookEvent: 'sessionStart',})- expect(resumed?.entry.processIdentity).toBeNull()+ expect(resumed?.entry.processIdentity).toEqual({ pid: 100, executable: 'agent', startMarker: 'old' })})it('persists a pending Cursor session and attaches its exact transcript later', async () => {const { registry } = await loadRegistryModule()registry.load()- expect(registry.register({+ expect(registerProcess(registry, {launcherId: 'h1',engine: 'cursor',sessionId: '12345678-1234-1234-1234-123456789abc',@@ -275,7 +316,7 @@ describe('registry remote display names', () => {)mkdirSync(join(transcript, '..'), { recursive: true })writeFileSync(transcript, '{}\n')- const attached = registry.register({+ const attached = registerProcess(registry, {launcherId: 'h1',engine: 'cursor',sessionId: '12345678-1234-1234-1234-123456789abc',@@ -309,7 +350,7 @@ describe('registry model coercion', () => {writeFileSync(transcriptPath, '{}\n')const { registry } = await loadRegistryModule()registry.load()- registry.register({+ registerProcess(registry, {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,@@ -322,12 +363,12 @@ describe('registry model coercion', () => {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' })+ registerProcess(registry, { 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 })+ registerProcess(registry, { launcherId: 'h2', sessionId: 'm3', transcriptPath, tmuxPane: '%2', cwd: '/tmp/demo', model: 42 as unknown as string })expect(registry.get('m3')?.model).toBeNull()})})@@ -350,7 +391,7 @@ describe('a Command Code session without a transcript path', () => {process.env.COMMANDCODE_HOME = dataDirconst { registry } = await loadRegistryModule()registry.load()- const registered = registry.register({+ const registered = registerProcess(registry, {launcherId: 'h1',engine: 'commandcode',sessionId: 'ae93cc89-0dff-452a-a875-33b1516bbc80',@@ -371,7 +412,7 @@ describe('a Command Code session without a transcript path', () => {const reported = join(dataDir, 'projects', 'somewhere-else', 'reported.jsonl')mkdirSync(join(dataDir, 'projects', 'somewhere-else'), { recursive: true })writeFileSync(reported, '')- const registered = registry.register({+ const registered = registerProcess(registry, {launcherId: 'h1',engine: 'commandcode',sessionId: 'reported',@@ -404,7 +445,7 @@ describe('a Grok session before updates.jsonl exists', () => {it('derives the URL-encoded cwd path at SessionStart', async () => {const { registry } = await loadRegistryModule()registry.load()- const registered = registry.register({+ const registered = registerProcess(registry, {launcherId: 'h1',engine: 'grok',sessionId: '8184b11d-175e-46cb-9cee-cf41cafe70d2',@@ -423,7 +464,7 @@ describe('a Grok session before updates.jsonl exists', () => {})})-describe('agent identity: the launcher owns the agent, the session is bound to it', () => {+describe('agent identity: the process owns the agent, the session is bound to it', () => {beforeEach(() => {vi.useFakeTimers()dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-id-'))@@ -448,7 +489,7 @@ describe('agent identity: the launcher owns the agent, the session is bound to i// 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' })+ const res = registerProcess(registry, { 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')@@ -461,8 +502,8 @@ describe('agent identity: the launcher owns the agent, the session is bound to i// 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' })+ registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })+ const rot = registerProcess(registry, { 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@@ -475,46 +516,40 @@ describe('agent identity: the launcher owns the agent, the session is bound to iit('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' })+ registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })+ const again = registerProcess(registry, { 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.+ // `claude --resume <id>` in a second pane: the newest bind wins; both live process agents remain.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)+ registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })+ registerProcess(registry, { launcherId: 'agent-2', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%2', cwd: '/tmp/demo' })+ expect(registry.list()).toHaveLength(2)expect(registry.resolve('s1')?.agentId).toBe('agent-2')- expect(registry.byAgent('agent-1')).toBeUndefined()+ expect(registry.byAgent('agent-1')?.sessionId).toBe('')})- 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.+ it('ignores a legacy launcherId and binds to the discovered pane process', async () => {const { registry } = await loadRegistryModule()registry.load()+ registry.openProcessAgent({ agentId: 'process-agent', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })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(res?.entry.agentId).toBe('process-agent')+ expect(registry.resolve('old-launcher')).toBeUndefined()+ const rot = registry.register({ launcherId: 'different-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.+ it('creates an agent at process discovery, before any engine session exists', async () => {const { registry, projectDisplayName } = await loadRegistryModule()registry.load()- const opened = registry.openAgent({ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo' })+ const opened = registry.openProcessAgent({ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })expect(opened?.isNew).toBe(true)expect(opened?.entry.sessionId).toBe('')expect(registry.unbound().map((s) => s.agentId)).toEqual(['agent-1'])@@ -522,21 +557,19 @@ describe('agent identity: the launcher owns the agent, the session is bound to iexpect(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' })+ const bound = registerProcess(registry, { 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.+ it('re-observing the same runtime keeps the session it had already bound', async () => {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' })+ registry.openProcessAgent({ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })+ registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })+ const again = registry.openProcessAgent({ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })expect(again?.isNew).toBe(false)expect(again?.entry.sessionId).toBe('s1')expect(registry.list()).toHaveLength(1)@@ -545,7 +578,7 @@ describe('agent identity: the launcher owns the agent, the session is bound to iit('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' })+ registry.openProcessAgent({ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })const { registry: reloaded } = await loadRegistryModule()reloaded.load()expect(reloaded.byAgent('agent-1')?.sessionId).toBe('')@@ -558,17 +591,17 @@ describe('agent identity: the launcher owns the agent, the session is bound to i// 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' })+ registry.openProcessAgent({ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })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' })+ const bound = registerProcess(registry, { 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' })+ const resumed = registerProcess(registry, { launcherId: 'agent-2', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })expect(projectDisplayName(resumed!.entry)).toBe('Backend fix')})@@ -587,8 +620,9 @@ describe('agent identity: the launcher owns the agent, the session is bound to iregistry.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.+ // It is immediately rewritten without legacy ownership metadata.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' })+ expect(saved[0]).toMatchObject({ agentId: 'legacy-agent' })+ expect(saved[0]).not.toHaveProperty('launcherId')})})diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex ad405e27c..93bd4c2e9 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -1,8 +1,8 @@/**- * Registry of AGENTS — one per `harness <engine>` launch.+ * Registry of process-owned AGENTS — one per supported top-level engine process in a tmux pane.*- * 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+ * An agent is created the moment process discovery observes it and lives exactly as long as that process.+ * 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.*@@ -14,6 +14,7 @@*/import { mkdirSync, readFileSync, writeFileSync, renameSync, realpathSync, statSync } from 'fs'+import { randomUUID } from 'crypto'import { join, basename, dirname, relative } from 'path'import { uptime } from 'os'import { env } from '../config/env.js'@@ -41,9 +42,8 @@ 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.+ * It is minted when a top-level engine process is first discovered. The persisted process identity lets+ * the same UUID survive daemon restarts while the engine underneath rotates sessions (`/clear`, `/new`).*/agentId: string/**@@ -54,9 +54,8 @@ export interface RegisteredSession {/** When the CURRENT sessionId was bound (vs `registeredAt`, which is when the agent appeared). */boundAt: number | nullengine: 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+ /** Legacy launcher-owned snapshots may still contain this field. New records never write it. */+ launcherId?: stringtranscriptPath: string | nullprojectDir: stringcwd: string | null@@ -74,8 +73,7 @@ export interface RegisteredSession {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. */+ /** Accepted from old hook/plugin payloads for wire compatibility, but deliberately ignored. */launcherId?: stringsessionId?: stringtranscriptPath?: string@@ -183,9 +181,19 @@ class Registry {}}- /** 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). */+ private releaseBinding(entry: RegisteredSession): void {+ if (entry.sessionId && this.sessionIndex.get(entry.sessionId) === entry.agentId) {+ this.sessionIndex.delete(entry.sessionId)+ }+ entry.sessionId = ''+ entry.boundAt = null+ entry.transcriptPath = null+ entry.source = null+ entry.lastTranscriptAt = Date.now()+ }++ /** Load persisted process agents. Invalid session bindings are released without dropping their agent;+ * a reboot still drops all cached pane identities because no process can survive it. */load(): void {this.agents.clear()this.sessionIndex.clear()@@ -208,6 +216,7 @@ class Registry {typeof raw?.transcriptPath === 'string' && raw.transcriptPath? raw.transcriptPath: null+ let bound = typeof raw?.sessionId === 'string' && raw.sessionId !== ''let repairedCodexTranscript = falseif (engine === 'codex' && transcriptPath) {const meta = readCodexRolloutMeta(transcriptPath)@@ -217,41 +226,41 @@ class Registry {: nullif (!repaired || !validTranscriptPath('codex', repaired) || readCodexRolloutMeta(repaired)?.isSubagent) {changed = true- continue+ bound = false+ transcriptPath = null+ } else {+ console.log(`[registry] repaired Codex parent ${raw.sessionId.slice(0, 8)} transcript after child hook overwrite`)+ transcriptPath = repaired+ repairedCodexTranscript = true+ changed = true}- 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 !== ''+ // A process agent remains valid without a session. A missing/invalid transcript releases only the+ // binding so the discovery/store repair path can bind it again if appropriate.if (!bound) transcriptPath = null+ if (!pane) {+ changed = true+ continue+ }if (- !pane- || (bound && engine !== 'cursor' && engine !== 'opencode' && engine !== 'kilo' && engine !== 'pi' && engine !== 'hermes' && engine !== 'commandcode' && engine !== 'devin' && !transcriptPath)+ (bound && engine !== 'cursor' && engine !== 'opencode' && engine !== 'kilo' && engine !== 'pi' && engine !== 'hermes' && engine !== 'commandcode' && engine !== 'devin' && !transcriptPath)|| (bound && transcriptPath !== null && !validTranscriptPath(engine, transcriptPath))) {+ bound = false+ transcriptPath = nullchanged = 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+ // Old launcher-owned records used launcherId as the public id. Preserve it while process discovery+ // validates/adopts the live runtime, then save the record without the legacy ownership field.+ const legacyLauncherId = typeof raw?.launcherId === 'string' ? raw.launcherId : ''+ const agentId = typeof raw.agentId === 'string' && raw.agentId ? raw.agentId : legacyLauncherId+ if (!agentId) { changed = true; continue }if (agentId !== raw.agentId) changed = trueconst now = Date.now()const s: RegisteredSession = {- ...raw,agentId,- launcherId: agentId,- boundAt: typeof raw.boundAt === 'number' ? raw.boundAt : (raw.registeredAt ?? now),+ boundAt: bound ? (typeof raw.boundAt === 'number' ? raw.boundAt : (raw.registeredAt ?? now)) : null,engine,transcriptPath,title: titleDisplayName(typeof raw.title === 'string' ? raw.title : null),@@ -262,8 +271,13 @@ class Registry {? basename(dirname(transcriptPath)): (bound ? raw.sessionId : agentId),tmuxPane: pane,+ cwd: typeof raw.cwd === 'string' ? raw.cwd : null,+ source: bound && typeof raw.source === 'string' ? raw.source : null,cliVersion: typeof raw.cliVersion === 'string' ? raw.cliVersion : null,+ model: modelString(raw.model),processIdentity: validProcessIdentity(raw.processIdentity) ? raw.processIdentity : null,+ registeredAt: typeof raw.registeredAt === 'number' ? raw.registeredAt : now,+ updatedAt: typeof raw.updatedAt === 'number' ? raw.updatedAt : now,lastHookAt: typeof raw.lastHookAt === 'number' ? raw.lastHookAt : (raw.updatedAt ?? now),lastTranscriptAt: typeof raw.lastTranscriptAt === 'number' ? raw.lastTranscriptAt : (raw.updatedAt ?? now),}@@ -274,8 +288,9 @@ class Registry {|| raw.title !== s.title|| raw.lastHookAt == null|| raw.lastTranscriptAt == null+ || legacyLauncherId !== '') changed = true- // Two records claiming one agent id cannot both be right (the id is per launcher run); keep the+ // Two records claiming one agent id cannot both be right; keep the// one that registered last, exactly as a re-register would.const clash = this.agents.get(s.agentId)if (clash && clash.registeredAt > s.registeredAt) { changed = true; continue }@@ -299,29 +314,34 @@ class Registry {}}- /**- * 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 }):+ /** Create/adopt a process agent before any engine session exists. */+ openProcessAgent(input: {+ agentId?: string+ engine: AgentEngine+ tmuxPane: string+ cwd?: string | null+ processIdentity: ProcessIdentity+ }):{ 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)+ const { engine, tmuxPane, processIdentity } = input+ if (!tmuxPane || !PANE_RE.test(tmuxPane) || !validProcessIdentity(processIdentity)) return null+ const existing = [...this.agents.values()].find((agent) =>+ agent.tmuxPane === tmuxPane+ && agent.engine === engine+ && (!agent.processIdentity || (+ agent.processIdentity.pid === processIdentity.pid+ && agent.processIdentity.startMarker === processIdentity.startMarker+ )))if (existing) {existing.tmuxPane = tmuxPaneexisting.cwd = input.cwd ?? existing.cwd+ existing.processIdentity = processIdentityexisting.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.++ const agentId = input.agentId || randomUUID()let evicted: string | null = nullfor (const other of this.agents.values()) {if (other.tmuxPane === tmuxPane) { this.drop(other); evicted = other.sessionId || other.agentId; break }@@ -332,7 +352,6 @@ class Registry {sessionId: '',boundAt: null,engine,- launcherId: agentId,transcriptPath: null,projectDir: basename(input.cwd ?? '') || agentId,cwd: input.cwd ?? null,@@ -341,7 +360,7 @@ class Registry {title: null,model: null,cliVersion: null,- processIdentity: null,+ processIdentity,registeredAt: now,updatedAt: now,lastHookAt: now,@@ -352,7 +371,7 @@ class Registry {return { entry, isNew: true, evicted }}- /** Agents this launcher opened that have no engine session bound yet. */+ /** Discovered process agents that have no engine session bound yet. */unbound(): RegisteredSession[] {return this.list().filter((s) => !s.sessionId)}@@ -371,10 +390,10 @@ class Registry {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 === 'muse' || input.engine === 'amp' || input.engine === 'kilo' || input.engine === 'grok' ? 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 || ''+ // Hooks carry process metadata, not ownership. The already-discovered pane+engine process chooses the+ // agent; an optional legacy launcherId is intentionally ignored.+ const processAgent = pane ? this.byPaneEngine(pane, engine) : undefined+ const agentId = processAgent?.agentId ?? ''if (!sessionId|| !agentId@@ -391,23 +410,16 @@ class Registry {// `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.+ // A rotation: the same process agent and 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 }- }- }+ const evicted: string | null = rebound// 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.+ // newest bind wins; the old process agent remains visible but becomes unbound.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+ this.releaseBinding(stolenFrom)}// Command Code announces SessionStart BEFORE writing its transcript, and validTranscriptPath stats the@@ -428,7 +440,6 @@ class Registry {sessionId,boundAt: isNew ? now : existing?.boundAt ?? now,engine,- launcherId: agentId,transcriptPath: effectiveTranscriptPath,projectDir: engine === 'grok'? basename(input.cwd ?? existing?.cwd ?? '') || sessionId@@ -441,9 +452,7 @@ class Registry {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),+ processIdentity: validProcessIdentity(input.processIdentity) ? input.processIdentity : existing?.processIdentity ?? null,registeredAt: existing?.registeredAt ?? now,updatedAt: now,lastHookAt: now,@@ -463,6 +472,16 @@ class Registry {return true}+ /** Release only the mutable session binding; the process-backed agent remains addressable. */+ unbindSession(sessionId: string): boolean {+ const entry = this.bySession(sessionId)+ if (!entry) return false+ this.releaseBinding(entry)+ entry.updatedAt = Date.now()+ this.save()+ return true+ }+/** Drop an agent outright, bound or not. */removeAgent(agentId: string): boolean {const entry = this.agents.get(agentId)@@ -485,6 +504,10 @@ class Registry {return agentId ? this.agents.get(agentId) : undefined}+ byPaneEngine(tmuxPane: string, engine: AgentEngine): RegisteredSession | undefined {+ return [...this.agents.values()].find((entry) => entry.tmuxPane === tmuxPane && entry.engine === engine)+ }+/** 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 {@@ -533,7 +556,7 @@ class Registry {* 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,+ * another under the same live process in the same pane. 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.*/diff --git a/cli/src/lib/sessionInput.spec.ts b/cli/src/lib/sessionInput.spec.tsindex 3ce8d9ffc..c596827fa 100644--- a/cli/src/lib/sessionInput.spec.ts+++ b/cli/src/lib/sessionInput.spec.ts@@ -1,5 +1,5 @@import { afterEach, describe, expect, it, vi } from 'vitest'-import { acceptsInputBeforeSession, SessionInputController } from './sessionInput.js'+import { SessionInputController } from './sessionInput.js'import type { RegisteredSession } from './registry.js'function session(engine: 'claude' | 'codex' | 'cursor' | 'commandcode' = 'codex'): RegisteredSession {@@ -322,11 +322,3 @@ describe('SessionInputController', () => {controller.forget('s1')})})--describe('pre-session input', () => {- it('lets Grok receive the prompt that creates its session', () => {- expect(acceptsInputBeforeSession('grok')).toBe(true)- expect(acceptsInputBeforeSession('claude')).toBe(false)- expect(acceptsInputBeforeSession('muse')).toBe(false)- })-})diff --git a/cli/src/lib/sessionInput.ts b/cli/src/lib/sessionInput.tsindex ea49e84d5..00883dc47 100644--- a/cli/src/lib/sessionInput.ts+++ b/cli/src/lib/sessionInput.ts@@ -46,13 +46,6 @@ const SUBMIT_MAX_RETRIES = 2// prompt is in flight. Bounded so a truly wedged session eventually reverts to the retry/error path.const SUBMIT_MAX_OBSERVES = 5-/** Grok does not allocate a session until its first prompt is submitted. Holding that prompt until a- * session id exists deadlocks: UserPromptSubmit is the event that supplies the id. Inject it into the- * launcher's already-validated pane, then let the hook bind the resulting session. */-export function acceptsInputBeforeSession(engine: RegisteredSession['engine']): boolean {- return engine === 'grok'-}-interface QueuedInput {content: stringbytes: numberdiff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.tsindex 2e2791912..767a09d07 100644--- a/cli/src/lib/sessionRepair.ts+++ b/cli/src/lib/sessionRepair.ts@@ -1,24 +1,17 @@/**- * Find the session a live launcher is running, when the daemon has lost track of it.+ * Find the session a live discovered engine process is running, when no hook has bound one yet.*- * 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.+ * Process discovery can see an engine immediately, including after a daemon restart, but a session id is+ * owned by the engine and may not be present in argv. Ask the engine's own store which session belongs to+ * that pane's directory and process start time.** 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.)+ * see tmuxAgentDiscovery.)* - **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.+ * unbound until its next turn, which is recoverable — mis-binding is not.*/import { execFile } from 'child_process'@@ -105,7 +98,7 @@ function idFromFile(path: string): string {/*** 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+ * On macOS `/tmp` is a symlink to `/private/tmp`, so discovery 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`.*/@@ -169,8 +162,8 @@ async function fileEngineSession(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,+ // there hands it whatever session was last touched in this directory — measured: exit the engine,+ // run `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@@ -203,7 +196,7 @@ function quote(value: string): string {}/**- * The session a launcher's engine is running in `cwd`, or null when it cannot be said for certain.+ * The session a discovered engine process 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 adiff --git a/cli/src/lib/tmux.spec.ts b/cli/src/lib/tmux.spec.tsindex d5beb35e9..e2b4f7407 100644--- a/cli/src/lib/tmux.spec.ts+++ b/cli/src/lib/tmux.spec.ts@@ -1,413 +1,46 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { mkdtempSync, rmSync, writeFileSync } from 'fs'-import { tmpdir } from 'os'-import { join } from 'path'+import { describe, expect, it } from 'vitest'+import { engineProcessMatchScore, parseProcessRow, resumeSessionId } from './tmux.js'-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({+describe('tmux process primitives', () => {+ it('parses a process whose comm field contains spaces', () => {+ expect(parseProcessRow('4242 100 ⌘ Greeting Thu Jul 30 11:00:03 2026 cmd -r abcdef12-3456-7890-abcd-ef1234567890')).toEqual({pid: 4242,+ parentPid: 100,executable: '⌘ Greeting',startMarker: 'Thu Jul 30 11:00:03 2026',+ args: 'cmd -r abcdef12-3456-7890-abcd-ef1234567890',})})- 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('scores muse through the launcher that execs into a versioned binary', async () => {- const { engineProcessMatchScore } = await loadModules()- // `~/.local/bin/muse` is a bash launcher that `exec`s `muse-bin-<version>`, so the pane process is- // usually the versioned name — measured on 0.1.0-R708.1. Without this branch muse falls through to- // the claude matcher, fails runtime validation, and the reaper evicts every live muse session.- expect(engineProcessMatchScore({ executable: 'muse', args: 'muse' }, 'muse')).toBe(3)+ it('recognises stable installed binary forms', () => {+ // Exact canonical/configured commands outrank vendor package-layout heuristics.+ expect(engineProcessMatchScore({ executable: 'devin', args: 'devin' }, 'devin')).toBe(4)expect(engineProcessMatchScore({ executable: 'muse-bin-0.1.0-R708.1', args: 'muse-bin-0.1.0-R708.1' }, 'muse')).toBe(3)- expect(engineProcessMatchScore({ executable: 'claude', args: 'claude' }, 'muse')).toBe(0)+ expect(engineProcessMatchScore({ executable: '/Users/demo/.grok/bin/grok', args: 'grok' }, 'grok')).toBe(4)})- it('matches the Grok binary and its installed path', async () => {- const { engineProcessMatchScore } = await loadModules()- expect(engineProcessMatchScore({ executable: 'grok', args: 'grok --always-approve' }, 'grok')).toBe(3)- expect(engineProcessMatchScore({ executable: '/Users/demo/.grok/bin/grok', args: 'grok' }, 'grok')).toBe(3)- expect(engineProcessMatchScore({ executable: 'claude', args: 'claude' }, 'grok')).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.+ it('extracts only explicit resume ids', () => {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'))+ expect(resumeSessionId('hermes', '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('kilo', 'kilo --session ses_024a007fdffe11yG68JPxsHJly'))+ .toBe('ses_024a007fdffe11yG68JPxsHJly')+ expect(resumeSessionId('pi', 'pi --session-id 53d3843c-724e-47ff-ae3a-9fedfa328bba'))+ .toBe('53d3843c-724e-47ff-ae3a-9fedfa328bba')+ expect(resumeSessionId('commandcode', 'cmd --resume 53d3843c-724e-47ff-ae3a-9fedfa328bba'))+ .toBe('53d3843c-724e-47ff-ae3a-9fedfa328bba')+ expect(resumeSessionId('muse', 'muse resume 53d3843c-724e-47ff-ae3a-9fedfa328bba'))+ .toBe('53d3843c-724e-47ff-ae3a-9fedfa328bba')+ expect(resumeSessionId('amp', 'amp threads continue T-019fda49-724e-47ff-ae3a-9fedfa328bba'))+ .toBe('T-019fda49-724e-47ff-ae3a-9fedfa328bba')+ expect(resumeSessionId('grok', 'grok -r 53d3843c-724e-47ff-ae3a-9fedfa328bba'))+ .toBe('53d3843c-724e-47ff-ae3a-9fedfa328bba')expect(resumeSessionId('commandcode', 'cmd -r Greeting')).toBeNull()- expect(resumeSessionId('grok', 'grok --resume 98ee3dac-175e-46cb-9cee-cf41cafe70d2'))- .toBe('98ee3dac-175e-46cb-9cee-cf41cafe70d2')- expect(resumeSessionId('grok', 'grok -r 98ee3dac-175e-46cb-9cee-cf41cafe70d2'))- .toBe('98ee3dac-175e-46cb-9cee-cf41cafe70d2')-- // `--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([])+ expect(resumeSessionId('codex', 'codex resume 53d3843c-724e-47ff-ae3a-9fedfa328bba')).toBeNull()+ expect(resumeSessionId('devin', 'devin --resume 53d3843c-724e-47ff-ae3a-9fedfa328bba')).toBeNull()})})diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.tsindex da201bef9..984f55cfb 100644--- a/cli/src/lib/tmux.ts+++ b/cli/src/lib/tmux.ts@@ -1,39 +1,9 @@-/**- * 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).- */+/** tmux process matching, runtime validation, pane capture, and input injection. */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) })- })- })-}+import { engineBin } from './engineBin.js'function cleanPaneTitle(title: string): string | null {const cleaned = title@@ -61,25 +31,55 @@ export function listPaneTitles(): Promise<Map<string, string>> {})}-interface ProcessRow extends ProcessIdentity {+export interface ProcessRow extends ProcessIdentity {parentPid: numberargs: string}-interface TmuxPaneProcess {- tmuxPane: string- rootPid: number- cwd: string+function argvTokens(args: string): string[] {+ return (args.match(/"[^"]*"|'[^']*'|\S+/g) ?? []).map((token) => {+ const quoted = (token.startsWith('"') && token.endsWith('"')) || (token.startsWith("'") && token.endsWith("'"))+ return quoted ? token.slice(1, -1) : token+ })}-export interface TmuxResume {- engine: RegisteredSession['engine']- sessionId: string- tmuxPane: string- cwd: string- processIdentity: ProcessIdentity+/**+ * Return only the executable/script portion of argv, never prompt text or later CLI arguments.+ *+ * Looking for an engine word anywhere in `ps args` is unsafe: `python worker.py "compare codex and+ * claude"` is not two coding agents. Package-manager installs commonly leave `node`, `bun`, Python, or a+ * shell in `comm`, so for those interpreters the first non-option token is the real entrypoint. Absolute+ * prefixes are deliberately retained only for suffix/package-layout checks and are never hard-coded.+ */+function processEntrypoint(args: string): string {+ const tokens = argvTokens(args)+ if (!tokens.length) return ''+ let index = 0+ let command = basename(tokens[index]).toLowerCase()+ if (command === 'env') {+ index+++ while (index < tokens.length && (tokens[index].startsWith('-') || /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[index]))) index+++ command = basename(tokens[index] ?? '').toLowerCase()+ }+ if (!/^(?:node|nodejs|bun|deno|python(?:\d+(?:\.\d+)*)?|bash|zsh|sh)$/.test(command)) return tokens[index] ?? ''++ index+++ const optionsWithValue = new Set(['-r', '--require', '--loader', '--import', '--conditions', '--inspect-port'])+ const inlineCodeOptions = new Set(['-c', '--command', '-e', '--eval', '--print'])+ while (index < tokens.length) {+ const token = tokens[index]+ if (token === '--') { index++; break }+ if (token === '-m' && index + 1 < tokens.length) return tokens[index + 1]+ // Inline shell/Node/Python source is not an executable entrypoint. Its text can legitimately mention+ // an engine command; the real child process, if one is launched, will be discovered from its own row.+ if (inlineCodeOptions.has(token)) return ''+ if (!token.startsWith('-')) break+ index += optionsWithValue.has(token) && index + 1 < tokens.length ? 2 : 1+ }+ return tokens[index] ?? ''}+/*** One `ps -axo pid=,ppid=,comm=,lstart=,args=` line → a row.*@@ -121,26 +121,6 @@ function processRows(): Promise<ProcessRow[] | null> {})}-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) => {@@ -155,77 +135,84 @@ 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()+ const entrypoint = processEntrypoint(row.args).toLowerCase()+ const entrybase = basename(entrypoint).toLowerCase()+ // A user may point an engine at a symlink/custom install through `<ENGINE>_PATH`. Treat that configured+ // executable exactly like the vendor command without baking its machine-specific directory into rules.+ const configured = engineBin(engine).toLowerCase()+ const configuredBase = basename(configured).toLowerCase()+ if (configuredBase && (executable === configuredBase || entrybase === configuredBase+ || row.executable.toLowerCase() === configured || entrypoint === configured)) return 4if (engine === 'codex') {- if (executable === 'codex') return 3- return /(^|[\/\s])codex(?:[\s]|$)/.test(haystack) ? 1 : 0+ if (executable === 'codex' || entrybase === 'codex') return 3+ // npm/pnpm/bun global installs may leave node as `comm`; match the package entrypoint without+ // caring which prefix or package manager store contains it.+ return /@openai[\/\\]codex[\/\\]bin[\/\\]codex(?:\.js)?$/.test(entrypoint) ? 2 : 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 (executable === 'agent' || executable === 'cursor-agent' || entrybase === 'agent' || entrybase === 'cursor-agent') return 3+ return /cursor-agent[\/\\]versions[\/\\][^/\\]+[\/\\]index\.js$/.test(entrypoint) ? 2 : 0}if (engine === 'opencode') {- if (executable === 'opencode') return 3- return /(^|[\/\s])opencode(?:[\s]|$)/.test(haystack) ? 1 : 0+ if (executable === 'opencode' || executable === 'opencode.exe' || entrybase === 'opencode' || entrybase === 'opencode.exe') return 3+ return /opencode-ai[\/\\]bin[\/\\]opencode(?:\.exe)?$/.test(entrypoint) ? 2 : 0}if (engine === 'kilo') {// `@kilocode/cli` installs the same file under both names, and kilo's own installer puts a second- // copy at ~/.kilo/bin/kilo — so match either spelling as the executable, and fall back to the argv- // scan for the wrapper form. `kilocode` is listed first so the weak regex below cannot claim it.- if (executable === 'kilo' || executable === 'kilocode') return 3- return /(^|[\/\s])kilocode?(?:[\s]|$)/.test(haystack) ? 1 : 0+ // copy at ~/.kilo/bin/kilo. The npm install measured on 2026-08-10 is a shallow+ // `node /usr/local/bin/kilo` wrapper with a `.kilo` child, so recognize both public command names+ // in argv while depth selection keeps the wrapper as the process-agent identity.+ if (executable === 'kilo' || executable === 'kilocode' || executable === '.kilo'+ || entrybase === 'kilo' || entrybase === 'kilocode' || entrybase === '.kilo') return 3+ return /@kilocode[\/\\]cli[\/\\]bin[\/\\](?:\.kilo|kilo|kilocode)$/.test(entrypoint) ? 2 : 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 (/^\s*⌘(?:\s|$)/.test(row.executable) || /^\s*⌘(?:\s|$)/.test(row.args)) return 3+ if (executable === 'cmd' || executable === 'commandcode' || executable === 'command-code'+ || entrybase === 'cmd' || entrybase === 'commandcode' || entrybase === 'command-code') return 3+ return /command-code[\/\\]dist[\/\\]index\.mjs$/.test(entrypoint) ? 2 : 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 (executable === 'devin' || entrybase === 'devin') return 3+ return /devin[\/\\]cli[\/\\]_versions[\/\\][^/\\]+[\/\\]bin[\/\\]devin$/.test(entrypoint) ? 2 : 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 (executable === 'hermes' || entrybase === 'hermes') return 3+ return /hermes-agent[\/\\]hermes$/.test(entrypoint) || /^(?:hermes|hermes_cli)(?:\.|$)/.test(entrypoint) ? 2 : 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 === 'pi' || entrybase === 'pi') return 3+ return /pi-coding-agent[\/\\]dist[\/\\]cli\.js$/.test(entrypoint) ? 2 : 0}if (engine === 'muse') {// `~/.local/bin/muse` is a bash launcher that `exec`s the real binary, so the pane process is// `muse-bin-<version>` — the bare name only appears before the exec.- if (executable === 'muse' || /^muse-bin-/.test(executable)) return 3- return /(^|[\/\s])muse(?:-bin-[^\s]+)?(?:[\s]|$)/.test(haystack) ? 1 : 0+ if (executable === 'muse' || /^muse-bin-/.test(executable) || entrybase === 'muse' || /^muse-bin-/.test(entrybase)) return 3+ return 0}if (engine === 'amp') {// `~/.local/bin/amp` symlinks to `~/.amp/bin/amp`, a single compiled binary that does NOT re-exec:// measured live, the pane process is `amp` with argv `amp` and no children at all.- if (executable === 'amp') return 3- if (/\.amp[\/\\]bin[\/\\]amp(?:\s|$)/.test(haystack)) return 3- return /(^|[\/\s])amp(?:[\s]|$)/.test(haystack) ? 1 : 0+ if (executable === 'amp' || entrybase === 'amp') return 3+ return /\.amp[\/\\]bin[\/\\]amp$/.test(entrypoint) ? 2 : 0}if (engine === 'grok') {// Grok ships as a single binary at ~/.grok/bin/grok and keeps the bare executable name in tmux.- if (executable === 'grok') return 3- if (/\.grok[\/\\]bin[\/\\]grok(?:\s|$)/.test(haystack)) return 3- return /(^|[\/\s])grok(?:[\s]|$)/.test(haystack) ? 1 : 0+ if (executable === 'grok' || entrybase === 'grok') return 3+ return /\.grok[\/\\]bin[\/\\]grok$/.test(entrypoint) ? 2 : 0}- if (executable === 'claude') return 3- return /(^|[\/\s])claude(?:[\s]|$)/.test(haystack) ? 1 : 0+ if (executable === 'claude' || entrybase === 'claude') return 3+ return /@anthropic-ai[\/\\]claude-code[\/\\]cli\.js$/.test(entrypoint) ? 2 : 0}function selectEngineProcess(@@ -246,7 +233,7 @@ function selectEngineProcess(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))) {+ if (row && score > 0 && (!best || current.depth < best.depth || (current.depth === best.depth && score > best.score))) {best = { row, depth: current.depth, score }}for (const child of children.get(current.pid) ?? []) queue.push({ pid: child.pid, depth: current.depth + 1 })@@ -302,43 +289,6 @@ export function resumeSessionId(engine: RegisteredSession['engine'], args: strinreturn 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@@ -398,12 +348,12 @@ export async function validateSessionRuntime(session: RegisteredSession): Promis* 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 =+export type RuntimeCheck =| { state: 'alive' }| { state: 'gone'; reason: string }| { state: 'unknown'; reason: string }-async function checkSessionRuntime(session: RegisteredSession): Promise<RuntimeCheck> {+export 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@@ -536,86 +486,3 @@ export function captureTmuxPane(pane: string, historyLines = 100): Promise<strin})})}--/**- * 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/tmuxAgentDiscovery.real.spec.ts b/cli/src/lib/tmuxAgentDiscovery.real.spec.tsnew file mode 100644index 000000000..66308b5db--- /dev/null+++ b/cli/src/lib/tmuxAgentDiscovery.real.spec.ts@@ -0,0 +1,91 @@+import { execFile } from 'node:child_process'+import { mkdtemp, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { promisify } from 'node:util'+import { afterAll, describe, expect, it } from 'vitest'+import type { AgentEngine } from '../engines/types.js'+import { ENGINE_CLI_COMMANDS, ENGINES } from './engineBin.js'+import { probeTmuxAgents } from './tmuxAgentDiscovery.js'++const exec = promisify(execFile)+const realDescribe = process.env.RUN_REAL_TMUX_DISCOVERY === '1' ? describe : describe.skip+const createdSessions = new Set<string>()++const engines: Array<[AgentEngine, string]> = ENGINES.map((engine) => [engine, ENGINE_CLI_COMMANDS[engine]])++async function tmux(args: string[]): Promise<string> {+ return (await exec('tmux', args, { timeout: 5_000 })).stdout.trim()+}++async function eventually<T>(read: () => Promise<T | null>, timeoutMs = 20_000): Promise<T | null> {+ const deadline = Date.now() + timeoutMs+ while (Date.now() < deadline) {+ const value = await read()+ if (value !== null) return value+ await new Promise((resolve) => setTimeout(resolve, 250))+ }+ return null+}++async function executable(name: string): Promise<string> {+ const result = await exec('/bin/zsh', ['-lc', `command -v ${name}`], { timeout: 5_000 })+ const path = result.stdout.trim()+ if (!path) throw new Error(`${name} is not installed`)+ return path+}++realDescribe.sequential('real installed CLI process discovery', () => {+ afterAll(async () => {+ for (const session of createdSessions) {+ await exec('tmux', ['kill-session', '-t', session], { timeout: 5_000 }).catch(() => {})+ }+ })++ it.each(engines)('discovers %s once and process-only deletion preserves its pane', async (engine, bin) => {+ const dir = await mkdtemp(join(tmpdir(), `harness-real-${engine}-`))+ const session = `harness-real-${process.pid}-${engine}`+ createdSessions.add(session)++ try {+ const path = await executable(bin)+ await tmux(['new-session', '-d', '-s', session, '-c', dir])+ const pane = await tmux(['list-panes', '-t', session, '-F', '#{pane_id}'])+ await tmux(['send-keys', '-t', pane, '-l', '--', path])+ await tmux(['send-keys', '-t', pane, 'C-m'])++ const discovered = await eventually(async () => {+ const result = await probeTmuxAgents()+ if (!result.ok) throw new Error(result.error)+ const inPane = result.agents.filter((candidate) => candidate.tmuxPane === pane)+ return inPane.length === 1 && inPane[0].engine === engine ? inPane[0] : null+ })+ const capture = await tmux(['capture-pane', '-p', '-t', pane]).catch(() => '')+ expect(discovered, `${bin} was not discovered in ${pane}\n${capture}`).not.toBeNull()++ const pid = discovered!.processIdentity.pid+ process.kill(pid, 'SIGTERM')+ const gone = await eventually(async () => {+ try { process.kill(pid, 0) } catch { return true }+ return null+ }, 2_000)+ if (!gone) {+ try { process.kill(pid, 'SIGKILL') } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error+ }+ }++ const absent = await eventually(async () => {+ const result = await probeTmuxAgents()+ if (!result.ok) throw new Error(result.error)+ return result.agents.some((candidate) => candidate.tmuxPane === pane) ? null : true+ }, 5_000)+ expect(absent, `${bin} remained discoverable after its exact saved PID was terminated`).toBe(true)+ await expect(tmux(['display-message', '-p', '-t', pane, '#{pane_id}'])).resolves.toBe(pane)+ } finally {+ await exec('tmux', ['kill-session', '-t', session], { timeout: 5_000 }).catch(() => {})+ createdSessions.delete(session)+ await rm(dir, { recursive: true, force: true })+ }+ }, 35_000)+})diff --git a/cli/src/lib/tmuxAgentDiscovery.spec.ts b/cli/src/lib/tmuxAgentDiscovery.spec.tsnew file mode 100644index 000000000..4cd28eab2--- /dev/null+++ b/cli/src/lib/tmuxAgentDiscovery.spec.ts@@ -0,0 +1,416 @@+import { describe, expect, it, vi } from 'vitest'+import type { AgentEngine } from '../engines/types.js'+import type { ProcessRow } from './tmux.js'+import type { RegisteredSession } from './registry.js'+import {+ TmuxAgentReconciler,+ discoverTmuxAgentsFromSnapshot,+ runtimeKey,+ type DiscoveredTmuxAgent,+ type TmuxAgentProbe,+} from './tmuxAgentDiscovery.js'++const START = 'Mon Aug 10 12:00:00 2026'+const pane = { tmuxPane: '%1', rootPid: 1, cwd: '/work/demo' }+const row = (pid: number, parentPid: number, executable: string, args = executable): ProcessRow => ({+ pid, parentPid, executable, args, startMarker: START,+})++describe('tmux process agent snapshot discovery', () => {+ const fixtures: Array<[AgentEngine, string, string]> = [+ ['claude', 'claude', 'claude'],+ ['codex', 'codex', 'codex'],+ ['cursor', 'agent', 'agent'],+ ['opencode', 'opencode', 'opencode'],+ ['pi', 'pi', 'pi'],+ ['hermes', 'python', '/opt/hermes-agent/hermes'],+ ['commandcode', '⌘ Project', '⌘ Project'],+ ['devin', 'devin', 'devin'],+ ['muse', 'muse-bin-1.2.3', 'muse-bin-1.2.3'],+ ['amp', 'amp', 'amp'],+ ['kilo', 'kilo', 'kilo'],+ ['grok', 'grok', 'grok'],+ ]++ it.each(fixtures)('recognizes the plain %s CLI process', (engine, executable, args) => {+ const result = discoverTmuxAgentsFromSnapshot([pane], [row(1, 0, 'zsh'), row(2, 1, executable, args)], 900)+ expect(result.agents).toHaveLength(1)+ expect(result.agents[0]).toMatchObject({ engine, tmuxPane: '%1', cwd: '/work/demo' })+ })++ const wrappers: Array<[AgentEngine, string, string]> = [+ ['claude', 'node', '/opt/lib/node_modules/@anthropic-ai/claude-code/cli.js'],+ ['codex', 'node', '/opt/lib/node_modules/@openai/codex/bin/codex.js'],+ ['cursor', 'node', '/opt/cursor-agent/versions/1.2.3/index.js'],+ ['opencode', 'opencode.exe', '/opt/lib/node_modules/opencode-ai/bin/opencode.exe'],+ ['pi', 'node', '/opt/lib/node_modules/pi-coding-agent/dist/cli.js'],+ ['hermes', 'python3', '/opt/hermes-agent/hermes'],+ ['commandcode', 'node', '/opt/lib/node_modules/command-code/dist/index.mjs'],+ ['devin', 'python3', '/opt/devin/cli/_versions/1.2.3/bin/devin'],+ ['muse', 'muse-bin-0.1.0-R708.1', 'muse-bin-0.1.0-R708.1'],+ ['amp', 'node', '/opt/.amp/bin/amp'],+ ['kilo', 'node', '/opt/lib/node_modules/@kilocode/cli/bin/kilo'],+ ['grok', 'node', '/opt/.grok/bin/grok'],+ ]++ it.each(wrappers)('recognizes the installed/wrapper form for %s', (engine, executable, args) => {+ const result = discoverTmuxAgentsFromSnapshot([pane], [row(1, 0, 'zsh'), row(2, 1, executable, args)], 900)+ expect(result.agents).toHaveLength(1)+ expect(result.agents[0].engine).toBe(engine)+ })++ const installPrefixes = [+ '/usr/local',+ '/opt/homebrew',+ '/nix/store/abc123-agent-cli',+ '/home/test/.local/share/pnpm/global/5',+ ]++ it.each(wrappers.flatMap(([engine, executable, args]) => installPrefixes.map((prefix) => [+ engine,+ executable,+ args.replace('/opt', prefix),+ ] as const)))('recognizes %s under arbitrary install prefix (%s)', (engine, executable, args) => {+ const result = discoverTmuxAgentsFromSnapshot(+ [pane],+ [row(1, 0, 'zsh'), row(2, 1, executable, args)],+ 900,+ )+ expect(result.agents[0]?.engine).toBe(engine)+ })++ it('recognizes an interpreter entrypoint under a quoted install prefix with spaces', () => {+ const result = discoverTmuxAgentsFromSnapshot(+ [pane],+ [row(1, 0, 'zsh'), row(2, 1, 'node', 'node "/Applications/Agent Tools/lib/node_modules/@openai/codex/bin/codex.js"')],+ 900,+ )+ expect(result.agents[0]?.engine).toBe('codex')+ })++ it('honors a configured engine path with a custom executable name', () => {+ const previous = process.env.CODEX_PATH+ process.env.CODEX_PATH = '/srv/company-tools/company-coding-agent'+ try {+ const result = discoverTmuxAgentsFromSnapshot(+ [pane],+ [row(1, 0, 'zsh'), row(2, 1, 'company-coding-agent', '/srv/company-tools/company-coding-agent')],+ 900,+ )+ expect(result.agents[0]?.engine).toBe('codex')+ } finally {+ if (previous === undefined) delete process.env.CODEX_PATH+ else process.env.CODEX_PATH = previous+ }+ })++ it('never treats engine names in prompt arguments as process entrypoints', () => {+ const result = discoverTmuxAgentsFromSnapshot(+ [pane],+ [row(1, 0, 'zsh'), row(2, 1, 'python3', 'python3 /work/runner.py compare claude codex agent opencode pi hermes cmd devin muse amp kilo grok')],+ 900,+ )+ expect(result.agents).toEqual([])+ })++ it('does not infer an agent from an engine-named repository path', () => {+ const result = discoverTmuxAgentsFromSnapshot(+ [pane],+ [row(1, 0, 'zsh'), row(2, 1, 'node', 'node /work/codex/tests/runner.js')],+ 900,+ )+ expect(result.agents).toEqual([])+ })++ it('does not treat inline shell source as the process entrypoint', () => {+ const result = discoverTmuxAgentsFromSnapshot(+ [pane],+ [row(1, 0, 'zsh'), row(2, 1, 'bash', 'bash -c "printf claude codex kilo"')],+ 900,+ )+ expect(result.agents).toEqual([])+ })++ it.each(['kilo', 'kilocode'])('recognizes the public %s wrapper command', (command) => {+ const result = discoverTmuxAgentsFromSnapshot(+ [pane],+ [row(1, 0, 'zsh'), row(2, 1, 'node', `node /any/prefix/bin/${command}`)],+ 900,+ )+ expect(result.agents[0]?.engine).toBe('kilo')+ })++ it('recognizes Command Code after it rewrites its process title', () => {+ const result = discoverTmuxAgentsFromSnapshot(+ [pane],+ [row(1, 0, 'zsh'), row(2, 1, '⌘ Implement lifecycle plan', '⌘ Implement lifecycle plan')],+ 900,+ )+ expect(result.agents[0]?.engine).toBe('commandcode')+ })++ it('creates independent agents for two panes running the same engine', () => {+ const result = discoverTmuxAgentsFromSnapshot(+ [pane, { tmuxPane: '%2', rootPid: 10, cwd: '/work/other' }],+ [row(1, 0, 'zsh'), row(2, 1, 'claude'), row(10, 0, 'zsh'), row(11, 10, 'claude')],+ 900,+ )+ expect(result.agents.map((agent) => [agent.tmuxPane, agent.engine])).toEqual([+ ['%1', 'claude'], ['%2', 'claude'],+ ])+ })++ it('keeps the shallow supported parent and ignores a nested supported sub-agent', () => {+ const result = discoverTmuxAgentsFromSnapshot(+ [pane],+ [row(1, 0, 'zsh'), row(2, 1, 'claude'), row(3, 2, 'codex')],+ 900,+ )+ expect(result.agents.map((agent) => agent.engine)).toEqual(['claude'])+ })++ it('keeps the same parent identity while nested sub-agent PIDs churn', () => {+ const first = discoverTmuxAgentsFromSnapshot(+ [pane],+ [+ row(1, 0, 'zsh'),+ row(2, 1, 'claude'),+ row(3, 2, 'node', 'node /work/helper.js'),+ row(4, 3, 'codex'),+ ],+ 900,+ )+ const second = discoverTmuxAgentsFromSnapshot(+ [pane],+ [+ row(1, 0, 'zsh'),+ row(2, 1, 'claude'),+ row(30, 2, 'node', 'node /work/helper.js'),+ row(40, 30, 'agent'),+ ],+ 900,+ )+ expect(first.agents[0]?.processIdentity.pid).toBe(2)+ expect(second.agents[0]?.processIdentity.pid).toBe(2)+ expect(runtimeKey(first.agents[0])).toBe(runtimeKey(second.agents[0]))+ })++ it('excludes recap/voice/one-shot descendants of the harness daemon', () => {+ const result = discoverTmuxAgentsFromSnapshot(+ [pane],+ [row(1, 0, 'zsh'), row(20, 1, 'node', 'node cli.js __run'), row(21, 20, 'codex', 'codex exec recap')],+ 20,+ )+ expect(result.agents).toEqual([])+ })++ it('does not guess when two top-level supported processes tie', () => {+ const result = discoverTmuxAgentsFromSnapshot(+ [pane],+ [row(1, 0, 'zsh'), row(2, 1, 'claude'), row(3, 1, 'codex')],+ 900,+ )+ expect(result.agents).toEqual([])+ expect(result.ambiguousPanes.has('%1')).toBe(true)+ })+})++function observed(pid: number, engine: AgentEngine = 'claude'): DiscoveredTmuxAgent {+ return {+ engine,+ tmuxPane: '%1',+ cwd: '/work/demo',+ processIdentity: { pid, executable: engine, startMarker: `${START} ${pid}` },+ args: engine,+ resumeSessionId: null,+ }+}++function registered(agent: DiscoveredTmuxAgent, agentId = 'agent-1'): RegisteredSession {+ return {+ agentId,+ sessionId: '',+ boundAt: null,+ engine: agent.engine,+ transcriptPath: null,+ projectDir: 'demo',+ cwd: agent.cwd,+ tmuxPane: agent.tmuxPane,+ source: null,+ title: null,+ model: null,+ cliVersion: null,+ processIdentity: agent.processIdentity,+ registeredAt: 1,+ updatedAt: 1,+ lastHookAt: 1,+ lastTranscriptAt: 1,+ }+}++const success = (agents: DiscoveredTmuxAgent[], panes = new Set(['%1'])): TmuxAgentProbe => ({+ ok: true,+ agents,+ panes,+ ambiguousPanes: new Set(),+})++describe('tmux process agent lifecycle reconciliation', () => {+ it('creates on the first positive scan and removes only after two confirmed misses', async () => {+ let current: RegisteredSession[] = []+ const live = observed(10)+ const probes = [success([live]), success([]), success([])]+ const removed: string[] = []+ const reconciler = new TmuxAgentReconciler({+ current: () => current,+ probe: async () => probes.shift()!,+ onDiscovered: (agent) => { current = [registered(agent)] },+ onObserved: () => {},+ onRemoved: (agent) => { removed.push(agent.agentId); current = [] },+ })+ await reconciler.trigger()+ expect(current).toHaveLength(1)+ await reconciler.trigger()+ expect(removed).toEqual([])+ await reconciler.trigger()+ expect(removed).toEqual(['agent-1'])+ })++ it('does not count a failed probe as a miss', async () => {+ const live = observed(10)+ let current = [registered(live)]+ const probes: TmuxAgentProbe[] = [+ { ok: false, error: 'ps timed out' },+ success([]),+ success([]),+ ]+ const removed = vi.fn(() => { current = [] })+ const reconciler = new TmuxAgentReconciler({+ current: () => current,+ probe: async () => probes.shift()!,+ onDiscovered: () => {},+ onObserved: () => {},+ onRemoved: removed,+ })+ await reconciler.trigger()+ await reconciler.trigger()+ expect(removed).not.toHaveBeenCalled()+ await reconciler.trigger()+ expect(removed).toHaveBeenCalledTimes(1)+ })++ it('holds the current agent through a detached same-depth sub-agent ambiguity', async () => {+ const live = observed(10)+ const current = [registered(live)]+ const ambiguous: TmuxAgentProbe = {+ ok: true,+ agents: [],+ panes: new Set(['%1']),+ ambiguousPanes: new Set(['%1']),+ }+ const probes = [ambiguous, ambiguous, success([live])]+ const discovered = vi.fn()+ const removed = vi.fn()+ const observedAgain = vi.fn()+ const reconciler = new TmuxAgentReconciler({+ current: () => current,+ probe: async () => probes.shift()!,+ onDiscovered: discovered,+ onObserved: observedAgain,+ onRemoved: removed,+ })++ await reconciler.trigger()+ await reconciler.trigger()+ expect(discovered).not.toHaveBeenCalled()+ expect(removed).not.toHaveBeenCalled()+ await reconciler.trigger()+ expect(observedAgain).toHaveBeenCalledWith(live, current[0])+ expect(removed).not.toHaveBeenCalled()+ })++ it('serializes scans and coalesces every trigger received during one slow pass', async () => {+ let releaseFirst!: () => void+ const firstGate = new Promise<void>((resolve) => { releaseFirst = resolve })+ let calls = 0+ let active = 0+ let maxActive = 0+ const reconciler = new TmuxAgentReconciler({+ current: () => [],+ probe: async () => {+ calls+++ active+++ maxActive = Math.max(maxActive, active)+ if (calls === 1) await firstGate+ active--+ return success([])+ },+ onDiscovered: () => {},+ onObserved: () => {},+ onRemoved: () => {},+ })++ const first = reconciler.trigger()+ const second = reconciler.trigger()+ const third = reconciler.trigger()+ expect(calls).toBe(1)+ releaseFirst()+ await Promise.all([first, second, third])+ expect(calls).toBe(2)+ expect(maxActive).toBe(1)+ })++ it('replaces a changed process in the same pane immediately', async () => {+ const old = observed(10)+ const replacement = observed(11, 'codex')+ let current = [registered(old)]+ const order: string[] = []+ const reconciler = new TmuxAgentReconciler({+ current: () => current,+ probe: async () => success([replacement]),+ onDiscovered: (agent) => { order.push('add'); current = [registered(agent, 'agent-2')] },+ onObserved: () => {},+ onRemoved: () => { order.push('remove'); current = [] },+ })+ await reconciler.trigger()+ expect(order).toEqual(['remove', 'add'])+ expect(current[0]).toMatchObject({ agentId: 'agent-2', engine: 'codex' })+ })++ it('treats PID reuse with a new start marker as immediate replacement', async () => {+ const old = observed(10)+ const replacement = { ...observed(10), processIdentity: { ...observed(10).processIdentity, startMarker: `${START} reused` } }+ let current = [registered(old)]+ const order: string[] = []+ const reconciler = new TmuxAgentReconciler({+ current: () => current,+ probe: async () => success([replacement]),+ onDiscovered: (agent) => { order.push('add'); current = [registered(agent, 'agent-2')] },+ onObserved: () => {},+ onRemoved: () => { order.push('remove'); current = [] },+ })+ await reconciler.trigger()+ expect(order).toEqual(['remove', 'add'])+ expect(current[0].agentId).toBe('agent-2')+ })++ it('suppresses a deleted runtime until that exact identity disappears', async () => {+ const live = observed(10)+ let current: RegisteredSession[] = []+ const probes = [success([live]), success([]), success([observed(11)])]+ const added: string[] = []+ const reconciler = new TmuxAgentReconciler({+ current: () => current,+ probe: async () => probes.shift()!,+ onDiscovered: (agent) => { added.push(runtimeKey(agent)); current = [registered(agent)] },+ onObserved: () => {},+ onRemoved: () => { current = [] },+ })+ reconciler.suppress(live)+ await reconciler.trigger()+ expect(added).toEqual([])+ await reconciler.trigger()+ await reconciler.trigger()+ expect(added).toEqual([runtimeKey(observed(11))])+ })+})diff --git a/cli/src/lib/tmuxAgentDiscovery.ts b/cli/src/lib/tmuxAgentDiscovery.tsnew file mode 100644index 000000000..eba62eec5--- /dev/null+++ b/cli/src/lib/tmuxAgentDiscovery.ts@@ -0,0 +1,279 @@+/**+ * Discover the top-level supported coding-agent process in every tmux pane.+ *+ * The process is the agent. A launcher, hook, transcript, or session id may describe it, but none of+ * those owns its lifetime. One successful reconciliation reads tmux once and ps once, then applies the+ * same snapshot to every pane so a slow machine cannot turn N agents into N independent timeout risks.+ */++import { execFile } from 'node:child_process'+import { ENGINES } from './engineBin.js'+import type { AgentEngine } from '../engines/types.js'+import type { ProcessIdentity, RegisteredSession } from './registry.js'+import { engineProcessMatchScore, parseProcessRow, resumeSessionId, type ProcessRow } from './tmux.js'++export interface TmuxPaneSnapshot {+ tmuxPane: string+ rootPid: number+ cwd: string+}++export interface DiscoveredTmuxAgent {+ engine: AgentEngine+ tmuxPane: string+ cwd: string+ processIdentity: ProcessIdentity+ /** The stable engine process argv, used only to bind an explicit `--resume <id>` after discovery. */+ args: string+ resumeSessionId: string | null+}++export type TmuxAgentProbe =+ | { ok: true; agents: DiscoveredTmuxAgent[]; panes: Set<string>; ambiguousPanes: Set<string> }+ | { ok: false; error: string }++export interface TmuxAgentDiscoveryDeps {+ current: () => RegisteredSession[]+ onDiscovered: (agent: DiscoveredTmuxAgent) => void | Promise<void>+ onObserved: (agent: DiscoveredTmuxAgent, current: RegisteredSession) => void | Promise<void>+ onRemoved: (agent: RegisteredSession, reason: string) => void | Promise<void>+ probe?: (daemonPid: number) => Promise<TmuxAgentProbe>+ daemonPid?: number+}++const MISS_LIMIT = 2++function execText(command: string, args: string[], timeout: number): Promise<{ ok: true; stdout: string } | { ok: false; error: string }> {+ return new Promise((resolve) => {+ execFile(command, args, { timeout }, (err, stdout) => {+ if (err) { resolve({ ok: false, error: err.message }); return }+ resolve({ ok: true, stdout })+ })+ })+}++function parsePanes(stdout: string): TmuxPaneSnapshot[] {+ const panes: TmuxPaneSnapshot[] = []+ 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') })+ }+ return panes+}++function childrenByParent(rows: readonly ProcessRow[]): Map<number, ProcessRow[]> {+ const children = new Map<number, ProcessRow[]>()+ for (const row of rows) {+ const list = children.get(row.parentPid) ?? []+ list.push(row)+ children.set(row.parentPid, list)+ }+ return children+}++function daemonDescendants(rows: readonly ProcessRow[], daemonPid: number): Set<number> {+ const children = childrenByParent(rows)+ const excluded = new Set<number>()+ const queue = [daemonPid]+ while (queue.length) {+ const pid = queue.shift()!+ if (excluded.has(pid)) continue+ excluded.add(pid)+ for (const child of children.get(pid) ?? []) queue.push(child.pid)+ }+ return excluded+}++/**+ * Pick one pane owner from an already-read process tree.+ *+ * Depth outranks score: a supported CLI nested below another supported CLI is a sub-agent/tool child and+ * must not steal the pane. Score only distinguishes wrappers at the same depth. A remaining tie is+ * ambiguous and deliberately produces no agent.+ */+function paneOwner(+ pane: TmuxPaneSnapshot,+ rows: readonly ProcessRow[],+ excluded: ReadonlySet<number>,+): { agent: DiscoveredTmuxAgent | null; ambiguous: boolean } {+ const byPid = new Map(rows.map((row) => [row.pid, row]))+ const children = childrenByParent(rows)+ const queue: Array<{ pid: number; depth: number }> = [{ pid: pane.rootPid, depth: 0 }]+ const matches: Array<{ row: ProcessRow; engine: AgentEngine; depth: number; score: number }> = []++ while (queue.length) {+ const current = queue.shift()!+ const row = byPid.get(current.pid)+ if (row && !excluded.has(row.pid)) {+ for (const engine of ENGINES) {+ const score = engineProcessMatchScore(row, engine)+ if (score > 0) matches.push({ row, engine, depth: current.depth, score })+ }+ }+ for (const child of children.get(current.pid) ?? []) queue.push({ pid: child.pid, depth: current.depth + 1 })+ }++ if (!matches.length) return { agent: null, ambiguous: false }+ const shallowest = Math.min(...matches.map((match) => match.depth))+ const atDepth = matches.filter((match) => match.depth === shallowest)+ const strongest = Math.max(...atDepth.map((match) => match.score))+ const finalists = atDepth.filter((match) => match.score === strongest)+ const unique = new Map(finalists.map((match) => [`${match.row.pid}:${match.engine}`, match]))+ if (unique.size !== 1) return { agent: null, ambiguous: true }++ const [{ row, engine }] = [...unique.values()]+ return {+ ambiguous: false,+ agent: {+ engine,+ tmuxPane: pane.tmuxPane,+ cwd: pane.cwd,+ processIdentity: { pid: row.pid, executable: row.executable, startMarker: row.startMarker },+ args: row.args,+ resumeSessionId: resumeSessionId(engine, row.args),+ },+ }+}++/** Pure snapshot form used by the reconciler and process-table fixtures. */+export function discoverTmuxAgentsFromSnapshot(+ panes: readonly TmuxPaneSnapshot[],+ rows: readonly ProcessRow[],+ daemonPid: number,+): Extract<TmuxAgentProbe, { ok: true }> {+ const excluded = daemonDescendants(rows, daemonPid)+ const agents: DiscoveredTmuxAgent[] = []+ const ambiguousPanes = new Set<string>()+ for (const pane of panes) {+ const owner = paneOwner(pane, rows, excluded)+ if (owner.ambiguous) ambiguousPanes.add(pane.tmuxPane)+ else if (owner.agent) agents.push(owner.agent)+ }+ return { ok: true, agents, panes: new Set(panes.map((pane) => pane.tmuxPane)), ambiguousPanes }+}++/** One tmux call plus one ps call for a complete reconciliation pass. */+export async function probeTmuxAgents(daemonPid = process.pid): Promise<TmuxAgentProbe> {+ const [tmux, ps] = await Promise.all([+ execText('tmux', ['list-panes', '-a', '-F', '#{pane_id}\t#{pane_pid}\t#{pane_current_path}'], 2_000),+ execText('ps', ['-axo', 'pid=,ppid=,comm=,lstart=,args='], 3_000),+ ])+ if (!tmux.ok) return { ok: false, error: `tmux list-panes failed: ${tmux.error}` }+ if (!ps.ok) return { ok: false, error: `process table failed: ${ps.error}` }+ const rows = ps.stdout.split('\n').map(parseProcessRow).filter((row): row is ProcessRow => row !== null)+ return discoverTmuxAgentsFromSnapshot(parsePanes(tmux.stdout), rows, daemonPid)+}++export function sameRuntime(+ current: Pick<RegisteredSession, 'engine' | 'tmuxPane' | 'processIdentity'>,+ observed: Pick<DiscoveredTmuxAgent, 'engine' | 'tmuxPane' | 'processIdentity'>,+): boolean {+ const saved = current.processIdentity+ const live = observed.processIdentity+ return current.engine === observed.engine+ && current.tmuxPane === observed.tmuxPane+ && !!saved+ && saved.pid === live.pid+ && saved.startMarker === live.startMarker+}++export function runtimeKey(runtime: Pick<DiscoveredTmuxAgent, 'engine' | 'tmuxPane' | 'processIdentity'>): string {+ return `${runtime.tmuxPane}\u0000${runtime.engine}\u0000${runtime.processIdentity.pid}\u0000${runtime.processIdentity.startMarker}`+}++/**+ * Serialized/coalesced lifecycle loop. Successful negative observations count; probe failures and+ * ambiguous panes leave both the agent and its miss count untouched.+ */+export class TmuxAgentReconciler {+ private readonly misses = new Map<string, number>()+ private readonly suppressed = new Set<string>()+ private pending = false+ private inFlight: Promise<void> | null = null+ private timer: NodeJS.Timeout | null = null++ constructor(private readonly deps: TmuxAgentDiscoveryDeps) {}++ start(intervalMs: number): void {+ void this.trigger()+ this.timer = setInterval(() => { void this.trigger() }, intervalMs)+ this.timer.unref?.()+ }++ stop(): void {+ if (this.timer) clearInterval(this.timer)+ this.timer = null+ }++ /** Hide an explicitly deleted runtime until a successful scan proves that exact process is gone. */+ suppress(runtime: Pick<DiscoveredTmuxAgent, 'engine' | 'tmuxPane' | 'processIdentity'>): void {+ this.suppressed.add(runtimeKey(runtime))+ }++ trigger(): Promise<void> {+ this.pending = true+ if (!this.inFlight) this.inFlight = this.drain().finally(() => { this.inFlight = null })+ return this.inFlight+ }++ private async drain(): Promise<void> {+ while (this.pending) {+ this.pending = false+ await this.reconcileOnce()+ }+ }++ private async reconcileOnce(): Promise<void> {+ const probe = await (this.deps.probe ?? probeTmuxAgents)(this.deps.daemonPid ?? process.pid)+ if (!probe.ok) {+ console.warn(`[discovery] ${probe.error}; keeping ${this.deps.current().length} agent(s)`)+ return+ }++ const observedKeys = new Set(probe.agents.map(runtimeKey))+ for (const key of [...this.suppressed]) if (!observedKeys.has(key)) this.suppressed.delete(key)++ const before = this.deps.current()+ const byPane = new Map(before.map((agent) => [agent.tmuxPane, agent]))+ const observedAgentIds = new Set<string>()++ for (const observed of probe.agents) {+ if (this.suppressed.has(runtimeKey(observed))) continue+ const current = byPane.get(observed.tmuxPane)+ if (!current) {+ await this.deps.onDiscovered(observed)+ continue+ }+ // One-time migration from a launcher-owned record that did not persist a process identity.+ const legacyMatch = !current.processIdentity && current.engine === observed.engine+ if (legacyMatch || sameRuntime(current, observed)) {+ observedAgentIds.add(current.agentId)+ this.misses.delete(current.agentId)+ await this.deps.onObserved(observed, current)+ continue+ }+ this.misses.delete(current.agentId)+ await this.deps.onRemoved(current, `process replaced in ${observed.tmuxPane}`)+ await this.deps.onDiscovered(observed)+ }++ for (const current of before) {+ if (observedAgentIds.has(current.agentId)) continue+ if (probe.ambiguousPanes.has(current.tmuxPane)) continue+ const observed = probe.agents.find((candidate) => candidate.tmuxPane === current.tmuxPane)+ if (observed) continue // replacement already handled above+ const misses = (this.misses.get(current.agentId) ?? 0) + 1+ if (misses < MISS_LIMIT) {+ this.misses.set(current.agentId, misses)+ continue+ }+ this.misses.delete(current.agentId)+ const reason = probe.panes.has(current.tmuxPane)+ ? `no supported engine process in ${current.tmuxPane} after ${MISS_LIMIT} confirmed scans`+ : `tmux pane ${current.tmuxPane} absent after ${MISS_LIMIT} confirmed scans`+ await this.deps.onRemoved(current, reason)+ }+ }+}