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: implement agent restart mechanism with session-resumption and process-swapping support
0xken1596b55dbcb4a1
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex 655da2595..8d6769477 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -466,6 +466,128 @@ describe('BackendSocket outbound queue', () => {})})+describe('agent_restart RPC', () => {+ afterEach(() => {+ wsMock.instances.length = 0+ vi.restoreAllMocks()+ })++ const BASE_SESSION: RegisteredSession = {+ schemaVersion: 2,+ active: true,+ agentId: 'agent-1',+ sessionId: 'session-1',+ boundAt: 1,+ engine: 'claude',+ transcriptPath: null,+ projectDir: 'workspace',+ cwd: '/tmp/workspace',+ runtimes: [],+ primaryRuntimeKey: '',+ tmuxPane: '%1',+ source: null,+ title: 'Agent one',+ model: null,+ cliVersion: null,+ processIdentity: null,+ registeredAt: 1,+ updatedAt: 1,+ lastHookAt: 1,+ lastTranscriptAt: 1,+ }++ function localSocket(): { socket: BackendSocket; frames: Array<Record<string, unknown>> } {+ const socket = new BackendSocket('token')+ const frames: Array<Record<string, unknown>> = []+ socket.registerLocalClient('local:restart', {+ sendFrame: (frame) => { frames.push(frame); return true },+ sendBinary: () => true,+ })+ return { socket, frames }+ }++ it('replies MISSING_AGENT_ID when no agentId is given', async () => {+ const { socket, frames } = localSocket()+ socket.handleLocalFrame('local:restart', { type: 'agent_restart', payload: { requestId: 'r1' } })+ await vi.waitFor(() => expect(frames).toContainEqual({+ type: 'agent_restart_result', payload: { requestId: 'r1', error: 'MISSING_AGENT_ID' },+ }))+ await socket.unregisterLocalClient('local:restart')+ await socket.stop()+ })++ it('replies UNSUPPORTED_ON_REMOTE when no handler is wired', async () => {+ const { socket, frames } = localSocket()+ socket.handleLocalFrame('local:restart', { type: 'agent_restart', payload: { requestId: 'r1', agentId: 'agent-1' } })+ await vi.waitFor(() => expect(frames).toContainEqual({+ type: 'agent_restart_result', payload: { requestId: 'r1', error: 'UNSUPPORTED_ON_REMOTE' },+ }))+ await socket.unregisterLocalClient('local:restart')+ await socket.stop()+ })++ it('delegates to onRestartAgent and replies with the agent projection and the resumed flag on success', async () => {+ const { socket, frames } = localSocket()+ let seenAgentId: string | undefined+ socket.onRestartAgent = async (agentId) => {+ seenAgentId = agentId+ return { ok: true, session: BASE_SESSION, resumed: true }+ }+ socket.handleLocalFrame('local:restart', { type: 'agent_restart', payload: { requestId: 'r1', agentId: 'agent-1' } })+ await vi.waitFor(() => {+ const result = frames.find((f) => f.type === 'agent_restart_result')+ expect(result).toMatchObject({+ type: 'agent_restart_result',+ payload: {+ requestId: 'r1',+ resumed: true,+ agent: expect.objectContaining({ id: 'agent-1', sessionId: 'session-1', engine: 'claude' }),+ },+ })+ })+ expect(seenAgentId).toBe('agent-1')+ await socket.unregisterLocalClient('local:restart')+ await socket.stop()+ })++ it('reports a fresh (non-resumed) relaunch through the same resumed flag', async () => {+ const { socket, frames } = localSocket()+ socket.onRestartAgent = async () => ({ ok: true, session: BASE_SESSION, resumed: false })+ socket.handleLocalFrame('local:restart', { type: 'agent_restart', payload: { requestId: 'r1', agentId: 'agent-1' } })+ await vi.waitFor(() => {+ const result = frames.find((f) => f.type === 'agent_restart_result')+ expect(result).toMatchObject({ payload: { requestId: 'r1', resumed: false } })+ })+ await socket.unregisterLocalClient('local:restart')+ await socket.stop()+ })++ it('replies with error+detail on failure, matching agent_create/agent_delete\'s reply shape', async () => {+ const { socket, frames } = localSocket()+ socket.onRestartAgent = async () => (+ { ok: false, error: 'RESTART_FAILED', detail: 'claude did not come back up after restart' }+ )+ socket.handleLocalFrame('local:restart', { type: 'agent_restart', payload: { requestId: 'r1', agentId: 'agent-1' } })+ await vi.waitFor(() => expect(frames).toContainEqual({+ type: 'agent_restart_result',+ payload: { requestId: 'r1', error: 'RESTART_FAILED', detail: 'claude did not come back up after restart' },+ }))+ await socket.unregisterLocalClient('local:restart')+ await socket.stop()+ })++ it('omits detail on failure when the handler did not supply one', async () => {+ const { socket, frames } = localSocket()+ socket.onRestartAgent = async () => ({ ok: false, error: 'AGENT_NOT_FOUND' })+ socket.handleLocalFrame('local:restart', { type: 'agent_restart', payload: { requestId: 'r1', agentId: 'agent-1' } })+ await vi.waitFor(() => expect(frames).toContainEqual({+ type: 'agent_restart_result', payload: { requestId: 'r1', error: 'AGENT_NOT_FOUND' },+ }))+ await socket.unregisterLocalClient('local:restart')+ await socket.stop()+ })+})+describe('compact runtime picker catalog', () => {const models = [{ id: 'runtime-v1:s1:codex:gpt-5.6-sol@auto', displayName: 'Sol / Auto' },diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 707a0e69f..174093b7b 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -295,6 +295,15 @@ export class BackendSocket {* requested folder and returns its process-agent. Session metadata may bind later through hooks. */onCreateAgent: ((input: { engine: AgentEngine; cwd: string; bypassPermission: boolean }) =>Promise<{ ok: true; session: RegisteredSession } | { ok: false; error: string; detail?: string }>) | null = null+ /** Called on `agent_restart` — cli.ts stops the agent's live engine process and relaunches it in the+ * SAME tmux pane, keeping the SAME agentId and (best-effort) resuming the same engine session.+ * `resumed` tells the caller whether the relaunch actually resumed the prior conversation or had to+ * fall back to a fresh one under the same agent/pane. */+ onRestartAgent: ((agentId: string) =>+ Promise<+ { ok: true; session: RegisteredSession; resumed: boolean }+ | { ok: false; error: string; detail?: string }+ >) | null = null/** Called when the web/device sends chat input to an agent terminal. */onMessage: ((sessionId: string, content: string) => void) | null = null/** Best-effort terminal-native title sync after a user renames an agent. */@@ -1303,6 +1312,21 @@ export class BackendSocket {return}+ // Restart an agent: exit its live engine process and relaunch it in the SAME tmux pane, keeping+ // the SAME agentId. Follows agent_create/agent_delete's exact validate → delegate → reply shape.+ case 'agent_restart': {+ const target = payload.agentId as string | undefined+ if (!target) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }+ if (!this.onRestartAgent) { reply(type, requestId, { error: 'UNSUPPORTED_ON_REMOTE' }); return }+ const result = await this.onRestartAgent(target)+ if (!result.ok) {+ reply(type, requestId, result.detail ? { error: result.error, detail: result.detail } : { error: result.error })+ return+ }+ reply(type, requestId, { agent: await this.toProject(result.session), resumed: result.resumed })+ return+ }+case 'agent_files': {// SourceTree list — rooted at the tmux session's working dir.const projectId = payload.agentId as string | undefineddiff --git a/cli/src/cli.ts b/cli/src/cli.tsindex cc5e361c0..047e54aa5 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -44,11 +44,20 @@ import { AuthSessionError, AuthSessionManager, clearAuthSession, readAuthSessionimport { ENGINE_CLI_COMMANDS, ENGINES } from './lib/engineBin.js'import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell, interactiveEngineShell } from './lib/engineLaunch.js'import { clearDeleted, isRecentlyDeleted, markDeleted } from './lib/deletedSessions.js'-import { terminateDeletedAgent } from './lib/deleteAgentFallback.js'+import { terminateDeletedAgent, checkPidRuntime } from './lib/deleteAgentFallback.js'+import { restartAgent } from './lib/restartAgent.js'import { findLiveSession } from './lib/sessionRepair.js'import { TmuxBackend } from './lib/tmuxBackend.js'import { basename } from 'node:path'-import { captureTmuxPane, clearPaneRemainOnExit, resolvePaneEngineProcess, tmuxPaneProcessTree, tmuxPaneState, type TmuxPaneState } from './lib/tmux.js'+import {+ bypassPermissionActive,+ captureTmuxPane,+ clearPaneRemainOnExit,+ resolvePaneEngineProcess,+ tmuxPaneProcessTree,+ tmuxPaneState,+ type TmuxPaneState,+} from './lib/tmux.js'import { describeAgentCreateFailure, summarizePaneOutput } from './lib/agentCreateDiagnosis.js'import { HerdrBackend } from './lib/herdrBackend.js'import {@@ -64,7 +73,13 @@ import { TerminalStreamManager } from './lib/terminalStreamManager.js'import { terminalRouteKey, terminalRuntimeLabel } from './lib/terminalRuntime.js'import { TerminalAgentReconciler } from './lib/terminalAgentReconciler.js'import { processRows, type DiscoveredTerminalAgent } from './lib/terminalAgentDiscovery.js'-import { terminalActionNotStarted, type HookTerminalHint, type TerminalActionResult, type TerminalRuntimeRef } from './lib/terminalTypes.js'+import {+ terminalActionNotStarted,+ type HookTerminalHint,+ type TerminalActionResult,+ type TerminalRuntimeRef,+ type TmuxRuntimeRef,+} from './lib/terminalTypes.js'import { readTerminalConfigSnapshot, writeTerminalConfigSnapshot } from './lib/terminalConfigSnapshot.js'import { Watcher, type LineEvent } from './watcher/watcher.js'import { chooseHookAgent, startHookServer } from './hookServer.js'@@ -2894,16 +2909,7 @@ async function runForeground(session: AuthSession): Promise<void> {forgetSession(sessionId, { force: true })if (!s) returnvoid terminateDeletedAgent(s, {- checkRuntime: async (session) => {- const expected = session.processIdentity- if (!expected) return { state: 'gone', reason: 'agent has no saved process identity' }- const rows = await processRows()- if (!rows) return { state: 'unknown', reason: 'process table is unavailable' }- const live = rows.find((row) => row.pid === expected.pid)- return live && live.startMarker === expected.startMarker && live.executable === expected.executable- ? { state: 'alive' }- : { state: 'gone', reason: 'saved process identity is no longer running' }- },+ checkRuntime: checkPidRuntime,kill: (pid, signal) => process.kill(pid, signal),sleep: (ms) => new Promise((resolve) => { const t = setTimeout(resolve, ms); t.unref?.() }),log: (message) => console.log(message),@@ -2917,6 +2923,97 @@ async function runForeground(session: AuthSession): Promise<void> {})}+ /**+ * Web or device restarted an agent (`agent_restart`): exit the live engine process and relaunch it in+ * the SAME tmux pane, keeping the SAME agentId/session — restart must never look like delete+create to+ * the registry or the UI. Two things guard that identity:+ *+ * - `remain-on-exit` is re-armed on the pane before the old process is killed (mirrors what+ * `create()` does at spawn time), or tmux would tear the pane — and with it the whole one-pane+ * session — down the instant that process exits.+ * - the periodic reconciler is told to ignore this pane's ROUTE for the duration of the swap+ * (`agentReconciler.holdRoute`/`releaseRoute`), or it would either flicker the agent dormant+ * mid-kill, or — worse — mint a brand-new agent for the relaunched process the instant it appears,+ * before this handler gets to rebind it.+ *+ * The bypass-permission mode is read from the LIVE process argv before anything is signalled (there is+ * nowhere else to read it from once the process is dead); the sessionId to resume comes from the+ * registry's live-synced field, not from the original launch argv (the user may have resumed/switched+ * sessions from inside the engine's own terminal since launch).+ */+ backend.onRestartAgent = async (agentId) => {+ const session = registry.resolve(agentId)+ if (!session) return { ok: false, error: 'AGENT_NOT_FOUND' }+ if (!session.tmuxPane || !tmuxBackend) return { ok: false, error: 'RESTART_UNSUPPORTED_BACKEND' }+ if (!session.processIdentity) return { ok: false, error: 'NO_ACTIVE_PROCESS' }+ const pane = session.tmuxPane+ const engine = session.engine+ const runtime: TmuxRuntimeRef = { backend: 'tmux', paneId: pane }+ const routeKey = terminalRouteKey(runtime)++ agentReconciler.holdRoute(routeKey)+ try {+ const rows = await processRows()+ const row = rows?.find((candidate) =>+ candidate.pid === session.processIdentity!.pid && candidate.startMarker === session.processIdentity!.startMarker)+ const bypassPermission = row ? bypassPermissionActive(engine, row.args) : false++ const outcome = await restartAgent({ engine, sessionId: session.sessionId }, bypassPermission, {+ holdOpen: async () => {+ const result = await tmuxBackend!.holdOpen(runtime)+ return result.state === 'succeeded'+ ? { ok: true }+ : { ok: false, reason: 'reason' in result ? result.reason : 'could not re-arm remain-on-exit' }+ },+ terminate: (checkAfterMs) => terminateDeletedAgent(session, {+ checkRuntime: checkPidRuntime,+ kill: (pid, signal) => process.kill(pid, signal),+ sleep: (ms) => new Promise((resolve) => { const t = setTimeout(resolve, ms); t.unref?.() }),+ log: (message) => console.log(message),+ }, checkAfterMs),+ respawn: async (argv) => {+ const result = await tmuxBackend!.respawn(runtime, argv, session.cwd)+ return result.state === 'succeeded'+ ? { ok: true }+ : { ok: false, reason: 'reason' in result ? result.reason : 'tmux respawn-pane did not complete' }+ },+ waitForProcess: async () => {+ // Mirrors onCreateAgent's own discovery budget/backoff shape for the same reason: the engine's+ // interactive-login-shell startup, not the tmux call, is the slow half.+ const RESTART_DISCOVERY_BUDGET_MS = 8_000+ let delayMs = 150+ let waited = 0+ while (waited < RESTART_DISCOVERY_BUDGET_MS) {+ await new Promise((resolve) => setTimeout(resolve, delayMs))+ waited += delayMs+ const found = await resolvePaneEngineProcess(pane, engine)+ if (found) return found+ delayMs = Math.min(delayMs * 2, 750)+ }+ return null+ },+ buildArgv: (opts) => buildEngineLaunchArgv(engine, opts),+ log: (message) => console.log(message),+ })++ if (!outcome.ok) return { ok: false, error: 'RESTART_FAILED', detail: outcome.detail }++ // Address the CANONICAL agentId from the resolved session, not the raw RPC input — `resolve()`+ // accepts either an agentId or a bare sessionId, but `setActive`/`byAgent` only ever key on the+ // real agentId.+ registry.updateProcessIdentity(session.agentId, outcome.processIdentity)+ registry.setActive(session.agentId, true)+ await clearPaneRemainOnExit(pane)+ const refreshed = registry.byAgent(session.agentId)+ if (!refreshed) return { ok: false, error: 'RESTART_FAILED', detail: 'agent vanished from the registry mid-restart' }+ announceSession(refreshed)+ console.log(`[restart] ${sid(session.agentId)} ${engine} · ${outcome.resumed ? 'resumed' : 'fresh session'}`)+ return { ok: true, session: refreshed, resumed: outcome.resumed }+ } finally {+ agentReconciler.releaseRoute(routeKey)+ }+ }+backend.onMessage = (id, content) => {const record = registry.resolve(id)const sessionId = record?.sessionId ?? iddiff --git a/cli/src/lib/deleteAgentFallback.spec.ts b/cli/src/lib/deleteAgentFallback.spec.tsindex c398566ff..34a326c74 100644--- a/cli/src/lib/deleteAgentFallback.spec.ts+++ b/cli/src/lib/deleteAgentFallback.spec.ts@@ -1,7 +1,13 @@-import { describe, expect, it } from 'vitest'-import { terminateDeletedAgent, type TerminateDeps } from './deleteAgentFallback.js'+import { describe, expect, it, vi } from 'vitest'+import { terminateDeletedAgent, checkPidRuntime, type TerminateDeps } from './deleteAgentFallback.js'import type { RegisteredSession } from './registry.js'-import type { RuntimeCheck } from './tmux.js'+import type { ProcessRow, RuntimeCheck } from './tmux.js'++const processRows = vi.hoisted(() => vi.fn())+vi.mock('./tmux.js', async (importOriginal) => ({+ ...await importOriginal<typeof import('./tmux.js')>(),+ processRows,+}))/*** The one place in the adapter that signals somebody else's process. Everything here is about NOT hitting@@ -177,3 +183,45 @@ describe('delete-agent process termination wiring', () => {expect(seen[0]).toBe(SESSION)})})++/**+ * `checkPidRuntime` — the exact PID + start-marker + executable check extracted out of onDeleteAgent's+ * former inline lambda so restart can reuse it via `terminateDeletedAgent` too, without duplicating the+ * PID-reuse guard. Pure extraction: this must not change onDeleteAgent's own behavior.+ */+describe('checkPidRuntime', () => {+ const row = (over: Partial<ProcessRow> = {}): ProcessRow => ({+ pid: 4242, parentPid: 1, executable: 'claude', startMarker: 'Mon Aug 3 09:00:00 2026', args: 'claude', ...over,+ })++ it('is alive when pid, startMarker, and executable all match', async () => {+ processRows.mockResolvedValue([row()])+ await expect(checkPidRuntime(SESSION)).resolves.toEqual({ state: 'alive' })+ })++ it('is gone when the saved pid is no longer in the process table', async () => {+ processRows.mockResolvedValue([row({ pid: 1 })])+ await expect(checkPidRuntime(SESSION)).resolves.toMatchObject({ state: 'gone' })+ })++ it('is gone — not alive — when the pid was recycled by a different process', async () => {+ // Same pid, different start time: the PID-reuse guard.+ processRows.mockResolvedValue([row({ startMarker: 'Tue Aug 4 09:00:00 2026' })])+ await expect(checkPidRuntime(SESSION)).resolves.toMatchObject({ state: 'gone' })+ })++ it('is gone when the executable identity does not match, even with the same pid/startMarker', async () => {+ processRows.mockResolvedValue([row({ executable: 'not-claude' })])+ await expect(checkPidRuntime(SESSION)).resolves.toMatchObject({ state: 'gone' })+ })++ it('is unknown, not gone, when the process table itself could not be read', async () => {+ processRows.mockResolvedValue(null)+ await expect(checkPidRuntime(SESSION)).resolves.toMatchObject({ state: 'unknown' })+ })++ it('is gone when the session never had a saved process identity', async () => {+ processRows.mockResolvedValue([row()])+ await expect(checkPidRuntime({ ...SESSION, processIdentity: null })).resolves.toMatchObject({ state: 'gone' })+ })+})diff --git a/cli/src/lib/deleteAgentFallback.ts b/cli/src/lib/deleteAgentFallback.tsindex 0b3936c94..de254a08b 100644--- a/cli/src/lib/deleteAgentFallback.ts+++ b/cli/src/lib/deleteAgentFallback.ts@@ -1,7 +1,7 @@/** 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'+import { processRows, type RuntimeCheck } from './tmux.js'/** Delete has already removed the UI entry; signal the saved process immediately. */export const TERMINATE_CHECK_MS = 0@@ -9,6 +9,26 @@ export const TERMINATE_CHECK_MS = 0export const FALLBACK_KILL_GRACE_MS = 3_000const POLL_MS = 250+/**+ * Exact PID + start-marker + executable validation — the PID-reuse guard shared by delete and restart.+ * Deliberately PID-only, not pane-based (unlike tmux.ts's `checkSessionRuntime`): by the time either+ * caller runs, the pane's UI entry may already be gone (delete) or is about to host a brand-new process+ * on purpose (restart), so nothing here should care whether a `tmux` pane still shows the expected+ * engine — only whether the exact saved process is still the one running.+ */+export async function checkPidRuntime(+ session: Pick<RegisteredSession, 'engine' | 'processIdentity'>,+): Promise<RuntimeCheck> {+ const expected = session.processIdentity+ if (!expected) return { state: 'gone', reason: 'agent has no saved process identity' }+ const rows = await processRows()+ if (!rows) return { state: 'unknown', reason: 'process table is unavailable' }+ const live = rows.find((row) => row.pid === expected.pid)+ return live && live.startMarker === expected.startMarker && live.executable === expected.executable+ ? { state: 'alive' }+ : { state: 'gone', reason: 'saved process identity is no longer running' }+}+export type TerminateOutcome =/** It left before or during signalling. */| 'gone'diff --git a/cli/src/lib/e2ee/core.test.ts b/cli/src/lib/e2ee/core.test.tsindex 94bfeabba..705389288 100644--- a/cli/src/lib/e2ee/core.test.ts+++ b/cli/src/lib/e2ee/core.test.ts@@ -187,6 +187,6 @@ describe('e2ee core — interop keystone', () => {it('core.ts still hashes to the pinned value shared with the other implementations', () => {const here = dirname(fileURLToPath(import.meta.url))const actual = createHash('sha256').update(readFileSync(join(here, 'core.ts'))).digest('hex')- expect(actual).toBe('5ce871815e610561cd829fc7dd7c5f280767e95355a05dacc996fb902d7ee11f')+ expect(actual).toBe('7f348978c7900f3221f4e77555ed2bbf9606ff1740562587d6d908d95bbd7ac3')})})diff --git a/cli/src/lib/e2ee/core.ts b/cli/src/lib/e2ee/core.tsindex ad7c987dd..ddbff7406 100644--- a/cli/src/lib/e2ee/core.ts+++ b/cli/src/lib/e2ee/core.ts@@ -349,7 +349,7 @@ export const ENCRYPTED_RPC_RESULT_TYPES = new Set<string>(['e2ee_pairings_unpair_all_result', 'e2ee_browser_link_create_result',// Device RPC replies that carry adapter content (recap headline/body, new agent name). Must be// ciphertext so the backend relay can't read them — device↔adapter E2EE parity with web.- 'agent_recent_result', 'agent_create_result',+ 'agent_recent_result', 'agent_create_result', 'agent_restart_result',// A remote-machine directory listing (New Agent folder browser) — leaks filesystem layout if plaintext.'fs_list_dir_result',])@@ -362,7 +362,7 @@ export const ENCRYPTED_DOWN_TYPES = new Set<string>([// as "no session/answers", the pane dialog was never keyed, and the CLI waited on question 1 forever.'question_response','agents_list', 'sessions_list', 'session_get', 'models_list',- 'agent_create', 'agent_delete', 'agent_recent', 'agent_update', 'agent_files', 'agent_read_file',+ 'agent_create', 'agent_delete', 'agent_restart', 'agent_recent', 'agent_update', 'agent_files', 'agent_read_file','fs_list_dir','device_e2ee_pair', 'e2ee_pairings_list', 'e2ee_pairing_unpair','e2ee_pairings_unpair_all', 'e2ee_browser_link_create',diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.tsindex 8482f8989..deb8e4e9c 100644--- a/cli/src/lib/engineLaunch.spec.ts+++ b/cli/src/lib/engineLaunch.spec.ts@@ -4,6 +4,7 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import {BYPASS_PERMISSION_FLAGS,+ LAUNCH_RESUME_FLAG,buildEngineCommandArgv,buildEngineLaunchArgv,commandAvailableInInteractiveShell,@@ -50,6 +51,39 @@ describe('buildEngineLaunchArgv', () => {expect(Object.prototype.hasOwnProperty.call(BYPASS_PERMISSION_FLAGS, engine)).toBe(true)}})++ it('appends a flag-style resume argument after the binary', () => {+ expect(buildEngineCommandArgv('claude', { resumeSessionId: 'abc-123' }))+ .toEqual([engineBin('claude'), '--resume', 'abc-123'])+ expect(buildEngineCommandArgv('opencode', { resumeSessionId: 'ses_1' }))+ .toEqual([engineBin('opencode'), '--session', 'ses_1'])+ })++ it('puts a subcommand-style resume FIRST, ahead of any other flag', () => {+ expect(buildEngineCommandArgv('codex', { resumeSessionId: 'abc-123' }))+ .toEqual([engineBin('codex'), 'resume', 'abc-123'])+ expect(buildEngineCommandArgv('codex', { resumeSessionId: 'abc-123', bypassPermission: true }))+ .toEqual([engineBin('codex'), 'resume', 'abc-123', '--dangerously-bypass-approvals-and-sandbox'])+ expect(buildEngineCommandArgv('amp', { resumeSessionId: 'T-1' }))+ .toEqual([engineBin('amp'), 'threads', 'continue', 'T-1'])+ })++ it('still applies bypassPermission with no resume requested (regression)', () => {+ expect(buildEngineCommandArgv('claude', { bypassPermission: true }))+ .toEqual([engineBin('claude'), '--dangerously-skip-permissions'])+ })++ it('is a no-op when resumeSessionId is set but the engine has no known launch resume flag', () => {+ expect(buildEngineCommandArgv('devin', { resumeSessionId: 'abc-123' })).toEqual([engineBin('devin')])+ })++ it('has a launch resume flag for every engine RESUME_ARGS also covers, plus claude/codex', () => {+ for (const engine of ['claude', 'codex', 'cursor', 'opencode', 'kilo', 'pi', 'hermes', 'commandcode',+ 'muse', 'amp', 'grok', 'agy', 'copilot'] as const) {+ expect(LAUNCH_RESUME_FLAG[engine]?.length).toBeGreaterThan(0)+ }+ expect(LAUNCH_RESUME_FLAG.devin).toBeUndefined()+ })})const dirs: string[] = []diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.tsindex 5a4f08296..1e75e718d 100644--- a/cli/src/lib/engineLaunch.ts+++ b/cli/src/lib/engineLaunch.ts@@ -30,15 +30,62 @@ export const BYPASS_PERMISSION_FLAGS: Readonly<Record<AgentEngine, string[] | nuexport interface LaunchCommandOptions {bypassPermission?: boolean+ /** Resume this engine session id on launch, when a launch-resume flag is known for the engine. */+ resumeSessionId?: string+}++/**+ * Best-known "resume this session id" launch flag per engine — kept SEPARATE from tmux.ts's+ * `RESUME_ARGS` (parsing-only, reverse-engineered from an already-running process's argv, never proven+ * as a launch argument). `claude` and `codex` are populated here from confirmed real invocations (see+ * the `resumeSessionId` test fixtures in tmux.spec.ts: `'claude --resume <id>'`, `'codex resume <id>'`)+ * even though `RESUME_ARGS` has no entry for either — that map's silence reflects that neither engine+ * ever needed argv-based repair (both fire their own SessionStart hook on resume), not an absent flag.+ * `amp` needs its full subcommand chain (`amp threads continue <id>`, confirmed by the same fixture+ * file) rather than the bare `continue` alternative `RESUME_ARGS` also accepts for parsing purposes.+ *+ * A wrong or unsupported entry here is not fatal: restart (cli.ts's `onRestartAgent`) falls back to a+ * fresh, no-resume relaunch automatically if the flagged relaunch doesn't produce a recognizable+ * process within budget — a working agent under a fresh session beats a dead pane.+ *+ * A leading token that does NOT start with `-` is a SUBCOMMAND (`resume`, `threads continue`) and must+ * be the first argv after the binary, ahead of any other flag — `buildEngineCommandArgv` branches on+ * this. `devin` has no known resume flag at all (not even for `RESUME_ARGS` parsing) and is+ * deliberately omitted, so no resume is ever attempted for it.+ */+export const LAUNCH_RESUME_FLAG: Readonly<Partial<Record<AgentEngine, string[]>>> = {+ claude: ['--resume'],+ codex: ['resume'],+ cursor: ['--resume'],+ opencode: ['--session'],+ kilo: ['--session'],+ pi: ['--session'],+ hermes: ['--resume'],+ commandcode: ['--resume'],+ muse: ['resume'],+ amp: ['threads', 'continue'],+ grok: ['--resume'],+ agy: ['--conversation'],+ copilot: ['--resume'],}/** The executable argv, before the interactive-shell wrapper is applied. */export function buildEngineCommandArgv(engine: AgentEngine, opts: LaunchCommandOptions = {}): string[] {const argv = [engineBin(engine)]+ const resumeFlag = opts.resumeSessionId ? LAUNCH_RESUME_FLAG[engine] : undefined+ const resumeIsSubcommand = !!resumeFlag?.length && !resumeFlag[0].startsWith('-')+ // Subcommand-style resume (`codex resume <id>`, `amp threads continue <id>`, `muse resume <id>`) is+ // parsed positionally and must be the first argv after the binary, ahead of any other flag.+ if (resumeIsSubcommand && resumeFlag && opts.resumeSessionId) {+ argv.push(...resumeFlag, opts.resumeSessionId)+ }if (opts.bypassPermission) {const flags = BYPASS_PERMISSION_FLAGS[engine]if (flags) argv.push(...flags)}+ if (!resumeIsSubcommand && resumeFlag && opts.resumeSessionId) {+ argv.push(...resumeFlag, opts.resumeSessionId)+ }return argv}diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.tsindex 8c2d1b56e..f14dc76c2 100644--- a/cli/src/lib/registry.spec.ts+++ b/cli/src/lib/registry.spec.ts@@ -768,6 +768,45 @@ describe('agent identity: the process owns the agent, the session is bound to itexpect(registry.resolve('s1')?.agentId).toBe('agent-1')})+ it('restart contract: updateProcessIdentity swaps ONLY the process, keeping agentId/sessionId/runtimes', async () => {+ // This is the primitive a restart handler relies on: exit the engine process, relaunch it in the+ // same pane, and rebind the SAME agent to the new process — never look like delete+create.+ const { registry } = await loadRegistryModule()+ registry.load()+ registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })+ const before = registry.resolve('agent-1')!+ // Registry entries are mutated in place (resolve() returns the live object), so the "before"+ // snapshot has to be copied — not just referenced — ahead of the swap.+ const beforeRuntimes = [...before.runtimes]+ const beforePrimary = before.primaryRuntimeKey+ const beforeIdentity = { ...before.processIdentity }++ const replacement = processIdentity(999)+ const ok = registry.updateProcessIdentity('agent-1', replacement)++ expect(ok).toBe(true)+ const after = registry.resolve('agent-1')!+ expect(after.agentId).toBe('agent-1')+ expect(after.sessionId).toBe('s1')+ expect(after.runtimes).toEqual(beforeRuntimes)+ expect(after.primaryRuntimeKey).toBe(beforePrimary)+ expect(after.processIdentity).toEqual(replacement)+ expect(after.processIdentity).not.toEqual(beforeIdentity)+ // Both lookups still resolve to the one record — swapping the process never splits the agent.+ expect(registry.resolve('s1')?.agentId).toBe('agent-1')+ expect(registry.list()).toHaveLength(1)+ })++ it('restart contract: updateProcessIdentity also resolves by bare sessionId', async () => {+ const { registry } = await loadRegistryModule()+ registry.load()+ registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })++ expect(registry.updateProcessIdentity('s1', processIdentity(999))).toBe(true)++ expect(registry.byAgent('agent-1')?.processIdentity).toEqual(processIdentity(999))+ })+it('does not advertise persisted terminal locators before this daemon verifies them', async () => {const { registry } = await loadRegistryModule()registry.load()diff --git a/cli/src/lib/restartAgent.spec.ts b/cli/src/lib/restartAgent.spec.tsnew file mode 100644index 000000000..9a78bc4aa--- /dev/null+++ b/cli/src/lib/restartAgent.spec.ts@@ -0,0 +1,126 @@+import { describe, expect, it, vi } from 'vitest'+import { restartAgent, type RestartAgentDeps } from './restartAgent.js'+import type { ProcessIdentity } from './registry.js'++const IDENTITY: ProcessIdentity = { pid: 555, executable: 'claude', startMarker: 'Mon Aug 3 09:05:00 2026' }++interface Overrides {+ holdOpen?: RestartAgentDeps['holdOpen']+ terminate?: RestartAgentDeps['terminate']+ respawn?: RestartAgentDeps['respawn']+ waitForProcess?: RestartAgentDeps['waitForProcess']+ buildArgv?: RestartAgentDeps['buildArgv']+}++/** Every primitive records its own call, even when overridden — so `calls` always reflects the real+ * order regardless of which primitive a test customizes the return value of. */+function deps(over: Overrides = {}): RestartAgentDeps & { calls: string[] } {+ const calls: string[] = []+ const holdOpenImpl = over.holdOpen ?? (async () => ({ ok: true }))+ const terminateImpl = over.terminate ?? (async () => 'terminated' as const)+ const respawnImpl = over.respawn ?? (async () => ({ ok: true }))+ const waitForProcessImpl = over.waitForProcess ?? (async () => IDENTITY)+ const buildArgvImpl = over.buildArgv ?? (() => ['claude'])+ return {+ calls,+ holdOpen: async () => { calls.push('holdOpen'); return holdOpenImpl() },+ terminate: async (checkAfterMs) => { calls.push('terminate'); return terminateImpl(checkAfterMs) },+ respawn: async (argv) => { calls.push('respawn'); return respawnImpl(argv) },+ waitForProcess: async () => { calls.push('waitForProcess'); return waitForProcessImpl() },+ buildArgv: (opts) => { calls.push('buildArgv'); return buildArgvImpl(opts) },+ log: () => {},+ }+}++describe('restartAgent', () => {+ it('holds the pane open, kills, respawns, and verifies — in that order', async () => {+ const d = deps()+ const outcome = await restartAgent({ engine: 'claude', sessionId: 's1' }, false, d)+ expect(outcome).toEqual({ ok: true, processIdentity: IDENTITY, resumed: true })+ expect(d.calls).toEqual(['holdOpen', 'terminate', 'buildArgv', 'respawn', 'waitForProcess'])+ })++ it('never respawns when holdOpen fails to re-arm the pane', async () => {+ const d = deps({ holdOpen: async () => ({ ok: false, reason: 'tmux unreachable' }) })+ const outcome = await restartAgent({ engine: 'claude', sessionId: 's1' }, false, d)+ expect(outcome).toEqual({ ok: false, detail: 'tmux unreachable' })+ expect(d.calls).toEqual(['holdOpen'])+ })++ it('never respawns over a kill that could not be confirmed (not-ours)', async () => {+ const d = deps({ terminate: async () => 'not-ours' })+ const outcome = await restartAgent({ engine: 'claude', sessionId: 's1' }, false, d)+ expect(outcome.ok).toBe(false)+ expect(d.calls).toEqual(['holdOpen', 'terminate'])+ })++ it('never respawns over a kill that failed', async () => {+ const d = deps({ terminate: async () => 'failed' })+ const outcome = await restartAgent({ engine: 'claude', sessionId: 's1' }, false, d)+ expect(outcome.ok).toBe(false)+ expect(d.calls).toEqual(['holdOpen', 'terminate'])+ })++ it('treats "gone" (the process had already exited) as a confirmed kill, safe to respawn over', async () => {+ const d = deps({ terminate: async () => 'gone' })+ const outcome = await restartAgent({ engine: 'claude', sessionId: 's1' }, false, d)+ expect(outcome.ok).toBe(true)+ })++ it('passes the resolved sessionId as resumeSessionId on the first attempt', async () => {+ const argvCalls: Array<{ bypassPermission: boolean; resumeSessionId?: string }> = []+ const d = deps({ buildArgv: (opts) => { argvCalls.push(opts); return ['claude'] } })+ await restartAgent({ engine: 'claude', sessionId: 'sess-42' }, true, d)+ expect(argvCalls).toEqual([{ bypassPermission: true, resumeSessionId: 'sess-42' }])+ })++ it('launches fresh (no resumeSessionId) when the session has none', async () => {+ const argvCalls: Array<{ bypassPermission: boolean; resumeSessionId?: string }> = []+ const d = deps({ buildArgv: (opts) => { argvCalls.push(opts); return ['claude'] } })+ const outcome = await restartAgent({ engine: 'claude', sessionId: '' }, false, d)+ expect(argvCalls).toEqual([{ bypassPermission: false }])+ expect(outcome).toMatchObject({ ok: true, resumed: false })+ })++ it('falls back to a fresh relaunch when the resumed relaunch never produces a recognizable process', async () => {+ let attempt = 0+ const argvCalls: Array<{ bypassPermission: boolean; resumeSessionId?: string }> = []+ const d = deps({+ buildArgv: (opts) => { argvCalls.push(opts); return ['claude'] },+ waitForProcess: async () => { attempt += 1; return attempt === 1 ? null : IDENTITY },+ })+ const outcome = await restartAgent({ engine: 'claude', sessionId: 'sess-42' }, false, d)+ expect(argvCalls).toEqual([+ { bypassPermission: false, resumeSessionId: 'sess-42' },+ { bypassPermission: false },+ ])+ expect(outcome).toEqual({ ok: true, processIdentity: IDENTITY, resumed: false })+ // respawn + waitForProcess ran twice (once per attempt); holdOpen/terminate ran once.+ expect(d.calls.filter((c) => c === 'respawn')).toHaveLength(2)+ expect(d.calls.filter((c) => c === 'holdOpen')).toHaveLength(1)+ expect(d.calls.filter((c) => c === 'terminate')).toHaveLength(1)+ })++ it('fails outright when even the fresh fallback relaunch never comes up', async () => {+ const d = deps({ waitForProcess: async () => null })+ const outcome = await restartAgent({ engine: 'codex', sessionId: 'sess-1' }, false, d)+ expect(outcome).toEqual({ ok: false, detail: 'codex did not come back up after restart' })+ })++ it('never retries a resume fallback for an engine with no session to resume in the first place', async () => {+ let respawnCalls = 0+ const d = deps({+ respawn: async () => { respawnCalls += 1; return { ok: true } },+ waitForProcess: async () => null,+ })+ await restartAgent({ engine: 'claude', sessionId: '' }, false, d)+ expect(respawnCalls).toBe(1) // no resume attempt to fall back FROM+ })++ it('does not poll for a process when respawn-pane itself fails', async () => {+ const d = deps({ respawn: async () => ({ ok: false, reason: 'tmux respawn-pane did not complete' }) })+ const outcome = await restartAgent({ engine: 'claude', sessionId: 's1' }, false, d)+ expect(outcome.ok).toBe(false)+ expect(d.calls).not.toContain('waitForProcess')+ })+})diff --git a/cli/src/lib/restartAgent.ts b/cli/src/lib/restartAgent.tsnew file mode 100644index 000000000..fb1601c84--- /dev/null+++ b/cli/src/lib/restartAgent.ts@@ -0,0 +1,85 @@+/**+ * Stop an agent's live engine process and relaunch it in the SAME tmux pane, preserving the pane/agent+ * identity and (best-effort) resuming the same engine conversation.+ *+ * Factored out of cli.ts's `onRestartAgent` the same way deleteAgentFallback.ts factors out delete's+ * kill sequence: a small, dependency-injected core so the kill → respawn → verify → fallback ordering+ * can be exercised without the daemon's registry, tmux, and reconciler wiring. cli.ts owns everything+ * registry-shaped around a call to this function — resolving the session, `agentReconciler.holdRoute` /+ * `releaseRoute`, `registry.updateProcessIdentity`, `clearPaneRemainOnExit`, and `announceSession`.+ */++import type { AgentEngine } from '../engines/types.js'+import type { ProcessIdentity } from './registry.js'+import type { TerminateOutcome } from './deleteAgentFallback.js'++export type RestartOutcome =+ | { ok: true; processIdentity: ProcessIdentity; resumed: boolean }+ | { ok: false; detail: string }++export interface RestartAgentDeps {+ /** Re-arm `remain-on-exit` before anything is killed — see `tmuxBackend.ts`'s `holdOpen`. Without+ * this, tmux tears the pane (and, being its only pane, the whole session) down the instant the old+ * process exits. */+ holdOpen: () => Promise<{ ok: boolean; reason?: string }>+ /** Validate + SIGTERM/SIGKILL the saved process. Same contract as `terminateDeletedAgent`. */+ terminate: (checkAfterMs?: number) => Promise<TerminateOutcome>+ /** `tmux respawn-pane` (or equivalent) with a fully-built argv. */+ respawn: (argv: string[]) => Promise<{ ok: boolean; reason?: string }>+ /** Poll the pane for a recognizable engine process, up to an internal budget. Null on timeout. */+ waitForProcess: () => Promise<ProcessIdentity | null>+ buildArgv: (opts: { bypassPermission: boolean; resumeSessionId?: string }) => string[]+ log: (message: string) => void+}++/** Outcomes that mean the old process is confirmed gone — safe to respawn over the pane. `not-ours` and+ * `failed` are NOT here on purpose: never respawn over a target the kill sequence could not confirm. */+const KILL_CONFIRMED: ReadonlySet<TerminateOutcome> = new Set(['gone', 'terminated', 'killed'])++export async function restartAgent(+ session: { engine: AgentEngine; sessionId: string },+ bypassPermission: boolean,+ deps: RestartAgentDeps,+): Promise<RestartOutcome> {+ const armed = await deps.holdOpen()+ if (!armed.ok) {+ return { ok: false, detail: armed.reason ?? 'could not re-arm the pane before restart' }+ }++ const outcome = await deps.terminate()+ if (!KILL_CONFIRMED.has(outcome)) {+ return { ok: false, detail: `could not confirm the running ${session.engine} process was stopped (${outcome})` }+ }++ const resumeSessionId = session.sessionId || undefined+ const spawnAndWait = async (withResume: boolean): Promise<ProcessIdentity | null> => {+ const argv = deps.buildArgv({+ bypassPermission,+ ...(withResume && resumeSessionId ? { resumeSessionId } : {}),+ })+ const spawned = await deps.respawn(argv)+ if (!spawned.ok) {+ deps.log(`[restart] ${session.engine} respawn-pane failed: ${spawned.reason ?? 'unknown reason'}`)+ return null+ }+ return deps.waitForProcess()+ }++ // Attempt a resume relaunch whenever we have a session id to resume, for every engine — an+ // unconfirmed/wrong flag is not fatal because of the fallback below. Engines with no known launch+ // resume flag never spawn a resume argv in the first place (buildArgv's `resumeSessionId` is a no-op+ // when LAUNCH_RESUME_FLAG has no entry for the engine), so `resumed` still degrades correctly.+ let resumed = !!resumeSessionId+ let identity = await spawnAndWait(resumed)+ if (!identity && resumed) {+ // Safe degradation: a working agent with a FRESH session under the same agentId/pane beats a dead+ // pane. Retry once with no resume attempt before giving up entirely.+ deps.log(`[restart] ${session.engine} did not come back up resuming its session — retrying fresh`)+ resumed = false+ identity = await spawnAndWait(false)+ }+ if (!identity) {+ return { ok: false, detail: `${session.engine} did not come back up after restart` }+ }+ return { ok: true, processIdentity: identity, resumed }+}diff --git a/cli/src/lib/terminalAgentReconciler.spec.ts b/cli/src/lib/terminalAgentReconciler.spec.tsindex fc30a7b23..f16776a49 100644--- a/cli/src/lib/terminalAgentReconciler.spec.ts+++ b/cli/src/lib/terminalAgentReconciler.spec.ts@@ -226,6 +226,82 @@ describe('composite terminal reconciliation', () => {})})+describe('restart route hold', () => {+ it('skips dormant-detection for a held route while a restart is in progress', async () => {+ const current = session([tmux])+ const onDormant = vi.fn()+ const onRemoved = vi.fn()+ // Same shape as "keeps a pane advertised but marks its missing engine dormant after two scans"+ // above: the pane's terminal placement validates alive, but no engine process is ever observed —+ // ordinarily that drives the agent dormant after MISS_LIMIT scans.+ const validate = vi.fn(async () => ({ state: 'alive' as const }))+ const backend = { instanceId: 'tmux:default', validate } as unknown as TerminalBackend+ const reconciler = new TerminalAgentReconciler({+ current: () => [current], backends: [backend], backendOrder: ['tmux'], herdrSessionOrder: [],+ onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant, onRemoved,+ probe: async () => probe([{ instanceId: 'tmux:default', result: { state: 'available', roots: [] } }]),+ })+ reconciler.holdRoute(terminalRouteKey(tmux))++ await reconciler.trigger()+ await reconciler.trigger()+ await reconciler.trigger()++ expect(onDormant).not.toHaveBeenCalled()+ expect(onRemoved).not.toHaveBeenCalled()+ expect(validate).not.toHaveBeenCalled()+ })++ it('does not open the replacement process as a new agent while its route is held', async () => {+ const current = session([tmux])+ const replacement = {+ ...observed([tmux]),+ processIdentity: { pid: 99, executable: 'claude', startMarker: 'Sat Aug 15 10:05:00 2026' },+ }+ const onDiscovered = vi.fn()+ const onObserved = vi.fn()+ const reconciler = new TerminalAgentReconciler({+ current: () => [current], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],+ onDiscovered, onObserved, onDormant: vi.fn(), onRemoved: vi.fn(),+ probe: async () => probe(+ [{ instanceId: 'tmux:default', result: { state: 'available', roots: [{ runtime: tmux, rootPid: 1, cwd: '/work' }] } }],+ [replacement],+ ),+ })+ reconciler.holdRoute(terminalRouteKey(tmux))++ await reconciler.trigger()++ expect(onDiscovered).not.toHaveBeenCalled()+ // The pre-existing agent isn't rebound through ordinary observation either — the restart handler+ // owns that via `registry.updateProcessIdentity` once it confirms the new process itself.+ expect(onObserved).not.toHaveBeenCalled()+ })++ it('resumes normal reconciliation once the route is released', async () => {+ const current = session([tmux])+ const onDormant = vi.fn()+ const validate = vi.fn(async () => ({ state: 'alive' as const }))+ const backend = { instanceId: 'tmux:default', validate } as unknown as TerminalBackend+ const reconciler = new TerminalAgentReconciler({+ current: () => [current], backends: [backend], backendOrder: ['tmux'], herdrSessionOrder: [],+ onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant, onRemoved: vi.fn(),+ probe: async () => probe([{ instanceId: 'tmux:default', result: { state: 'available', roots: [] } }]),+ })+ const routeKey = terminalRouteKey(tmux)+ reconciler.holdRoute(routeKey)+ await reconciler.trigger()+ expect(onDormant).not.toHaveBeenCalled()+ expect(validate).not.toHaveBeenCalled()++ reconciler.releaseRoute(routeKey)+ await reconciler.trigger()+ await reconciler.trigger()++ expect(onDormant).toHaveBeenCalledTimes(1)+ })+})+describe('verified process adoption', () => {it('opens a sessionless agent through the normal discovery callback without another inventory scan', async () => {let current: RegisteredSession[] = []diff --git a/cli/src/lib/terminalAgentReconciler.ts b/cli/src/lib/terminalAgentReconciler.tsindex 13871218a..3ed22deff 100644--- a/cli/src/lib/terminalAgentReconciler.ts+++ b/cli/src/lib/terminalAgentReconciler.ts@@ -77,6 +77,11 @@ export class TerminalAgentReconciler {private readonly engineMisses = new Map<string, number>()private readonly suppressed = new Set<string>()private readonly hints = new Map<string, AgentEngine>()+ /** Terminal routes currently mid an in-place process swap (restart). Held by ROUTE, not by process+ * identity like `suppressed` — the replacement process's identity is not known until the swap+ * finishes, so there is nothing to key a process-identity suppression on yet. */+ private readonly heldRoutes = new Set<string>()+ private readonly heldRouteTimers = new Map<string, NodeJS.Timeout>()private pending = falseprivate inFlight: Promise<void> | null = nullprivate timer: NodeJS.Timeout | null = null@@ -128,6 +133,40 @@ export class TerminalAgentReconciler {if (session.processIdentity) this.suppressed.add(processIdentityKey(session.engine, session.processIdentity))}+ /**+ * Hide one terminal route from BOTH halves of reconciliation — the existing-agent liveness/dormant+ * loop and new-process discovery — for the duration of an in-place process swap (restart). Without+ * this, the old process going away can flicker the agent dormant mid-kill, and the replacement+ * process appearing in the same pane before the restart handler rebinds it would otherwise be opened+ * as a brand-new agent (`onDiscovered` mints a fresh `agentId`).+ *+ * `autoReleaseMs` is a belt-and-suspenders bound: the caller is expected to `releaseRoute` in a+ * `finally`, but a future refactor that drops that `finally` must not leave a route permanently+ * invisible to reconciliation.+ */+ holdRoute(routeKey: string, autoReleaseMs = 30_000): void {+ this.heldRoutes.add(routeKey)+ const existing = this.heldRouteTimers.get(routeKey)+ if (existing) clearTimeout(existing)+ const timer = setTimeout(() => this.releaseRoute(routeKey), autoReleaseMs)+ timer.unref?.()+ this.heldRouteTimers.set(routeKey, timer)+ }++ /** Resume normal reconciliation for a route held by `holdRoute`. Idempotent. */+ releaseRoute(routeKey: string): void {+ this.heldRoutes.delete(routeKey)+ const timer = this.heldRouteTimers.get(routeKey)+ if (timer) {+ clearTimeout(timer)+ this.heldRouteTimers.delete(routeKey)+ }+ }++ private routeHeld(runtimes: readonly TerminalRuntimeRef[]): boolean {+ return runtimes.some((runtime) => this.heldRoutes.has(terminalRouteKey(runtime)))+ }+trigger(): Promise<void> {this.pending = trueif (!this.inFlight) this.inFlight = this.drain().finally(() => { this.inFlight = null })@@ -196,6 +235,10 @@ export class TerminalAgentReconciler {// Refresh existing process identities first. New route owners are opened afterwards so split/merge// conflict handling never depends on backend probe completion order.for (const current of before) {+ // A restart in progress on this route: leave it untouched. The old process going dormant here+ // and the new one being adopted by the discovery loop below are both races restart's `holdRoute`+ // exists to prevent — see the class-level comment on `heldRoutes`.+ if (this.routeHeld(current.runtimes)) continueconst processKey = currentProcessKey(current)const observed = (processKey ? observedByProcess.get(processKey) : undefined)?? unboundRouteObservation(current, probe.agents)@@ -306,7 +349,11 @@ export class TerminalAgentReconciler {for (const observed of probe.agents) {const key = processIdentityKey(observed.engine, observed.processIdentity)- if (!matchedProcesses.has(key)) await this.deps.onDiscovered(observed)+ if (matchedProcesses.has(key)) continue+ // The replacement process for a restart in progress: the restart handler will bind it via+ // `updateProcessIdentity` itself once confirmed, not through ordinary discovery.+ if (this.routeHeld(observed.runtimes)) continue+ await this.deps.onDiscovered(observed)}}diff --git a/cli/src/lib/terminalBackend.ts b/cli/src/lib/terminalBackend.tsindex 169363330..f0cbeef2d 100644--- a/cli/src/lib/terminalBackend.ts+++ b/cli/src/lib/terminalBackend.ts@@ -40,4 +40,11 @@ export interface TerminalBackend<Ref extends TerminalRuntimeRef = TerminalRuntimsize: TerminalStreamSize,sink: TerminalStreamSink,): Promise<TerminalReadResult<TerminalStreamHandle<Ref>>>++ /** Restart's two primitives. Optional per backend — only tmux (a real multiplexer pane) supports an+ * in-place process swap; a backend without them makes restart report RESTART_UNSUPPORTED_BACKEND. */+ /** Re-arm a pane's "keep it when the process dies" behavior ahead of killing that process. */+ holdOpen?(runtime: Ref): Promise<TerminalActionResult>+ /** Replace the process occupying an existing pane/session in place, preserving its identity. */+ respawn?(runtime: Ref, command: string[], cwd: string | null): Promise<TerminalActionResult>}diff --git a/cli/src/lib/tmux.spec.ts b/cli/src/lib/tmux.spec.tsindex 1e016abf8..f319d5901 100644--- a/cli/src/lib/tmux.spec.ts+++ b/cli/src/lib/tmux.spec.ts@@ -6,6 +6,7 @@ import { ENGINES } from '../engines/types.js'import type { AgentCommandOwnershipSnapshot } from './engineBin.js'import {ambiguousAgentProcess,+ bypassPermissionActive,engineProcessMatch,engineProcessMatchScore,parseProcessRow,@@ -218,6 +219,32 @@ describe('tmux process primitives', () => {expect(resumeSessionId('devin', 'devin --resume 53d3843c-724e-47ff-ae3a-9fedfa328bba')).toBeNull()})+ it('reads bypass-permission mode from a live process argv via exact token match', () => {+ expect(bypassPermissionActive('claude', '/usr/local/bin/claude --dangerously-skip-permissions'))+ .toBe(true)+ expect(bypassPermissionActive('codex', 'codex --dangerously-bypass-approvals-and-sandbox'))+ .toBe(true)+ expect(bypassPermissionActive('cursor', 'cursor-agent --force')).toBe(true)+ expect(bypassPermissionActive('opencode', 'opencode --auto')).toBe(true)+ })++ it('does not false-positive on a flag that only appears as a substring', () => {+ // The flag text can legitimately appear inside a prompt/argument; only an exact token counts.+ expect(bypassPermissionActive('claude', 'claude "please avoid --dangerously-skip-permissions for now"'))+ .toBe(false)+ expect(bypassPermissionActive('claude', 'claude --dangerously-skip-permissions-explained')).toBe(false)+ })++ it('reads false when the confirmed flag is absent', () => {+ expect(bypassPermissionActive('claude', 'claude --resume abc')).toBe(false)+ })++ it('always reads false for engines with no confirmed bypass flag — never guesses', () => {+ expect(bypassPermissionActive('pi', 'pi --dangerously-skip-permissions')).toBe(false)+ expect(bypassPermissionActive('hermes', 'hermes --dangerously-skip-permissions')).toBe(false)+ expect(bypassPermissionActive('devin', 'devin --dangerously-skip-permissions')).toBe(false)+ })+it('maps neutral visible/history and ANSI capture options to tmux flags', () => {expect(tmuxCaptureArgs('%7', 60)).toEqual(['capture-pane', '-p', '-e', '-J', '-t', '%7', '-S', '-60',diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.tsindex 114ca2303..4381461d0 100644--- a/cli/src/lib/tmux.ts+++ b/cli/src/lib/tmux.ts@@ -14,6 +14,7 @@ import {executableFileIdentity,type AgentCommandOwnershipSnapshot,} from './engineBin.js'+import { BYPASS_PERMISSION_FLAGS } from './engineLaunch.js'function cleanPaneTitle(title: string): string | null {const cleaned = title@@ -52,7 +53,7 @@ export interface ProcessRow extends ProcessIdentity {entrypointFileKey?: string}-function argvTokens(args: string): string[] {+export 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@@ -564,6 +565,21 @@ const RESUME_ARGS: Partial<Record<RegisteredSession['engine'], { flags: string[]copilot: { flags: ['--resume', '--session-id'], id: /^[0-9a-f-]{16,}$/i },}+/**+ * Whether a live process's argv already contains every flag this engine's confirmed bypass-permission+ * mode requires — read from the running process BEFORE restart signals it, so the relaunch can reapply+ * the exact autonomy mode the agent had (there is nowhere else to read it from once the process is+ * dead). Token-exact via `argvTokens`, not a substring `.includes()` check on the raw string, so a+ * prompt or argument that merely CONTAINS the flag text cannot false-positive. Engines with no+ * confirmed bypass flag (`BYPASS_PERMISSION_FLAGS[engine] === null`) always read false — never guess.+ */+export function bypassPermissionActive(engine: RegisteredSession['engine'], args: string): boolean {+ const flags = BYPASS_PERMISSION_FLAGS[engine]+ if (!flags) return false+ const tokens = argvTokens(args)+ return flags.every((flag) => tokens.includes(flag))+}+/** The session id an engine was told to resume, or null when argv does not name one. */export function resumeSessionId(engine: RegisteredSession['engine'], args: string): string | null {const spec = RESUME_ARGS[engine]diff --git a/cli/src/lib/tmuxBackend.spec.ts b/cli/src/lib/tmuxBackend.spec.tsindex df1d1476f..7741467dd 100644--- a/cli/src/lib/tmuxBackend.spec.ts+++ b/cli/src/lib/tmuxBackend.spec.ts@@ -81,6 +81,47 @@ exit 1expect(created.reason).toBe('tmux is unavailable')})+ it('re-arms remain-on-exit on an already-live pane for holdOpen', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-holdopen-'))+ dirs.push(dir)+ const calls = join(dir, 'calls')+ const tmux = join(dir, 'tmux')+ writeFileSync(tmux, `#!/bin/sh+printf '%s\\n' "$*" >> "$TMUX_BACKEND_CALLS"+`)+ chmodSync(tmux, 0o700)+ process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`+ process.env.TMUX_BACKEND_CALLS = calls++ await expect(new TmuxBackend().holdOpen({ backend: 'tmux', paneId: '%9' }))+ .resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })+ expect(readFileSync(calls, 'utf8').trim()).toBe('set-option -w -t %9 remain-on-exit on')+ })++ it('respawns a pane in place with -k, an optional cwd, and the exact argv, no shell', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-respawn-'))+ dirs.push(dir)+ const calls = join(dir, 'calls')+ const tmux = join(dir, 'tmux')+ writeFileSync(tmux, `#!/bin/sh+printf '%s\\n' "$*" >> "$TMUX_BACKEND_CALLS"+`)+ chmodSync(tmux, 0o700)+ process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`+ process.env.TMUX_BACKEND_CALLS = calls++ const backend = new TmuxBackend()+ await expect(backend.respawn({ backend: 'tmux', paneId: '%9' }, ['claude', '--resume', 'abc; rm -rf /'], '/tmp/work'))+ .resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })+ await expect(backend.respawn({ backend: 'tmux', paneId: '%9' }, ['claude'], null))+ .resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })+ expect(readFileSync(calls, 'utf8').trim().split('\n')).toEqual([+ // The `;` inside an argv element is never shell-interpreted — it lands as one literal token.+ 'respawn-pane -k -t %9 -c /tmp/work claude --resume abc; rm -rf /',+ 'respawn-pane -k -t %9 claude',+ ])+ })+it('displays a bounded message in the addressed pane without a shell', async () => {const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-notify-'))dirs.push(dir)diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.tsindex b578a1a38..33c5544b7 100644--- a/cli/src/lib/tmuxBackend.ts+++ b/cli/src/lib/tmuxBackend.ts@@ -129,6 +129,40 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {return legacyActionResult(ok, 'tmux session close')}+ /**+ * Re-arm `remain-on-exit` on an already-live pane, mirroring what `create()` does at spawn time.+ *+ * Restart must call this BEFORE killing the pane's engine process. `clearPaneRemainOnExit` turns+ * this off the moment an agent is first confirmed (see `cli.ts`'s `onCreateAgent`), so without+ * re-arming it here tmux destroys the pane — and, being its only pane, the whole session — the+ * instant the old process exits.+ */+ async holdOpen(runtime: TmuxRuntimeRef): Promise<TerminalActionResult> {+ const ok = await new Promise<boolean>((resolve) => {+ execFile('tmux', ['set-option', '-w', '-t', runtime.paneId, 'remain-on-exit', 'on'], { timeout: 2_000 }, (error) => {+ resolve(!error)+ })+ })+ return legacyActionResult(ok, 'tmux remain-on-exit re-arm')+ }++ /**+ * Replace the process running in an existing pane IN PLACE, preserving the pane/session — the tmux+ * primitive restart needs. `-k` is always passed: harmless on an already-dead pane (the normal case,+ * since the caller kills the old process itself first), and a safety net against anything that kill+ * sequence did not reach. Same unquoted-argv convention as `create()` — no shell interposition, so+ * engine paths/flags cannot be interpolated.+ */+ async respawn(runtime: TmuxRuntimeRef, command: string[], cwd: string | null): Promise<TerminalActionResult> {+ const args = ['respawn-pane', '-k', '-t', runtime.paneId]+ if (cwd) args.push('-c', cwd)+ args.push(...command)+ const ok = await new Promise<boolean>((resolve) => {+ execFile('tmux', args, { timeout: 5_000 }, (error) => resolve(!error))+ })+ return legacyActionResult(ok, 'tmux respawn-pane')+ }+async titles(): Promise<TerminalReadResult<Map<string, string>>> {const titles = await listPaneTitles()return {