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
Merge origin/main into feat/grid-agent-launch
Dev jacob616c5033ba28
diff --cc cli/src/backendSocket.tsindex f4feb7a95,174093b7b..4a94fe239--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@@ -294,23 -293,17 +294,35 @@@ export class BackendSocketonDeleteAgent: ((sessionId: string) => void) | null = null/** Called on `agent_create` — cli.ts spawns a fresh tmux session running the requested engine in the* requested folder and returns its process-agent. Session metadata may bind later through hooks. */- onCreateAgent: ((input: { engine: AgentEngine; cwd: string; bypassPermission: boolean }) =>+ onCreateAgent: ((input: {+ engine: AgentEngine+ cwd: string+ bypassPermission: boolean+ /** A grid to point this agent at instead of the engine's own login; null when none was chosen. */+ grid: GridLaunchOverride | null+ }) =>Promise<{ ok: true; session: RegisteredSession } | { ok: false; error: string; detail?: string }>) | null = null+ /**+ * Called on `agent_retarget` — cli.ts re-execs an EXISTING agent's pane against a different grid.+ *+ * Separate from `onCreateAgent` because it is a different promise: the pane, its id and its+ * scrollback survive, and only the process is replaced. A running process's environment cannot be+ * edited, so there is no gentler way to move an agent that is already up.++ *++ * Separate from `onRestartAgent` because that one puts the agent back exactly as it was; this one++ * puts it back somewhere else. They share the swap underneath and differ in what they hand it.+ */+ onRetargetAgent: ((input: { agentId: string; grid: GridLaunchOverride }) =>+ Promise<{ ok: true } | { 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. */diff --cc cli/src/cli.tsindex 13fab5293,047e54aa5..71425fcfa--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@@ -43,11 -43,9 +43,12 @@@ import { renderLoginSuccessHtml } fromimport { AuthSessionError, AuthSessionManager, clearAuthSession, readAuthSession, writeAuthSession, type AuthSession } from './lib/authSession.js'import { ENGINE_CLI_COMMANDS, ENGINES } from './lib/engineBin.js'import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell, interactiveEngineShell } from './lib/engineLaunch.js'+import { buildGridEngineLaunch, describeGridLaunch } from './lib/gridLaunch.js'+import { writeGridConfigDir } from './lib/gridConfigDir.js'+import { tmuxSupportsSessionEnv, TMUX_SESSION_ENV_MIN } from './lib/tmuxVersion.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 { restartAgent, type RestartAgentDeps } from './lib/restartAgent.js'import { findLiveSession } from './lib/sessionRepair.js'import { TmuxBackend } from './lib/tmuxBackend.js'import { basename } from 'node:path'@@@ -2000,10 -2040,23 +2044,24 @@@ async function runForeground(session: Acwd: observed.cwd,processIdentity: observed.processIdentity,gateway: observed.gateway,+ grid: observed.grid,})if (!opened) return- if (opened.evicted) console.log(`[discovery] ${observed.primaryRuntimeKey} replaced ${sid(opened.evicted)}`)+ if (opened.evicted) {+ console.log(`[discovery] ${observed.primaryRuntimeKey} replaced ${sid(opened.evicted.agentId)}`)+ // ⚠️ THE REGISTRY ALREADY DROPPED IT; NOBODY HAD TOLD THE CLIENTS. That+ // is the whole bug behind "two sessions, one of them frozen": resuming+ // an engine in a pane another agent owned takes the pane away, and an+ // agent with no pane can never be opened again — but the app kept the+ // row until someone hit Reload machines by hand, and opening it landed+ // on TERMINAL FROZEN. This is the same call the hook path already makes+ // for the same situation (see onRegistered below).+ forgetSession(opened.evicted.sessionId || opened.evicted.agentId, {+ force: true,+ agentId: opened.evicted.agentId,+ })+ }+if (opened.isNew) {console.log(`[discovery] ${sid(opened.entry.agentId)} opened · engine=${observed.engine} · terminal=${observed.primaryRuntimeKey}`)announceSession(opened.entry)@@@ -2877,114 -2889,6 +2935,174 @@@return { ok: false, error: 'ENGINE_DID_NOT_START', detail }}++ /**++ * The dependencies a pane-process swap needs, for both callers that do one.++ *++ * Restart and retarget are the same mechanism pointed at different ends: kill the engine, respawn it++ * in the pane it was already in, wait for the new process. They differ only in what the replacement++ * is launched WITH — retarget adds the grid's environment and the argv that configures it — so that++ * is the only thing this takes. Written once because two copies of a kill sequence drift, and the++ * half that drifts is the half nobody ran today.++ */++ const paneSwapDeps = (++ session: RegisteredSession,++ runtime: TmuxRuntimeRef,++ launch: { env?: Record<string, string>; extraArgs?: readonly string[] } = {},++ ): RestartAgentDeps => ({++ 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, {++ command: argv,++ ...(session.cwd ? { cwd: session.cwd } : {}),++ ...(launch.env ? { env: launch.env } : {}),++ })++ 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 SWAP_DISCOVERY_BUDGET_MS = 8_000++ let delayMs = 150++ let waited = 0++ while (waited < SWAP_DISCOVERY_BUDGET_MS) {++ await new Promise((resolve) => setTimeout(resolve, delayMs))++ waited += delayMs++ const found = await resolvePaneEngineProcess(runtime.paneId, session.engine)++ if (found) return found++ delayMs = Math.min(delayMs * 2, 750)++ }++ return null++ },++ buildArgv: (opts) => buildEngineLaunchArgv(session.engine, {++ ...opts,++ ...(launch.extraArgs?.length ? { extraArgs: launch.extraArgs } : {}),++ }),++ log: (message) => console.log(message),++ })++++ /** The bypass-permission mode the LIVE process was launched with — there is nowhere to read it from++ * once that process is dead, so both swap paths read it before signalling anything. */++ const liveBypassPermission = async (session: RegisteredSession): Promise<boolean> => {++ const identity = session.processIdentity++ if (!identity) return false++ const rows = await processRows()++ const row = rows?.find((candidate) =>++ candidate.pid === identity.pid && candidate.startMarker === identity.startMarker)++ return row ? bypassPermissionActive(session.engine, row.args) : false++ }+++ /**+ * Move a RUNNING agent onto a grid (`agent_retarget`).+ *+ * A process's environment is fixed at `execve`, so there is no way to re-point a live engine short of+ * replacing the process. `respawn-pane -k` does exactly that and keeps the pane, which keeps the pane+ * id, which keeps the agent's identity, its tile and its scrollback — the user sees their agent+ * restart, not a new agent appear. `--resume` brings the conversation back.+ *+ * Every check below refuses instead of doing something partial, because a half-applied move is+ * indistinguishable from a working one until the bill arrives.+ */+ backend.onRetargetAgent = async ({ agentId, grid }) => {+ if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }+ const session = registry.resolve(agentId)+ if (!session) return { ok: false, error: 'AGENT_NOT_FOUND' }+ const pane = session.runtimes.find((runtime): runtime is TmuxRuntimeRef => runtime.backend === 'tmux')+ // Only tmux panes can be respawned. A Herdr-hosted agent has no equivalent, and saying so is better+ // than a generic failure the user cannot act on.+ if (!pane) return { ok: false, error: 'RETARGET_UNSUPPORTED_BACKEND', detail: `${session.engine} is not running in a tmux pane` }++ // The swap kills a process it has validated by pid + start marker. Without one there is nothing to++ // validate, and respawning over a pane whose occupant we cannot identify is how you replace++ // something that was not ours.++ if (!session.processIdentity) return { ok: false, error: 'NO_ACTIVE_PROCESS' }+ const built = buildGridEngineLaunch(session.engine, grid)+ if (!built.ok) return { ok: false, error: built.error, detail: built.detail }+ if (!(await tmuxSupportsSessionEnv())) {+ return {+ ok: false,+ error: 'TMUX_TOO_OLD_FOR_GRID',+ detail: `this machine's tmux is older than ${TMUX_SESSION_ENV_MIN.major}.${TMUX_SESSION_ENV_MIN.minor}, `+ + 'which is the first version that can give a respawned pane its own environment.',+ }+ }+ // Mid-turn is the one state where restarting costs real work: the conversation comes back but+ // whatever the engine was doing does not. The app is told which agents these are so the user can+ // move them once they are done, rather than being asked to choose between losing a turn and losing+ // the grid.+ const capture = await captureTerminal(session.agentId, 100)+ if (!capture) return { ok: false, error: 'TMUX_FAILED' }+ if (!inspectRuntimePane(session.engine, capture).idle) return { ok: false, error: 'AGENT_BUSY' }+ // Nothing may type into the pane while it is being replaced.+ const release = acquireTerminalControl(session.agentId)+ if (!release) return { ok: false, error: 'AGENT_BUSY' }+ const gridEnv: Record<string, string> = { ...built.launch.env }+ if (built.launch.configDir) {+ // Keyed on the agent, so moving the same agent between grids rewrites one directory rather+ // than leaving a trail of them.+ const { envVar, files } = built.launch.configDir+ try {+ gridEnv[envVar] = await writeGridConfigDir(session.agentId, files)+ } catch (error) {++ release()+ const detail = `could not write ${session.engine}'s grid configuration · ${error instanceof Error ? error.message : error}`+ return { ok: false, error: 'GRID_CONFIG_FAILED', detail }+ }+ }++++ // ⚠️ THE AGENT MUST ADOPT THE NEW PROCESS, OR IT STOPS BEING THE SAME AGENT.++ //++ // Identity in this daemon is keyed on the PROCESS, not the pane: the reconciler matches an existing++ // record to an observation by pid + start marker (`currentProcessKey`), and its same-pane fallback++ // only applies to an agent with no bound engine session. A respawn changes the pid, so left to++ // discovery the new process is an unmatched observation — `onDiscovered` mints a NEW agent id, and++ // the record the user was looking at becomes a ghost that the app still lists, still counts as "on++ // an older target", and still offers to move. Moving it respawns the same pane again. Holding the++ // route shuts the reconciler out for the duration; rebinding below is what ends the swap.++ const routeKey = terminalRouteKey(pane)++ agentReconciler.holdRoute(routeKey)+ try {- const launchOptions = { resumeSessionId: session.sessionId || null, extraArgs: built.launch.args }- const respawned = await tmuxBackend.respawn(pane, {- ...(session.cwd ? { cwd: session.cwd } : {}),- command: buildEngineLaunchArgv(session.engine, launchOptions),- env: gridEnv,- })- if (respawned.state !== 'succeeded') {- console.warn(`[grid] retarget ${sid(session.agentId)} failed · ${respawned.reason}`)- return { ok: false, error: 'RESPAWN_FAILED', detail: respawned.reason }++ const outcome = await restartAgent(++ { engine: session.engine, sessionId: session.sessionId },++ await liveBypassPermission(session),++ paneSwapDeps(session, pane, { env: gridEnv, extraArgs: built.launch.args }),++ )++ if (!outcome.ok) {++ console.warn(`[grid] retarget ${sid(session.agentId)} failed · ${outcome.detail}`)++ return { ok: false, error: 'RESPAWN_FAILED', detail: outcome.detail }+ }- console.log(`${describeGridLaunch(session.engine, grid)} · retargeted ${sid(session.agentId)}`)++ // Both are read from the one cached environment of the new pid, so this costs no extra `ps`.++ const [gateway, assignment] = await Promise.all([++ probeGatewayRuntime(outcome.processIdentity),++ probeGridAssignment(outcome.processIdentity, session.engine, outcome.processIdentity.executable),++ ])++ registry.updateProcessIdentity(session.agentId, outcome.processIdentity, gateway.kind, assignment)++ registry.setActive(session.agentId, true)++ await clearPaneRemainOnExit(pane.paneId)++ const refreshed = registry.byAgent(session.agentId)++ // The app decides whether to still offer a move from what it is told here, so a silent success++ // would leave the banner up over an agent that had already been moved.++ if (refreshed) announceSession(refreshed)++ const how = outcome.resumed ? 'resumed' : 'fresh session'++ console.log(`${describeGridLaunch(session.engine, grid)} · retargeted ${sid(session.agentId)} · ${how}`)++ return { ok: true }+ } finally {+ release()++ agentReconciler.releaseRoute(routeKey)+ }- // ⚠️ THE AGENT MUST ADOPT THE NEW PROCESS, OR IT STOPS BEING THE SAME AGENT.- //- // Identity in this daemon is keyed on the PROCESS, not the pane: the reconciler matches an- // existing record to an observation by pid + start marker (`currentProcessKey`), and its- // same-pane fallback only applies to an agent with no bound engine session. A respawn changes- // the pid, so left to discovery the new process is an unmatched observation — `onDiscovered`- // mints a NEW agent id, and the record the user was looking at becomes a ghost that the app- // still lists, still counts as "on an older target", and still offers to move. Moving it- // respawns the same pane again. That loop is what this adoption prevents.- //- // The wait is the same one `onCreateAgent` measured: a freshly exec'd engine is not in `ps` the- // instant tmux returns, because the user's interactive login shell runs first.- const previousPid = session.processIdentity?.pid- const deadline = Date.now() + 8_000- let delayMs = 150- let adopted = false- while (!adopted && Date.now() < deadline) {- await new Promise((resolve) => setTimeout(resolve, delayMs))- const identity = await resolvePaneEngineProcess(pane.paneId, session.engine)- if (identity && identity.pid !== previousPid) {- // Both are read from the one cached environment of the new pid, so this costs no extra `ps`.- const [gateway, assignment] = await Promise.all([- probeGatewayRuntime(identity),- probeGridAssignment(identity, session.engine, identity.executable),- ])- registry.updateProcessIdentity(session.agentId, identity, gateway.kind, assignment)- adopted = true- break- }- delayMs = Math.min(delayMs * 2, 750)- }- if (!adopted) {- // The respawn itself succeeded — only the adoption ran out of patience, and the periodic- // reconcile will pick the pane up. Reporting a failure would send the user to redo something- // that already happened.- console.warn(`[grid] retarget ${sid(session.agentId)} · respawned, but its new process was not adopted in time`)- }- await agentReconciler.triggerHint({ backend: 'tmux', paneId: pane.paneId }, session.engine)- await clearPaneRemainOnExit(pane.paneId)- return { ok: true }+ }+/*** Web or device deleted an agent (`agent_delete`): end the AGENT, not the user's window.*@@@ -3028,6 -2923,97 +3137,61 @@@})}+ /**+ * 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),- })++ const bypassPermission = await liveBypassPermission(session)++ const outcome = await restartAgent(++ { engine, sessionId: session.sessionId },++ bypassPermission,++ paneSwapDeps(session, runtime),++ )++ 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 --cc cli/src/lib/engineLaunch.tsindex cb7410497,1e75e718d..26510620b--- a/cli/src/lib/engineLaunch.ts+++ b/cli/src/lib/engineLaunch.ts@@@ -28,39 -28,47 +28,59 @@@ export const BYPASS_PERMISSION_FLAGS: Rcopilot: null,}- /**- * How to name an existing session on the command line, for the engines that need it here.- *- * Deliberately separate from `RESUME_ARGS` in `tmux.ts`, which reads argv the other way round to- * recover an id and omits claude on purpose. This table is for WRITING a launch, and it exists for- * one caller: moving a running agent to a grid re-execs it, and an engine that came back empty would- * have thrown away the conversation the user was in the middle of. Only engines that can be pointed- * at a grid at all need an entry — see `GRID_ENGINE_ENV` in `gridLaunch.ts`.- */- export const RESUME_FLAGS: Partial<Record<AgentEngine, string>> = {- claude: '--resume',- }-export interface LaunchCommandOptions {bypassPermission?: boolean- /**- * Resume this engine session instead of starting a new conversation.- *- * Ignored when the engine has no entry in [RESUME_FLAGS], and callers pass null for an agent that- * has not bound a session yet — there is nothing to resume, and guessing with a `--continue` style- * flag could attach a DIFFERENT agent's conversation from the same folder.- */- resumeSessionId?: string | null+ /** Resume this engine session id on launch, when a launch-resume flag is known for the engine. */+ resumeSessionId?: string+ /**+ * Extra argv the caller has already composed, appended last.+ *+ * Exists for engines whose endpoint is configured on the command line rather than through the+ * environment — Codex's `-c model_providers.*`, Grok's `-m`. See `gridLaunch.ts`; a credential+ * never travels this way.+ */+ extraArgs?: readonly 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.+ *++ * Moving a running agent to a grid re-execs it through the same path, and relies on the same table for++ * the same reason: an engine that came back with no way to resume would have thrown away the++ * conversation the user was in the middle of.++ *+ * 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)]@@@ -68,9 -83,9 +95,10 @@@const flags = BYPASS_PERMISSION_FLAGS[engine]if (flags) argv.push(...flags)}- const resumeFlag = opts.resumeSessionId ? RESUME_FLAGS[engine] : undefined- if (resumeFlag) argv.push(resumeFlag, opts.resumeSessionId as string)+ if (!resumeIsSubcommand && resumeFlag && opts.resumeSessionId) {+ argv.push(...resumeFlag, opts.resumeSessionId)+ }+ if (opts.extraArgs?.length) argv.push(...opts.extraArgs)return argv}diff --cc cli/src/lib/registry.tsindex 1d5e45357,fd85e561a..78b5154f0--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@@ -793,9 -787,23 +793,24 @@@ class Registrycwd?: string | nullprocessIdentity: ProcessIdentitygateway?: 'ori' | null+ grid?: GridAssignment | null}):- { entry: RegisteredSession; isNew: boolean; evicted: string | null } | null {+ {+ entry: RegisteredSession+ isNew: boolean+ /**+ * The agent this one took a terminal from, once it has no terminal left.+ *+ * BOTH IDS, because by the time the caller reads this the agent is ALREADY+ * GONE from the registry — `drop()` removes it and the loop below only+ * re-indexes it if it still owns a runtime — so nothing can look either id+ * up afterwards. Clients key on the agentId and the daemon's per-session+ * state keys on the sessionId, and the caller needs both to finish the+ * removal it was never told to do.+ */+ evicted: { agentId: string; sessionId: string } | null+ } | null {+if (this.writeBlocked) return nullconst { engine, processIdentity } = inputconst runtimes = normalizedRuntimes(input.runtimes, input.tmuxPane)diff --cc cli/src/lib/terminalBackend.tsindex 169363330,f0cbeef2d..56614c0d8--- a/cli/src/lib/terminalBackend.ts+++ b/cli/src/lib/terminalBackend.ts@@@ -8,6 -8,6 +8,7 @@@ import typeTerminalLogicalKey,TerminalProcessExpectation,TerminalReadResult,++ TerminalRespawnRequest,TerminalRuntimeRef,TerminalStreamHandle,TerminalStreamSink,@@@ -40,4 -40,11 +41,11 @@@ export interface TerminalBackend<Ref exsize: 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>++ respawn?(runtime: Ref, request: TerminalRespawnRequest): Promise<TerminalActionResult>}diff --cc cli/src/lib/tmuxBackend.spec.tsindex a860f7120,7741467dd..e1b71bd33--- a/cli/src/lib/tmuxBackend.spec.ts+++ b/cli/src/lib/tmuxBackend.spec.ts@@@ -81,6 -81,47 +81,49 @@@ exitexpect(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))++ await expect(backend.respawn({ backend: 'tmux', paneId: '%9' }, {++ command: ['claude', '--resume', 'abc; rm -rf /'],++ cwd: '/tmp/work',++ })).resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })++ await expect(backend.respawn({ backend: 'tmux', paneId: '%9' }, { command: ['claude'] }))+ .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',++ 'set-option -w -t %9 remain-on-exit on ; respawn-pane -k -c /tmp/work -t %9 claude --resume abc; rm -rf /',++ 'set-option -w -t %9 remain-on-exit on ; 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 --cc cli/src/lib/tmuxBackend.tsindex 3eb87e715,33c5544b7..338a0f648--- a/cli/src/lib/tmuxBackend.ts+++ b/cli/src/lib/tmuxBackend.ts@@@ -161,6 -129,40 +161,23 @@@ export class TmuxBackend implements Terreturn 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 {