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: add launch overrides and Codex home probing for session restoration
0xken154b2f7836d513
diff --git a/cli/README.md b/cli/README.mdindex d8bfd4bb8..c325a90ac 100644--- a/cli/README.md+++ b/cli/README.md@@ -142,8 +142,13 @@ claude under a terminal backend ──writes──▶ ~/.claude/projects/**.json- **Agents survive a reboot.** The registry outlives the tmux server. On start, every registered agentwhose pane is gone (a reboot, a `tmux kill-server`) gets a new pane running the same engine in thesame folder, resuming its engine session when it has one, under the same agent id — so the app's- tiles reattach by themselves. Agents that were pointed at a grid are not restored (the launch- credential is never persisted), and an engine with no resume flag (devin) comes back fresh.+ tiles reattach by themselves. An agent that was pointed at a grid comes back on that grid: the+ registry row keeps the launch it was created or retargeted with (`gridLaunch`, key included, in the+ 0600 `registry.json`), and restore, `agent_restart` and the offline hook fallback all reuse it — a+ relaunch on the engine's own login would spend the wrong account while looking identical. A Codex+ profile agent comes back under its `CODEX_HOME` with its hooks installed. A grid row written before+ the launch was persisted is not relaunched; it is marked `GRID_CREDENTIAL_REQUIRED` instead. An+ engine with no resume flag (devin) comes back fresh.- **Hooks bind mutable engine sessions** to the process agent using authenticated tmux and/or Herdrruntime hints plus verified caller ancestry. Hook socket paths are lookup hints only. They do notrequire `MACHINE_ID`. `SessionStart` and catch hooks attach transcript/store metadata; `SessionEnd` onlydiff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjsindex 1fc5bba84..7bdca8d3d 100644--- a/cli/hook/notify.mjs+++ b/cli/hook/notify.mjs@@ -1253,9 +1253,22 @@ async function fallbackRegister(input, engine, tmuxPane) {const agentId = typeof existing?.agentId === 'string' && existing.agentId ? existing.agentId : randomUUID()const runtimes = mergeRuntimes(existing?.runtimes, observedRuntimes)const tmuxProjection = runtimes.find((runtime) => runtime.backend === 'tmux')?.paneId || ''+ // What the daemon chose for this agent at launch and cannot re-derive from the process — the+ // grid launch (credential included), the Codex profile, the bypass flag, the observed grid and+ // gateway — is carried forward exactly as `registry.register()` does. A hook arriving while the+ // daemon is down must not be the one write that strips the row of them. `launch` is not: like+ // there, a hook means the engine is up, whatever the launch was.+ const carried = {+ gateway: existing?.gateway === 'ori' ? 'ori' : null,+ grid: existing?.grid ?? null,+ ...(existing && Object.hasOwn(existing, 'gridLaunch') ? { gridLaunch: existing.gridLaunch ?? null } : {}),+ codexHome: typeof existing?.codexHome === 'string' && existing.codexHome ? existing.codexHome : null,+ ...(existing?.bypassPermission === true ? { bypassPermission: true } : {}),+ }const entry = {schemaVersion: 2,active: true,+ ...carried,agentId,sessionId,engine,diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 731561e23..39b3776ab 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -36,6 +36,7 @@ import { messagesToEvents, windowRawLines, subagentStatsFromRawLines, type Sessiimport { listFileTree, readProjectFile } from './lib/files.js'import { MediaPreviewError, readMediaPreviewChunk } from './lib/mediaPreview.js'import { codexMessagesToEvents, windowCodexLines } from './engines/codex/normalizer.js'+import { codexSubagentResolverFor } from './engines/codex/subagent.js'import { cursorMessagesToEvents, windowCursorLines } from './engines/cursor/normalizer.js'import { loadCursorReplayTaskLinks } from './engines/cursor/subagent.js'import { opencodeMessagesToEvents, windowOpencodeMessages } from './engines/opencode/normalizer.js'@@ -1305,7 +1306,7 @@ export class BackendSocket {if (!limit) {const fullEvents = s.engine === 'codex'- ? codexMessagesToEvents(lines)+ ? codexMessagesToEvents(lines, codexSubagentResolverFor(s.codexHome)): s.engine === 'cursor'? cursorMessagesToEvents(lines, sessionId, await loadCursorReplayTaskLinks(env.CURSOR_HOME, sessionId)): s.engine === 'muse'@@ -1378,7 +1379,7 @@ export class BackendSocket {return}const events = s.engine === 'codex'- ? codexMessagesToEvents(w.window)+ ? codexMessagesToEvents(w.window, codexSubagentResolverFor(s.codexHome)): s.engine === 'cursor'? cursorMessagesToEvents(w.window,diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex ec0549086..7c90fdc4f 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -66,6 +66,7 @@ import { claudeContinuation, findLiveSession } from './lib/sessionRepair.js'import { TmuxBackend } from './lib/tmuxBackend.js'import { createAndRegisterPane } from './lib/createAgentPane.js'import { restoreAgents } from './lib/restoreAgents.js'+import { buildLaunchOverrides, validateLaunchOverrides, type LaunchOverridesDeps, type LaunchOverridesResult, type LaunchSource } from './lib/launchOverrides.js'import { buildHarnessSessionLabel } from './lib/harnessSessionLabel.js'import { basename } from 'node:path'import {@@ -131,6 +132,7 @@ import { managedNodePath } from './lib/nodeRuntime.js'import { ensureLauncher, ensureManagedRuntime } from './lib/runtimeInstall.js'import { stat } from 'fs/promises'import { CodexNormalizer, codexTaskError, lastCodexTurnText } from './engines/codex/normalizer.js'+import { codexSubagentResolverFor } from './engines/codex/subagent.js'import { CursorNormalizer, lastCursorTurnText } from './engines/cursor/normalizer.js'import { CursorTranscriptDiscovery, findCursorTranscript } from './engines/cursor/discovery.js'import { CursorSubagentManager } from './engines/cursor/subagent.js'@@ -1533,7 +1535,7 @@ async function runForeground(session: AuthSession): Promise<void> {return out.turnOpen}if (session.engine === 'codex') {- const normalizer = new CodexNormalizer('live')+ const normalizer = new CodexNormalizer('live', codexSubagentResolverFor(session.codexHome))// Hydrate state silently; never replay history live — except a turn left open, below.historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)codexNormalizers.set(session.sessionId, normalizer)@@ -2363,6 +2365,7 @@ async function runForeground(session: AuthSession): Promise<void> {processIdentity: observed.processIdentity,gateway: observed.gateway,grid: observed.grid,+ codexHome: observed.codexHome,})if (!opened) returnif (opened.evicted) {@@ -2399,6 +2402,10 @@ async function runForeground(session: AuthSession): Promise<void> {// agent passes through — so a row written before the flag was persisted at all (or by a build// that did not yet) learns it here, before any pane recreation ever needs it.registry.setBypassPermission(current.agentId, bypassPermissionActive(current.engine, observed.args))+ // Same idea for a Codex profile: a row that never learned which CODEX_HOME its process runs+ // under learns it from the process, before the hook path validates a transcript against it.+ // Fill-only — a profile the row already knows is never re-derived.+ if (observed.codexHome && !current.codexHome) registry.setCodexHome(current.agentId, observed.codexHome)if (wasLaunching) registry.setLaunch(current.agentId, { state: 'ready' })await bindObservedAgent(observed)if (wasDormant || wasLaunching) {@@ -3121,7 +3128,7 @@ async function runForeground(session: AuthSession): Promise<void> {let eventsif (session.engine === 'codex') {let normalizer = codexNormalizers.get(evt.sessionId)- if (!normalizer) { normalizer = new CodexNormalizer('live'); codexNormalizers.set(evt.sessionId, normalizer) }+ if (!normalizer) { normalizer = new CodexNormalizer('live', codexSubagentResolverFor(session.codexHome)); codexNormalizers.set(evt.sessionId, normalizer) }events = normalizer.ingest(evt.text)// Codex rides its failure ON task_complete, so the turn closes by itself — but with no text and// no reason, which reads as "the agent answered nothing". Announce the reason ahead of the@@ -3208,6 +3215,40 @@ async function runForeground(session: AuthSession): Promise<void> {)}}+ /**+ * The config directory a grid launch should actually be given on THIS machine, or none.+ *+ * Only Hermes can lose one. Its web tools ride a managed-scope overlay, and `HERMES_MANAGED_DIR`+ * REPLACES `/etc/hermes` rather than adding to it — so on a machine where an administrator pinned+ * Hermes settings there, writing ours would take their policy away for as long as the agent runs.+ * The agent still launches on the grid; it launches without web tools, which is the smaller loss+ * and the one that can be said out loud.+ *+ * Here rather than in the contract because it is a fact about the machine: a `build()` that+ * stats the filesystem answers differently on two of them, and its spec would follow.+ */+ const gridConfigDirFor = (engine: AgentEngine, launch: GridEngineLaunch): GridEngineLaunch['configDir'] => {+ if (!launch.configDir || engine !== 'hermes' || !existsSync(HERMES_SYSTEM_MANAGED_DIR)) return launch.configDir+ console.warn(`[grid] ${engine} starts without web tools · ${HERMES_SYSTEM_MANAGED_DIR} pins this `+ + `machine's Hermes settings, and the overlay carrying the web tools would replace it`)+ return undefined+ }++ /**+ * What a relaunch of `session` must be given, beyond the engine's argv, to come back where it was —+ * on its grid (the registry kept the launch, key included) or under its Codex profile. Restore and+ * restart read the row; retarget passes the override the desktop just sent. The config directory is+ * keyed on the agent, so relaunching the same agent rewrites one directory instead of leaving a trail.+ */+ const launchOverridesDeps: LaunchOverridesDeps = {+ configDirFor: gridConfigDirFor,+ writeGridConfigDir,+ tmuxSupportsSessionEnv,+ installCodexHooks: (codexHome) => { if (!env.DISABLE_HOOK_INSTALL) installCodexHooks(hookPort, codexHome) },+ }+ const relaunchOverrides = (session: RegisteredSession, source: LaunchSource = session): Promise<LaunchOverridesResult> =>+ buildLaunchOverrides(launchOverridesDeps, session.engine, source, session.agentId)+watcher.start()await cursorDiscovery.start()// Panes that died while the daemon was down (a reboot takes the whole tmux server with it) are@@ -3224,17 +3265,22 @@ async function runForeground(session: AuthSession): Promise<void> {// and a pane that outlived the daemon in a session discovery no longer lists still has its// engine, which a second pane resuming the same session would collide with.liveProcess: (entry, runtime) => resolvePaneEngineProcess(runtime.paneId, entry.engine),- buildLaunch: (entry, opts) => {- // Mirrors `agent_create`: a Codex profile other than the default needs its hooks and its- // CODEX_HOME; the install check runs inside the pane's own shell.- if (entry.codexHome && !env.DISABLE_HOOK_INSTALL) installCodexHooks(hookPort, entry.codexHome)+ buildLaunch: async (entry, opts) => {+ // Mirrors `agent_create`: the same grid env/argv (and the same vendor variables cleared), or+ // the same Codex profile with its hooks installed; the install check runs inside the pane's+ // own shell.+ const built = await relaunchOverrides(entry)+ if (!built.ok) return { error: built.error, detail: built.detail }+ const { env: launchEnv, extraArgs, clearEnv } = built.overridesconst argv = buildEngineLaunchArgv(entry.engine, {...opts,bypassPermission: entry.bypassPermission === true,installIfMissing: enginePathOverride(entry.engine) ? undefined : engineInstallRecipe(entry.engine),...(entry.cwd ? { cwd: entry.cwd } : {}),+ ...(extraArgs.length ? { extraArgs } : {}),+ ...(clearEnv.length ? { clearEnv } : {}),})- return { argv, ...(entry.codexHome ? { env: { CODEX_HOME: entry.codexHome } } : {}) }+ return { argv, ...(Object.keys(launchEnv).length ? { env: launchEnv } : {}) }},createPane: async (entry, launch) => {const created = await backend.create({@@ -3399,24 +3445,6 @@ async function runForeground(session: AuthSession): Promise<void> {* The freshly-exec'd engine process may not be visible to `ps` the instant tmux returns, so one probe* pass can miss it — retry `triggerHint` a few times with backoff before giving up.*/- /**- * The config directory a grid launch should actually be given on THIS machine, or none.- *- * Only Hermes can lose one. Its web tools ride a managed-scope overlay, and `HERMES_MANAGED_DIR`- * REPLACES `/etc/hermes` rather than adding to it — so on a machine where an administrator pinned- * Hermes settings there, writing ours would take their policy away for as long as the agent runs.- * The agent still launches on the grid; it launches without web tools, which is the smaller loss- * and the one that can be said out loud.- *- * Here rather than in the contract because it is a fact about the machine: a `build()` that- * stats the filesystem answers differently on two of them, and its spec would follow.- */- const gridConfigDirFor = (engine: AgentEngine, launch: GridEngineLaunch): GridEngineLaunch['configDir'] => {- if (!launch.configDir || engine !== 'hermes' || !existsSync(HERMES_SYSTEM_MANAGED_DIR)) return launch.configDir- console.warn(`[grid] ${engine} starts without web tools · ${HERMES_SYSTEM_MANAGED_DIR} pins this `- + `machine's Hermes settings, and the overlay carrying the web tools would replace it`)- return undefined- }backend.onCreateAgent = async ({ engine, cwd, bypassPermission, grid, codexHome }) => {if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }@@ -3506,6 +3534,7 @@ async function runForeground(session: AuthSession): Promise<void> {argv,env: gridLaunch?.env ?? (codexHome ? { CODEX_HOME: codexHome } : undefined),grid: grid ? { baseUrl: grid.baseUrl, model: grid.model ?? null } : null,+ gridLaunch: grid ?? null,codexHome,bypassPermission,})@@ -3580,7 +3609,7 @@ async function runForeground(session: AuthSession): Promise<void> {const paneSwapDeps = (session: RegisteredSession,runtime: TmuxRuntimeRef,- launch: { env?: Record<string, string>; extraArgs?: readonly string[] } = {},+ launch: { env?: Record<string, string>; extraArgs?: readonly string[]; clearEnv?: readonly string[] } = {},): RestartAgentDeps => ({holdOpen: async () => {const result = await tmuxBackend!.holdOpen(runtime)@@ -3629,11 +3658,10 @@ async function runForeground(session: AuthSession): Promise<void> {// gap — a create cleared them, then moving that agent onto a grid from the pane header put them// straight back, so the engine came up on Anthropic with a grid selected above it.//- // Derived from what this swap actually provides, so the empty-env case — a retarget back to the- // engine's own login — clears nothing. There the user's own variables are the point.- ...(launch.env && Object.keys(launch.env).length- ? { clearEnv: gridConflictingEnvToClear({ env: launch.env, args: [] }) }- : {}),+ // Named by the caller (`buildLaunchOverrides` derives it from what the grid launch provides), so+ // a swap that sets no grid — back to the engine's own login, or a Codex profile's CODEX_HOME —+ // clears nothing. There the user's own variables are the point.+ ...(launch.clearEnv?.length ? { clearEnv: launch.clearEnv } : {}),}),log: (message) => console.log(message),})@@ -3672,18 +3700,10 @@ async function runForeground(session: AuthSession): Promise<void> {// 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 = grid ? buildGridEngineLaunch(session.engine, grid) : null- if (built && !built.ok) return { ok: false, error: built.error, detail: built.detail }- // Only a launch that SETS variables needs the tmux that can set them. Clearing uses- // set-environment, which every supported tmux has.- if (built && !(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.',- }- }+ // What this machine cannot do at all is said first, before the pane is even looked at.+ const target: LaunchSource = { gridLaunch: grid, codexHome: session.codexHome }+ const valid = await validateLaunchOverrides(launchOverridesDeps, session.engine, target)+ if (!valid.ok) return { ok: false, error: valid.error, detail: valid.detail }// 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@@ -3694,21 +3714,15 @@ async function runForeground(session: AuthSession): Promise<void> {// 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 && built.ok ? { ...built.launch.env } : {}- const retargetConfigDir = built && built.ok ? gridConfigDirFor(session.engine, built.launch) : undefined- if (retargetConfigDir) {- // Keyed on the agent, so moving the same agent between grids rewrites one directory rather- // than leaving a trail of them.- const { envVar, files, pointAt, links } = retargetConfigDir- try {- const dir = await writeGridConfigDir(session.agentId, files, links)- // Same split as create: a directory for Pi, the file itself for OpenCode.- gridEnv[envVar] = pointAt ? join(dir, pointAt) : dir- } 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 grid's env and argv, config directory written (keyed on the agent, so moving it between+ // grids rewrites one directory) — or nothing at all for a move back to the engine's own login+ // (clearing uses set-environment, which every supported tmux has). Built from the override the+ // desktop just sent, never from the row: the row is what this call REPLACES. After the refusal+ // guards, so a refused move leaves the live process's own configuration untouched.+ const built = await relaunchOverrides(session, target)+ if (!built.ok) {+ release()+ return { ok: false, error: built.error, detail: built.detail }}// ⚠️ THE AGENT MUST ADOPT THE NEW PROCESS, OR IT STOPS BEING THE SAME AGENT.@@ -3743,7 +3757,7 @@ async function runForeground(session: AuthSession): Promise<void> {const outcome = await restartAgent({ engine: session.engine, sessionId: session.sessionId },await liveBypassPermission(session),- paneSwapDeps(session, pane, { env: gridEnv, extraArgs: built && built.ok ? built.launch.args : [] }),+ paneSwapDeps(session, pane, built.overrides),)if (!outcome.ok) {console.warn(`[grid] retarget ${sid(session.agentId)} failed · ${outcome.detail}`)@@ -3755,6 +3769,8 @@ async function runForeground(session: AuthSession): Promise<void> {probeGridAssignment(outcome.processIdentity, session.engine, outcome.processIdentity.executable),])registry.updateProcessIdentity(session.agentId, outcome.processIdentity, gateway.kind, assignment)+ // The launch that just worked is the one a restart or a post-reboot restore must repeat.+ registry.setGridLaunch(session.agentId, grid)registry.setActive(session.agentId, true)await clearPaneRemainOnExit(pane.paneId)const refreshed = registry.byAgent(session.agentId)@@ -3833,27 +3849,41 @@ async function runForeground(session: AuthSession): Promise<void> {const runtime: TmuxRuntimeRef = { backend: 'tmux', paneId: pane }const routeKey = terminalRouteKey(runtime)+ // The replacement is launched WITH what the original was: its grid's env and argv (a bare+ // respawn would inherit the tmux session's variables but never the codex `-c …` / pi `--model`+ // half, and an agent moved here by a retarget has nothing in the session env at all), or its+ // Codex profile. Refused before anything is killed, so a restart that cannot honour the grid+ // leaves the running process alone.+ const built = await relaunchOverrides(session)+ if (!built.ok) return { ok: false, error: built.error, detail: built.detail }+agentReconciler.holdRoute(routeKey)try {const bypassPermission = await liveBypassPermission(session)const outcome = await restartAgent({ engine, sessionId: session.sessionId },bypassPermission,- paneSwapDeps(session, runtime),+ paneSwapDeps(session, runtime, built.overrides),)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)+ // real agentId. Gateway and grid are re-read off the new pid now (one cached env read) rather+ // than left to the next scan, so the announce below already says where the engine came back.+ const [gateway, assignment] = await Promise.all([+ probeGatewayRuntime(outcome.processIdentity),+ probeGridAssignment(outcome.processIdentity, engine, outcome.processIdentity.executable),+ ])+ registry.updateProcessIdentity(session.agentId, outcome.processIdentity, gateway.kind, assignment)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'}`)+ console.log(`[restart] ${sid(session.agentId)} ${engine} · ${outcome.resumed ? 'resumed' : 'fresh session'}`+ + (session.gridLaunch ? ` · grid ${session.gridLaunch.networkName}` : ''))return { ok: true, session: refreshed, resumed: outcome.resumed }} finally {agentReconciler.releaseRoute(routeKey)diff --git a/cli/src/engines/codex/subagent.ts b/cli/src/engines/codex/subagent.tsindex 321b16ef8..ebdf126bd 100644--- a/cli/src/engines/codex/subagent.ts+++ b/cli/src/engines/codex/subagent.ts@@ -1,4 +1,5 @@import { readFileSync } from 'fs'+import { join } from 'path'import type { SessionEvent } from '../../lib/normalize.js'import { resolveCodexRollout } from './rollout.js'@@ -223,3 +224,17 @@ export const resolveCodexSubagent: CodexSubagentResolver = (threadId) => {const file = resolveChildRollout(threadId)return file ? readChildRollout(file) : null}++/**+ * The resolver for an agent on a Codex PROFILE: its child rollouts live under that profile's+ * `sessions/`, not the default one, so the default resolver would answer every Task card with+ * "history unreadable". Null/undefined = the default profile = the default resolver.+ */+export function codexSubagentResolverFor(codexHome: string | null | undefined): CodexSubagentResolver {+ if (!codexHome) return resolveCodexSubagent+ const root = join(codexHome, 'sessions')+ return (threadId) => {+ const file = resolveChildRollout(threadId, root)+ return file ? readChildRollout(file) : null+ }+}diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.tsindex 53a1250d5..87ec34b7a 100644--- a/cli/src/hookNotify.spec.ts+++ b/cli/src/hookNotify.spec.ts@@ -829,6 +829,72 @@ describe('hook notify terminal scope', () => {expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))).toEqual([{ sessionId: 'maybe-alive' }])})+ it('carries what the daemon chose at launch through an offline re-register', async () => {+ // A hook arriving while the daemon is down rebuilds the row. The grid launch (key included), the+ // Codex profile, the bypass flag and the observed grid are not on the process or in the hook body+ // — they must come from the row being replaced, or this becomes the one write that strips them+ // and the next restart relaunches the agent on the wrong login.+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-carry-'))+ tmpDirs.push(dir)+ const claudeProjectsDir = join(dir, 'claude-projects')+ const dataDir = join(dir, 'data')+ const transcriptPath = join(claudeProjectsDir, 'demo', 'session-1.jsonl')+ mkdirSync(join(claudeProjectsDir, 'demo'), { recursive: true })+ mkdirSync(dataDir, { recursive: true })+ chmodSync(dataDir, 0o755)+ writeFileSync(transcriptPath, '{}\n')+ const gridLaunch = { networkId: 'grid-abc', networkName: 'Team grid', baseUrl: 'https://grid.example/grid-abc/relay/v1', apiKey: 'gridkey-abc123' }+ writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([{+ schemaVersion: 2,+ active: true,+ launch: { state: 'starting' },+ agentId: 'agent-created',+ sessionId: '',+ boundAt: null,+ engine: 'claude',+ gateway: null,+ grid: { baseUrl: gridLaunch.baseUrl, model: null },+ gridLaunch,+ codexHome: null,+ bypassPermission: true,+ transcriptPath: null,+ projectDir: 'demo',+ cwd: '/tmp/demo',+ runtimes: [{ backend: 'tmux', paneId: '%7' }],+ primaryRuntimeKey: 'tmux\u0000%7',+ tmuxPane: '%7',+ source: null,+ title: null,+ model: null,+ cliVersion: null,+ processIdentity: { pid: 7001, executable: 'claude', startMarker: 'Mon Aug 10 10:00:01 2026' },+ registeredAt: 1,+ updatedAt: 1,+ lastHookAt: 1,+ lastTranscriptAt: 1,+ }]))++ await runHook({+ port: 9,+ tmuxPane: '%7',+ processEngine: 'claude',+ dataDir,+ claudeProjectsDir,+ input: { hook_event_name: 'SessionStart', session_id: 'session-1', transcript_path: transcriptPath, cwd: '/tmp/demo' },+ })++ const registry = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))+ expect(registry).toHaveLength(1)+ expect(registry[0]).toMatchObject({+ agentId: 'agent-created',+ sessionId: 'session-1',+ grid: { baseUrl: gridLaunch.baseUrl, model: null },+ gridLaunch,+ bypassPermission: true,+ })+ expect(registry[0]).not.toHaveProperty('launch')+ })+it('drops stale registry entries when boot marker predates this boot', async () => {const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-reboot-'))tmpDirs.push(dir)diff --git a/cli/src/lib/agentFrame.spec.ts b/cli/src/lib/agentFrame.spec.tsindex c5f59c948..cf6b0cc19 100644--- a/cli/src/lib/agentFrame.spec.ts+++ b/cli/src/lib/agentFrame.spec.ts@@ -26,6 +26,14 @@ describe('agentFrame', () => {.toMatchObject({ grid: assignment })})+ it('never carries the grid launch — the key stays in the registry', async () => {+ const row = session(assignment)+ row.gridLaunch = { networkId: 'grid-abc', networkName: 'Team grid', baseUrl: assignment.baseUrl, apiKey: 'gridkey-SECRET' }+ const frame = await agentFrame(row, { selectedModel: null, terminalAvailable: true })+ expect(frame).not.toHaveProperty('gridLaunch')+ expect(JSON.stringify(frame)).not.toContain('gridkey-SECRET')+ })+it('reports no assignment as null rather than omitting the field', async () => {const frame = await agentFrame(session(null), { selectedModel: null, terminalAvailable: true })expect(frame).toHaveProperty('grid', null)diff --git a/cli/src/lib/codexHomeProbe.spec.ts b/cli/src/lib/codexHomeProbe.spec.tsnew file mode 100644index 000000000..362739adf--- /dev/null+++ b/cli/src/lib/codexHomeProbe.spec.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from 'vitest'+import { mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { codexHomeFromEnv } from './codexHomeProbe.js'++describe('codexHomeFromEnv', () => {+ const DEFAULT = '/home/u/.codex'++ it('reads a non-default profile off the process environment', () => {+ expect(codexHomeFromEnv('codex', { CODEX_HOME: '/home/u/.codex-work' }, DEFAULT)).toBe('/home/u/.codex-work')+ })++ it('reports the default profile as null, whichever way it is spelled', () => {+ expect(codexHomeFromEnv('codex', {}, DEFAULT)).toBeNull()+ expect(codexHomeFromEnv('codex', { CODEX_HOME: DEFAULT }, DEFAULT)).toBeNull()+ const real = mkdtempSync(join(tmpdir(), 'codex-home-'))+ try {+ // A path that resolves to the default (a symlink, `..` — here realpath vs. the tmp alias on+ // macOS) is still the default.+ expect(codexHomeFromEnv('codex', { CODEX_HOME: join(real, '.', '') }, real)).toBeNull()+ } finally {+ rmSync(real, { recursive: true, force: true })+ }+ })++ it('is Codex-only and refuses a value that could not be a home', () => {+ expect(codexHomeFromEnv('claude', { CODEX_HOME: '/home/u/.codex-work' }, DEFAULT)).toBeNull()+ expect(codexHomeFromEnv('codex', { CODEX_HOME: 'relative/dir' }, DEFAULT)).toBeNull()+ expect(codexHomeFromEnv('codex', { CODEX_HOME: '/bad\nline' }, DEFAULT)).toBeNull()+ })+})diff --git a/cli/src/lib/codexHomeProbe.ts b/cli/src/lib/codexHomeProbe.tsnew file mode 100644index 000000000..ad1b28f96--- /dev/null+++ b/cli/src/lib/codexHomeProbe.ts@@ -0,0 +1,39 @@+/**+ * Which Codex profile a live `codex` process was launched under, read off its environment.+ *+ * The registry's `codexHome` is chosen at `agent_create` and carried forward — but a codex pane the+ * daemon did not create (started by hand, or a row discovery had to mint again) has nothing to carry.+ * Its transcript lives under `<CODEX_HOME>/sessions`, so without this the hook's transcript path fails+ * `validTranscriptPath` against the default profile and session repair scans the wrong root. Same+ * cached env read `probeGridAssignment` uses: one `ps` per process for its whole life.+ *+ * Three answers, same contract as the grid probe: a path when the process runs under a non-default+ * profile, `null` when it runs under the machine's default (or CODEX_HOME is unset), and `undefined`+ * when the process could not be read — which must never overwrite what the registry already knows.+ */++import { realpathSync } from 'node:fs'+import { isAbsolute } from 'node:path'+import { env } from '../config/env.js'+import type { AgentEngine } from '../engines/types.js'+import { readProcessEnv } from './processEnv.js'+import type { ProcessIdentity } from './registry.js'++function canonical(path: string): string {+ try { return realpathSync(path) } catch { return path }+}++/** Pure half, for specs and for callers that already hold the environment. */+export function codexHomeFromEnv(engine: AgentEngine, processEnv: Record<string, string>, defaultHome = env.CODEX_HOME): string | null {+ if (engine !== 'codex') return null+ const home = processEnv.CODEX_HOME+ if (!home || !isAbsolute(home) || home.length > 4096 || /[\x00-\x1f\x7f]/.test(home)) return null+ return canonical(home) === canonical(defaultHome) ? null : home+}++export async function probeCodexHome(identity: ProcessIdentity, engine: AgentEngine): Promise<string | null | undefined> {+ if (engine !== 'codex') return null+ const processEnv = await readProcessEnv(identity)+ if (!processEnv) return undefined+ return codexHomeFromEnv(engine, processEnv)+}diff --git a/cli/src/lib/createAgentPane.ts b/cli/src/lib/createAgentPane.tsindex 631cb5c4d..9d63830cc 100644--- a/cli/src/lib/createAgentPane.ts+++ b/cli/src/lib/createAgentPane.ts@@ -13,6 +13,7 @@*/import { homedir } from 'node:os'import type { AgentEngine } from '../engines/types.js'+import type { GridLaunchOverride } from './gridLaunch.js'import type { RegisteredSession } from './registry.js'import type { TerminalBackend } from './terminalBackend.js'import type { TerminalCreateResult, TmuxRuntimeRef } from './terminalTypes.js'@@ -28,6 +29,7 @@ export interface CreateAgentPaneDeps {primaryRuntimeKey?: stringcwd?: string | nullgrid?: { baseUrl: string; model: string | null } | null+ gridLaunch?: GridLaunchOverride | nullcodexHome?: string | nullbypassPermission?: boolean}) => RegisteredSession | null }@@ -39,6 +41,8 @@ export interface CreateAgentPaneDeps {argv: string[]env?: Record<string, string>grid?: { baseUrl: string; model: string | null } | null+ /** The grid launch behind `grid`, credential included — what restore/restart relaunch the pane with. */+ gridLaunch?: GridLaunchOverride | null/** The CODEX_HOME folder this agent was launched against, if the caller chose one; codex only. */codexHome?: string | nullmaxAttempts?: number@@ -72,6 +76,7 @@ export async function createAndRegisterPane(deps: CreateAgentPaneDeps): Promise<primaryRuntimeKey: terminalRouteKey(spawned.runtime),cwd: deps.cwd,grid: deps.grid,+ gridLaunch: deps.gridLaunch,codexHome: deps.codexHome,bypassPermission: deps.bypassPermission,})diff --git a/cli/src/lib/gridConfigDir.ts b/cli/src/lib/gridConfigDir.tsindex 2d585c0b3..62359d1d0 100644--- a/cli/src/lib/gridConfigDir.ts+++ b/cli/src/lib/gridConfigDir.ts@@ -8,7 +8,8 @@* directory undoes the whole thing.** Nothing written here is secret. A provider block references the key through an environment- * variable; the key itself only ever lives in the process environment.+ * variable; the key itself lives in the process environment — and, so a relaunch can put it back+ * there, in the registry row (`RegisteredSession.gridLaunch`), never in these files.*/import { lstat, mkdir, readdir, readlink, rm, stat, symlink, writeFile } from 'node:fs/promises'diff --git a/cli/src/lib/gridLaunch.ts b/cli/src/lib/gridLaunch.tsindex 2ffbf5e7b..12e57aa63 100644--- a/cli/src/lib/gridLaunch.ts+++ b/cli/src/lib/gridLaunch.ts@@ -6,6 +6,11 @@* reaches an engine by itself: this CLI is what spawns the engine, so this module turns that payload* into the launch — environment, and where the vendor demands it, argv.*+ * The one place that payload is kept is the registry row (`RegisteredSession.gridLaunch`, in a 0600+ * file this daemon owns) — so a restart, or a pane recreated after a reboot, relaunches onto the SAME+ * grid with the SAME key rather than silently coming back on the engine's own login. Nothing THIS+ * module writes (argv, a config directory) ever carries the key; that rule is unchanged.+ ** ## Every entry here is the vendor's own documented contract** The relay speaks two dialects — Anthropic Messages at `<grid>/relay`, and OpenAI@@ -84,7 +89,8 @@ export interface GridLaunchOverride {* Per-engine forms are derived from this; see [relayBaseUrl] and [anthropicBaseUrl].*/baseUrl: string- /** Short-lived, minted per launch. Never logged, and never placed in argv. */+ /** Short-lived, minted per launch. Never logged, never placed in argv; persisted only in the registry+ * row (see the module header), so a relaunch can repeat this launch. */apiKey: string/** Absent means "whatever the engine asks for" — the relay's own default. */model?: stringdiff --git a/cli/src/lib/launchOverrides.spec.ts b/cli/src/lib/launchOverrides.spec.tsnew file mode 100644index 000000000..87e3ed5a2--- /dev/null+++ b/cli/src/lib/launchOverrides.spec.ts@@ -0,0 +1,89 @@+import { describe, expect, it, vi } from 'vitest'+import { buildLaunchOverrides, validateLaunchOverrides, type LaunchOverridesDeps } from './launchOverrides.js'+import { GRID_CONFLICTING_ENV_VARS, type GridLaunchOverride } from './gridLaunch.js'++const GRID: GridLaunchOverride = {+ networkId: 'grid-abc',+ networkName: 'Team grid',+ baseUrl: 'https://grid.example/grid-abc/relay/v1',+ apiKey: 'gridkey-abc123',+ model: 'gpt-5',+}++function deps(overrides: Partial<LaunchOverridesDeps> = {}) {+ const calls: string[] = []+ const d: LaunchOverridesDeps = {+ configDirFor: (_engine, launch) => launch.configDir,+ writeGridConfigDir: async (key) => { calls.push(`writeConfig:${key}`); return `/state/grid-engine-config/${key}` },+ tmuxSupportsSessionEnv: async () => true,+ installCodexHooks: (home) => { calls.push(`hooks:${home}`) },+ ...overrides,+ }+ return { d, calls }+}++describe('buildLaunchOverrides — a relaunch comes back where the agent was', () => {+ it('rebuilds a grid launch from the persisted override: env with the key, argv, and the vendor variables to clear', async () => {+ const { d, calls } = deps()+ const result = await buildLaunchOverrides(d, 'claude', { gridLaunch: GRID }, 'agent-1')+ expect(result.ok).toBe(true)+ if (!result.ok) return+ expect(result.overrides.env).toMatchObject({ ANTHROPIC_AUTH_TOKEN: 'gridkey-abc123', ANTHROPIC_MODEL: 'gpt-5' })+ expect(result.overrides.env.ANTHROPIC_BASE_URL).toMatch(/^https:\/\/grid\.example\/grid-abc\/relay/)+ expect(result.overrides.extraArgs).toEqual(expect.arrayContaining(['--disallowedTools=WebSearch']))+ // Everything the launch does not set itself, so an inherited key cannot outrank the grid.+ for (const name of GRID_CONFLICTING_ENV_VARS) {+ expect(result.overrides.clearEnv.includes(name)).toBe(!(name in result.overrides.env))+ }+ expect(calls).toEqual([])+ })++ it('writes a file-configured engine its config directory keyed on the agent, and points the env at it', async () => {+ const { d, calls } = deps()+ const result = await buildLaunchOverrides(d, 'pi', { gridLaunch: GRID }, 'agent-1')+ expect(result.ok).toBe(true)+ if (!result.ok) return+ expect(calls).toEqual(['writeConfig:agent-1'])+ expect(result.overrides.env.PI_CODING_AGENT_DIR).toBe('/state/grid-engine-config/agent-1')+ expect(result.overrides.clearEnv).not.toContain('PI_CODING_AGENT_DIR')+ })++ it('refuses rather than falling back when the grid cannot be honoured', async () => {+ expect(await buildLaunchOverrides(deps().d, 'cursor', { gridLaunch: GRID }, 'a')).toMatchObject({ ok: false, error: 'GRID_ENGINE_UNSUPPORTED' })+ expect(await buildLaunchOverrides(deps({ tmuxSupportsSessionEnv: async () => false }).d, 'claude', { gridLaunch: GRID }, 'a'))+ .toMatchObject({ ok: false, error: 'TMUX_TOO_OLD_FOR_GRID', detail: expect.stringContaining('Team grid') })+ expect(await buildLaunchOverrides(deps({ writeGridConfigDir: async () => { throw new Error('disk full') } }).d, 'pi', { gridLaunch: GRID }, 'a'))+ .toMatchObject({ ok: false, error: 'GRID_CONFIG_FAILED', detail: expect.stringContaining('disk full') })+ })++ it('validation refuses the same launches without writing anything', async () => {+ const { d, calls } = deps({ tmuxSupportsSessionEnv: async () => false })+ expect(await validateLaunchOverrides(d, 'claude', { gridLaunch: GRID })).toMatchObject({ ok: false, error: 'TMUX_TOO_OLD_FOR_GRID' })+ expect(await validateLaunchOverrides(d, 'cursor', { gridLaunch: GRID })).toMatchObject({ ok: false, error: 'GRID_ENGINE_UNSUPPORTED' })+ expect(await validateLaunchOverrides(d, 'pi', { gridLaunch: null, codexHome: '/x' })).toEqual({ ok: true })+ expect(await validateLaunchOverrides(deps().d, 'pi', { gridLaunch: GRID })).toEqual({ ok: true })+ expect(calls).toEqual([])+ })++ it('a Codex profile gets its CODEX_HOME and its hooks, and clears nothing', async () => {+ const { d, calls } = deps()+ const result = await buildLaunchOverrides(d, 'codex', { gridLaunch: null, codexHome: '/home/u/.codex-work' }, 'agent-2')+ expect(result).toEqual({ ok: true, overrides: { env: { CODEX_HOME: '/home/u/.codex-work' }, extraArgs: [], clearEnv: [] } })+ expect(calls).toEqual(['hooks:/home/u/.codex-work'])+ })++ it('an agent on its own login gets nothing — its own variables are the point', async () => {+ const { d, calls } = deps()+ expect(await buildLaunchOverrides(d, 'claude', {}, 'a')).toEqual({ ok: true, overrides: { env: {}, extraArgs: [], clearEnv: [] } })+ expect(await buildLaunchOverrides(d, 'claude', { gridLaunch: null, codexHome: null }, 'a')).toMatchObject({ ok: true })+ expect(calls).toEqual([])+ })++ it('never lets the key into argv', async () => {+ for (const engine of ['claude', 'codex', 'opencode', 'hermes', 'grok', 'pi', 'copilot'] as const) {+ const result = await buildLaunchOverrides(deps().d, engine, { gridLaunch: { ...GRID, model: 'm' } }, 'a')+ expect(result.ok).toBe(true)+ if (result.ok) expect(result.overrides.extraArgs.join(' ')).not.toContain('gridkey-abc123')+ }+ })+})diff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.tsnew file mode 100644index 000000000..e9544e6a6--- /dev/null+++ b/cli/src/lib/launchOverrides.ts@@ -0,0 +1,131 @@+/**+ * What a pane has to be launched WITH, beyond the engine's own argv, for the engine to come back+ * where it was: on the same grid with the same credential, or under the same Codex profile.+ *+ * `agent_create` assembles this from the desktop's fresh `GridLaunchOverride`. Every later relaunch of+ * the same agent — a restart in place, a pane recreated after a reboot — has to assemble the SAME+ * thing from what the registry kept (`gridLaunch`, `codexHome`), or the engine silently comes back on+ * its own login, spending the wrong account while looking identical. Written once so the three+ * callers cannot drift: the half that drifts is the half nobody ran today.+ *+ * Dependency-injected like restoreAgents.ts, because the two machine-specific parts (the tmux version+ * probe and the config directory writer) are exactly the parts worth stubbing in a spec.+ */++import { join } from 'node:path'+import type { AgentEngine } from '../engines/types.js'+import {+ buildGridEngineLaunch,+ gridConflictingEnvToClear,+ type GridEngineLaunch,+ type GridLaunchOverride,+} from './gridLaunch.js'+import { TMUX_SESSION_ENV_MIN } from './tmuxVersion.js'++export interface LaunchOverrides {+ /** Layered over the pane's inherited environment. The grid key lives here, and only here. */+ env: Record<string, string>+ /** Appended to the engine's argv (`-c model_providers…`, `-m …`, `--mcp-config …`). */+ extraArgs: string[]+ /** Vendor credentials the launch must hide from the engine — see `gridConflictingEnvToClear`. */+ clearEnv: string[]+}++export type LaunchOverridesResult =+ | { ok: true; overrides: LaunchOverrides }+ | { ok: false; error: string; detail: string }++export interface LaunchOverridesDeps {+ /** The config directory this MACHINE can give the launch, or none — cli.ts prunes Hermes's. */+ configDirFor: (engine: AgentEngine, launch: GridEngineLaunch) => GridEngineLaunch['configDir']+ writeGridConfigDir: (+ key: string,+ files: NonNullable<GridEngineLaunch['configDir']>['files'],+ links: NonNullable<GridEngineLaunch['configDir']>['links'],+ ) => Promise<string>+ tmuxSupportsSessionEnv: () => Promise<boolean>+ /** Install the daemon's hooks into a non-default Codex profile. The caller decides whether hook+ * installation is enabled at all. */+ installCodexHooks: (codexHome: string) => void+}++/** Where the agent should come back: the registry row, or an override the desktop just sent. */+export interface LaunchSource {+ gridLaunch?: GridLaunchOverride | null+ codexHome?: string | null+}++/** Fresh each time: callers hand `env` to tmux and may extend it, and a shared object would carry+ * one relaunch's additions into the next. */+const noOverrides = (): LaunchOverrides => ({ env: {}, extraArgs: [], clearEnv: [] })++/**+ * Build the overrides for relaunching `engine` from `source`. `configKey` names the config directory+ * a file-configured engine gets (`writeGridConfigDir`); key it on the agent so relaunching the same+ * agent rewrites one directory rather than leaving a trail of them.+ *+ * A grid the launch cannot honour is a refusal, never a fallback — the rule `agent_create` sets.+ */+/**+ * The refusals that need nothing written: the engine has no way onto a grid, or this tmux cannot+ * give a pane its own environment. Split out so a caller with a live process to protect can refuse+ * BEFORE it decides to touch anything (retarget checks these ahead of its busy guards, and only+ * builds — config directory included — once it holds the pane).+ */+export async function validateLaunchOverrides(+ deps: Pick<LaunchOverridesDeps, 'tmuxSupportsSessionEnv'>,+ engine: AgentEngine,+ source: LaunchSource,+): Promise<{ ok: true } | { ok: false; error: string; detail: string }> {+ if (!source.gridLaunch) return { ok: true }+ const built = buildGridEngineLaunch(engine, source.gridLaunch)+ if (!built.ok) return { ok: false, error: built.error, detail: built.detail }+ // Only a launch that SETS variables needs the tmux that can set them.+ if (!(await deps.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 pane its own environment — so ${engine} could not be `+ + `pointed at grid ${source.gridLaunch.networkName}.`,+ }+ }+ return { ok: true }+}++export async function buildLaunchOverrides(+ deps: LaunchOverridesDeps,+ engine: AgentEngine,+ source: LaunchSource,+ configKey: string,+): Promise<LaunchOverridesResult> {+ const valid = await validateLaunchOverrides(deps, engine, source)+ if (!valid.ok) return valid+ if (source.gridLaunch) {+ const built = buildGridEngineLaunch(engine, source.gridLaunch)+ if (!built.ok) return { ok: false, error: built.error, detail: built.detail }+ const env: Record<string, string> = { ...built.launch.env }+ const configDir = deps.configDirFor(engine, built.launch)+ if (configDir) {+ const { envVar, files, pointAt, links } = configDir+ try {+ const dir = await deps.writeGridConfigDir(configKey, files, links ?? [])+ // Pi is handed the directory; OpenCode's OPENCODE_CONFIG wants the file inside it.+ env[envVar] = pointAt ? join(dir, pointAt) : dir+ } catch (error) {+ const detail = `could not write ${engine}'s grid configuration · ${error instanceof Error ? error.message : error}`+ return { ok: false, error: 'GRID_CONFIG_FAILED', detail }+ }+ }+ // Derived from what this launch actually provides (the config-dir variable included), so an+ // inherited vendor key never outranks the grid the engine was handed.+ return { ok: true, overrides: { env, extraArgs: [...built.launch.args], clearEnv: gridConflictingEnvToClear({ env, args: [] }) } }+ }+ if (source.codexHome) {+ // A Codex agent on a profile OTHER than this machine's default reads hooks.json from THAT folder,+ // not the one `harness login` installed into — without this it fires no hook at all. Idempotent.+ deps.installCodexHooks(source.codexHome)+ return { ok: true, overrides: { env: { CODEX_HOME: source.codexHome }, extraArgs: [], clearEnv: [] } }+ }+ return { ok: true, overrides: noOverrides() }+}diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.tsindex 921dcd8a2..2d3fa11d8 100644--- a/cli/src/lib/registry.spec.ts+++ b/cli/src/lib/registry.spec.ts@@ -1253,6 +1253,106 @@ describe('registry across a reboot and pane loss', () => {expect(saved[0]).not.toHaveProperty('bypassPermission')})+ const GRID_LAUNCH = {+ networkId: 'grid-abc',+ networkName: 'Team grid',+ baseUrl: 'https://grid.example/grid-abc/relay/v1',+ apiKey: 'gridkey-abc123',+ model: 'gpt-5',+ }++ it('carries the grid — launch, key and observed assignment — through the first hook bind', async () => {+ // The first SessionStart hook rebuilds the row. Before this, it rebuilt it without `grid`, so the+ // agent was announced as "on no grid" until the next scan re-read the process; and without+ // `gridLaunch`, so nothing could ever put it back on its grid.+ const transcriptPath = join(dataDir, 'session-g.jsonl')+ writeFileSync(transcriptPath, '{}\n')+ const { registry } = await loadRegistryModule()+ registry.load()++ const pending = registry.openPendingAgent({+ engine: 'claude',+ runtimes: [{ backend: 'tmux', paneId: '%9' }],+ cwd: '/tmp/demo',+ grid: { baseUrl: GRID_LAUNCH.baseUrl, model: 'gpt-5' },+ gridLaunch: GRID_LAUNCH,+ })!+ expect(pending.gridLaunch).toEqual(GRID_LAUNCH)+ expect(pending.launch).toEqual({ state: 'starting' })++ const bound = registry.register({ sessionId: 'session-g', transcriptPath, tmuxPane: '%9', cwd: '/tmp/demo' })+ expect(bound?.entry.agentId).toBe(pending.agentId)+ expect(bound?.entry).toMatchObject({+ grid: { baseUrl: GRID_LAUNCH.baseUrl, model: 'gpt-5' },+ gridLaunch: GRID_LAUNCH,+ gateway: null,+ })+ // The hook is the engine reporting in: the launch is over and the frame reads ready.+ expect(bound?.entry.launch).toBeUndefined()++ // Moved back to the engine's own login: the launch is gone, and a bind keeps it gone.+ expect(registry.setGridLaunch(pending.agentId, null)).toBe(true)+ expect(registry.register({ sessionId: 'session-g', transcriptPath, tmuxPane: '%9', cwd: '/tmp/demo' })?.entry.gridLaunch).toBeNull()+ expect(registry.setGridLaunch('nobody', null)).toBe(false)+ })++ it('drops any launch state on the hook that proves the engine is up', async () => {+ const transcriptPath = join(dataDir, 'session-f.jsonl')+ writeFileSync(transcriptPath, '{}\n')+ const { registry } = await loadRegistryModule()+ registry.load()+ const pending = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%9' }], cwd: '/tmp/demo' })!+ registry.setLaunch(pending.agentId, { state: 'failed', error: 'START_TIMEOUT' })+ const bound = registry.register({ sessionId: 'session-f', transcriptPath, tmuxPane: '%9', cwd: '/tmp/demo' })+ expect(bound?.entry.launch).toBeUndefined()+ })++ it('persists the grid launch across a reboot and forgets one it cannot trust', async () => {+ const transcriptPath = join(dataDir, 'session-a.jsonl')+ writeFileSync(transcriptPath, '{}\n')+ chmodSync(dataDir, 0o755)+ writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([+ persistedRow(transcriptPath, { grid: { baseUrl: GRID_LAUNCH.baseUrl, model: 'gpt-5' }, gridLaunch: GRID_LAUNCH }),+ persistedRow(transcriptPath, { agentId: 'agent-b', sessionId: 'session-b', runtimes: [{ backend: 'tmux', paneId: '%4' }], primaryRuntimeKey: 'tmux\u0000%4', tmuxPane: '%4', processIdentity: processIdentity(4243), grid: { baseUrl: GRID_LAUNCH.baseUrl, model: null }, gridLaunch: { baseUrl: GRID_LAUNCH.baseUrl } }),+ persistedRow(transcriptPath, { agentId: 'agent-c', sessionId: 'session-c', runtimes: [{ backend: 'tmux', paneId: '%5' }], primaryRuntimeKey: 'tmux\u0000%5', tmuxPane: '%5', processIdentity: processIdentity(4244) }),+ ]))+ writeLegacyStateFile(join(dataDir, 'registry-boot'), 'time:1')++ const { registry } = await loadRegistryModule()+ registry.load()+ expect(registry.rebootedSinceLastRun).toBe(true)+ // Kept verbatim: this is what restore relaunches the pane with.+ expect(registry.byAgent('agent-a')).toMatchObject({ processIdentity: null, gridLaunch: GRID_LAUNCH })+ // A half-remembered launch is worse than none — it would look like a grid launch and fail like one.+ expect(registry.byAgent('agent-b')?.gridLaunch).toBeNull()+ // A row from before the field existed stays distinguishable from "vendor login".+ expect(registry.byAgent('agent-c')).not.toHaveProperty('gridLaunch')+ const saved = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8')) as Array<Record<string, unknown>>+ expect(saved[0]).toMatchObject({ gridLaunch: GRID_LAUNCH })+ expect(saved[2]).not.toHaveProperty('gridLaunch')+ })++ it('a discovered Codex process fills in the profile it runs under, but never replaces one', async () => {+ const { registry } = await loadRegistryModule()+ registry.load()+ const opened = registry.openProcessAgent({ engine: 'codex', tmuxPane: '%5', processIdentity: processIdentity(77), codexHome: '/tmp/codex-work' })!+ expect(opened.entry.codexHome).toBe('/tmp/codex-work')+ // Discovery cannot have seen the credential: a discovered grid agent is observed, never relaunched.+ expect(opened.entry.gridLaunch).toBeNull()++ expect(registry.setCodexHome(opened.entry.agentId, '/tmp/codex-other')).toBe(false)+ expect(registry.byAgent(opened.entry.agentId)?.codexHome).toBe('/tmp/codex-work')+ registry.openProcessAgent({ engine: 'codex', tmuxPane: '%5', processIdentity: processIdentity(77), codexHome: '/tmp/codex-other' })+ expect(registry.byAgent(opened.entry.agentId)?.codexHome).toBe('/tmp/codex-work')++ const bare = registry.openProcessAgent({ engine: 'codex', tmuxPane: '%6', processIdentity: processIdentity(78) })!+ expect(bare.entry.codexHome).toBeNull()+ expect(registry.setCodexHome(bare.entry.agentId, '/tmp/codex-work')).toBe(true)+ expect(registry.byAgent(bare.entry.agentId)?.codexHome).toBe('/tmp/codex-work')+ const claude = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%7', processIdentity: processIdentity(79) })!+ expect(registry.setCodexHome(claude.entry.agentId, '/tmp/codex-work')).toBe(false)+ })+it('clearProcessIdentity forgets the pid everywhere it is indexed', async () => {const { registry } = await loadRegistryModule()registry.load()diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex 3d98b1241..aba34e4d8 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -36,6 +36,7 @@ import { env } from '../config/env.js'import { readCodexRolloutMeta, resolveCodexRollout } from '../engines/codex/rollout.js'import { ENGINES, type AgentEngine } from '../engines/types.js'import type { GridAssignment } from './gridAssignment.js'+import { parseGridLaunchOverride, type GridLaunchOverride } from './gridLaunch.js'import { commandcodeTranscriptPath } from '../engines/commandcode/transcript.js'import { agyTranscriptPath } from '../engines/agy/session.js'import { copilotTranscriptPath } from '../engines/copilot/session.js'@@ -96,9 +97,20 @@ export interface RegisteredSession {gateway?: 'ori' | null/*** The grid this pane's engine is pointed at, if any — read off the live process on every discovery- * exactly like `gateway`, never declared. See `gridAssignment.ts`. Carries no credential.+ * exactly like `gateway`, never declared. See `gridAssignment.ts`. Carries no credential; the+ * launch that put the engine there, credential included, is `gridLaunch` below.*/grid?: GridAssignment | null+ /**+ * The full grid launch this agent was last created or retargeted with, apiKey included. Persisted+ * (this file is 0600, see `secureState.ts`) so a pane recreated after a reboot (`restoreAgents`) or+ * respawned in place (`agent_restart`) is launched onto the SAME grid with the SAME credential+ * instead of silently coming back on the engine's own login. Never announced — `agentFrame` picks+ * its fields explicitly — and never logged. `grid` stays the observed, credential-free projection.+ * Null on a vendor-login agent; absent on a row written before this field existed, which restore+ * treats as "grid agent without a credential".+ */+ gridLaunch?: GridLaunchOverride | null/*** The CODEX_HOME folder this agent was launched against, if one was chosen instead of `~/.codex`.* Codex only. Unlike `grid`, this is chosen once at creation and never re-derived from the live@@ -682,6 +694,7 @@ class Registry {// This row's own CODEX_HOME profile, when it was created against one other than the default —// see RegisteredSession.codexHome.const rawCodexHome = raw?.codexHome ?? undefined+ const rawGridLaunch = normalizedGridLaunch(raw?.gridLaunch)let repairedCodexTranscript = falseif (engine === 'codex' && transcriptPath) {const meta = readCodexRolloutMeta(transcriptPath)@@ -735,6 +748,7 @@ class Registry {gateway: raw.gateway === 'ori' ? 'ori' : null,grid: normalizedGridAssignment(raw.grid),codexHome: typeof rawCodexHome === 'string' && rawCodexHome ? rawCodexHome : null,+ ...(rawGridLaunch !== undefined ? { gridLaunch: rawGridLaunch } : {}),...(raw.bypassPermission === true ? { bypassPermission: true } : {}),transcriptPath,title: titleDisplayName(typeof raw.title === 'string' ? raw.title : null),@@ -823,6 +837,9 @@ class Registry {processIdentity: ProcessIdentitygateway?: 'ori' | nullgrid?: GridAssignment | null+ /** Codex only: the CODEX_HOME the process was launched under, read off its environment. Fills a+ * row that does not know its profile yet; never overwrites one that does (see `codexHome`). */+ codexHome?: string | null}):{entry: RegisteredSession@@ -873,6 +890,7 @@ class Registry {// the last good one said rather than silently downgrading a gateway agent to a vendor one.if (input.gateway !== undefined) existing.gateway = input.gatewayif (input.grid !== undefined) existing.grid = input.grid+ if (input.codexHome && !existing.codexHome) existing.codexHome = input.codexHomeexisting.updatedAt = Date.now()this.index(existing)this.terminalAvailableAgents.add(existing.agentId)@@ -911,6 +929,9 @@ class Registry {engine,gateway: input.gateway ?? null,grid: input.grid ?? null,+ // A discovered grid agent has no credential the daemon ever saw: it can be observed, not relaunched.+ gridLaunch: null,+ codexHome: input.codexHome ?? null,transcriptPath: null,projectDir: basename(input.cwd ?? '') || agentId,cwd: input.cwd ?? null,@@ -940,6 +961,7 @@ class Registry {primaryRuntimeKey?: stringcwd?: string | nullgrid?: GridAssignment | null+ gridLaunch?: GridLaunchOverride | nullcodexHome?: string | nullbypassPermission?: boolean}): RegisteredSession | null {@@ -959,6 +981,7 @@ class Registry {engine: input.engine,gateway: null,grid: input.grid ?? null,+ gridLaunch: input.gridLaunch ?? null,codexHome: input.codexHome ?? null,...(input.bypassPermission ? { bypassPermission: true } : {}),transcriptPath: null,@@ -1093,10 +1116,19 @@ class Registry {const entry: RegisteredSession = {schemaVersion: 2,active: existing?.active ?? true,+ // No `launch`: a hook is the engine reporting for duty, so whatever the launch was — starting,+ // or failed by a watcher that gave up too early — it is over, and the frame reads `ready`.agentId,sessionId,boundAt: isNew ? now : existing?.boundAt ?? now,engine,+ // Both are facts about the live process the hook came from, re-read by discovery on every+ // pass — but a bind must not blank them in between, or the very first SessionStart hook would+ // announce a grid agent as "on no grid" until the next scan put it back.+ gateway: existing?.gateway ?? null,+ grid: existing?.grid ?? null,+ // The credential-bearing launch. Like codexHome: written once, carried forward, never re-derived.+ gridLaunch: existing?.gridLaunch ?? null,transcriptPath: effectiveTranscriptPath,projectDir: engine === 'grok' || engine === 'agy' || engine === 'copilot'? basename(input.cwd ?? existing?.cwd ?? '') || sessionId@@ -1290,6 +1322,28 @@ class Registry {return true}+ /** Fill in the Codex profile a row did not know (discovery read it off the live process). Never+ * replaces one it already has — the profile is chosen once, see `codexHome`. */+ setCodexHome(agentId: string, codexHome: string): boolean {+ const session = this.agents.get(agentId)+ if (!session || session.engine !== 'codex' || session.codexHome) return false+ session.codexHome = codexHome+ session.updatedAt = Date.now()+ this.save()+ return true+ }++ /** Record the launch an agent was last put onto a grid with (`agent_create` / `agent_retarget`), or+ * null once it was moved back to the engine's own login. */+ setGridLaunch(agentId: string, gridLaunch: GridLaunchOverride | null): boolean {+ const session = this.agents.get(agentId)+ if (!session) return false+ session.gridLaunch = gridLaunch+ session.updatedAt = Date.now()+ this.save()+ return true+ }+touchTranscript(sessionId: string, at = Date.now()): boolean {const session = this.bySession(sessionId)if (!session) return false@@ -1551,6 +1605,16 @@ function validProcessIdentity(value: unknown): value is ProcessIdentity {return !!p && Number.isSafeInteger(p.pid) && (p.pid ?? 0) > 0 && typeof p.executable === 'string' && typeof p.startMarker === 'string'}+/** A persisted grid launch. Anything short of a complete, well-formed override is treated as+ * "no credential" — a half-remembered key is worse than none, because a launch built from it would+ * look like a grid launch and fail like one. `undefined` (the field was never written) is kept+ * distinct from `null` (vendor login) so restore can tell a pre-upgrade grid row apart. */+function normalizedGridLaunch(value: unknown): GridLaunchOverride | null | undefined {+ if (value === undefined) return undefined+ const parsed = parseGridLaunchOverride(value)+ return parsed.state === 'ok' ? parsed.override : null+}+/** A persisted grid assignment. Lenient on `model` on purpose: a row that only knows WHERE it pointed* must still read as a grid agent, or a restore would relaunch it on the engine's own login. */function normalizedGridAssignment(value: unknown): GridAssignment | null {diff --git a/cli/src/lib/restoreAgents.spec.ts b/cli/src/lib/restoreAgents.spec.tsindex 07efc1386..5a1bee982 100644--- a/cli/src/lib/restoreAgents.spec.ts+++ b/cli/src/lib/restoreAgents.spec.ts@@ -1,7 +1,15 @@import { describe, expect, it, vi } from 'vitest'import type { AgentLaunch, ProcessIdentity, RegisteredSession } from './registry.js'import type { TerminalRuntimeRef, TmuxRuntimeRef } from './terminalTypes.js'-import { restoreAgents, type RestoreAgentsDeps, type RestoreLaunch } from './restoreAgents.js'+import { GRID_CREDENTIAL_REQUIRED, restoreAgents, type RestoreAgentsDeps, type RestoreLaunch } from './restoreAgents.js'+import type { GridLaunchOverride } from './gridLaunch.js'++const GRID: GridLaunchOverride = {+ networkId: 'grid-abc',+ networkName: 'Team grid',+ baseUrl: 'https://grid.example/grid-abc/relay/v1',+ apiKey: 'gridkey-abc123',+}const identity = (pid: number): ProcessIdentity => ({ pid, executable: 'claude', startMarker: `start ${pid}` })@@ -38,6 +46,8 @@ interface Harness {calls: string[]rows: Map<string, RegisteredSession>launches: Array<{ agentId: string; resumeSessionId?: string }>+ /** What createPane / respawn were handed, per agent — the env is where a grid's key travels. */+ launched: Array<{ agentId: string; launch: RestoreLaunch }>/** Per-pane scripted answers for probeProcess; shifted on each call. */probes: Map<string, Array<ProcessIdentity | null>>states: Map<string, Array<{ dead: boolean } | null>>@@ -48,11 +58,12 @@ interface Harness {released: string[]}-function harness(rows: RegisteredSession[], opts: { livePanes?: string[]; failCreate?: boolean; budgetMs?: number; settleMs?: number } = {}): Harness {+function harness(rows: RegisteredSession[], opts: { livePanes?: string[]; failCreate?: boolean; refuseLaunch?: boolean; budgetMs?: number; settleMs?: number } = {}): Harness {const h: Harness = {calls: [],rows: new Map(rows.map((r) => [r.agentId, r])),launches: [],+ launched: [],probes: new Map(),states: new Map(),nextPane: ['%0', '%1', '%2'],@@ -89,18 +100,31 @@ function harness(rows: RegisteredSession[], opts: { livePanes?: string[]; failCrinheritName: (from, to) => { note(`inheritName:${from}->${to}`) },},liveProcess: async (_entry, runtime) => live.has(runtime.paneId) ? identity(1000 + Number(runtime.paneId.slice(1))) : null,- buildLaunch: (entry, o) => {+ buildLaunch: async (entry, o) => {h.launches.push({ agentId: entry.agentId, ...(o.resumeSessionId ? { resumeSessionId: o.resumeSessionId } : {}) })- const launch: RestoreLaunch = { argv: [entry.engine, ...(o.resumeSessionId ? ['--resume', o.resumeSessionId] : [])] }+ if (opts.refuseLaunch) return { error: 'GRID_ENGINE_UNSUPPORTED', detail: 'no way to point it at a grid' }+ // The shape cli.ts builds: a grid's env and argv when the row kept its launch, a profile's+ // CODEX_HOME otherwise. Only the presence matters here; gridLaunch.ts specs the contents.+ const grid = entry.gridLaunch+ const launch: RestoreLaunch = {+ argv: [entry.engine, ...(o.resumeSessionId ? ['--resume', o.resumeSessionId] : []), ...(grid ? ['--grid', grid.networkId] : [])],+ ...(grid ? { env: { GRID_API_KEY: grid.apiKey } } : entry.codexHome ? { env: { CODEX_HOME: entry.codexHome } } : {}),+ }return launch},- createPane: async (entry) => {+ createPane: async (entry, launch) => {note(`createPane:${entry.agentId}`)+ h.launched.push({ agentId: entry.agentId, launch })h.paneCreates++if (opts.failCreate) return { ok: false, reason: 'tmux said no' }return { ok: true, runtime: { backend: 'tmux', paneId: h.nextPane.shift() ?? '%99' } }},- respawn: async (runtime, launch) => { note(`respawn:${runtime.paneId}:${launch.argv.join(' ')}`); h.respawns++; return { ok: true } },+ respawn: async (runtime, launch) => {+ note(`respawn:${runtime.paneId}:${launch.argv.join(' ')}`)+ h.launched.push({ agentId: 'respawn', launch })+ h.respawns+++ return { ok: true }+ },probeProcess: async (runtime) => {const queue = h.probes.get(runtime.paneId) ?? []return queue.length ? queue.shift()! : null@@ -179,17 +203,61 @@ describe('restoreAgents — which agents get a pane back', () => {expect(h.calls).toEqual([])})- it('skips herdr-only rows, failed launches and grid agents, saying why', async () => {+ it('skips herdr-only rows and failed launches, saying why', async () => {const h = harness([row({ agentId: 'herdr', runtimes: [{ backend: 'herdr', sessionName: 's', paneId: 'p' } as unknown as TerminalRuntimeRef] }),row({ agentId: 'broken', launch: { state: 'failed', error: 'START_TIMEOUT' } }),- row({ agentId: 'gridded', grid: { baseUrl: 'https://grid.example/relay', model: null } }),])const summary = await restoreAgents(h.deps)expect(summary.restored).toEqual([])- expect(summary.skipped.map((s) => s.agentId)).toEqual(['herdr', 'broken', 'gridded'])- expect(summary.skipped[2].reason).toMatch(/grid/)+ expect(summary.skipped.map((s) => s.agentId)).toEqual(['herdr', 'broken'])+ expect(h.paneCreates).toBe(0)+ })++ it('puts a grid agent back on its grid, key and all, when the row kept its launch', async () => {+ const h = harness([row({ agentId: 'gridded', grid: { baseUrl: GRID.baseUrl, model: null }, gridLaunch: GRID })])+ h.probes.set('%0', [identity(7)])+ const summary = await restoreAgents(h.deps)+ expect(summary).toEqual({ restored: ['gridded'], skipped: [], failed: [] })+ expect(h.launched).toEqual([{ agentId: 'gridded', launch: { argv: ['claude', '--resume', 'session-a', '--grid', 'grid-abc'], env: { GRID_API_KEY: 'gridkey-abc123' } } }])+ await settled(h, 1, 1)+ })++ it('the fresh fallback of a grid agent is a grid launch too', async () => {+ const h = harness([row({ agentId: 'gridded', grid: { baseUrl: GRID.baseUrl, model: null }, gridLaunch: GRID })])+ h.states.set('%0', [{ dead: true }])+ h.probes.set('%0', [null, identity(8)])+ await restoreAgents(h.deps)+ await settled(h, 1, 1)+ expect(h.launched.map((l) => l.launch.env)).toEqual([{ GRID_API_KEY: 'gridkey-abc123' }, { GRID_API_KEY: 'gridkey-abc123' }])+ expect(h.launched[1].launch.argv).toEqual(['claude', '--grid', 'grid-abc'])+ })++ it('does not relaunch a grid agent whose credential was never persisted, and marks it so', async () => {+ // A row written before `gridLaunch` existed: it knows WHERE it pointed and nothing else. On the+ // engine's own login it would spend the wrong account while looking identical.+ const h = harness([row({ agentId: 'legacy', grid: { baseUrl: 'https://grid.example/relay', model: null } })])+ const summary = await restoreAgents(h.deps)+ expect(summary.restored).toEqual([])+ expect(summary.skipped).toEqual([{ agentId: 'legacy', reason: expect.stringMatching(/credential not persisted/) }])expect(h.paneCreates).toBe(0)+ expect(h.calls).toEqual([`setLaunch:legacy:failed:${GRID_CREDENTIAL_REQUIRED}`])+ })++ it('a launch the machine cannot build fails the row instead of opening a pane on the wrong login', async () => {+ const h = harness([row({ agentId: 'gridded', grid: { baseUrl: GRID.baseUrl, model: null }, gridLaunch: GRID })], { refuseLaunch: true })+ const summary = await restoreAgents(h.deps)+ expect(summary.failed).toEqual([{ agentId: 'gridded', reason: 'no way to point it at a grid' }])+ expect(h.paneCreates).toBe(0)+ expect(h.calls).toEqual(['clearIdentity:gridded@tx', 'setLaunch:gridded:failed:GRID_ENGINE_UNSUPPORTED@tx'])+ })++ it('a Codex profile agent comes back under its own CODEX_HOME', async () => {+ const h = harness([row({ agentId: 'profiled', engine: 'codex', codexHome: '/home/u/.codex-work' })])+ h.probes.set('%0', [identity(9)])+ await restoreAgents(h.deps)+ expect(h.launched[0].launch.env).toEqual({ CODEX_HOME: '/home/u/.codex-work' })+ await settled(h, 1, 1)})it('records a pane that could not be opened and leaves the row untouched', async () => {diff --git a/cli/src/lib/restoreAgents.ts b/cli/src/lib/restoreAgents.tsindex a64f10aa6..988828204 100644--- a/cli/src/lib/restoreAgents.ts+++ b/cli/src/lib/restoreAgents.ts@@ -19,6 +19,12 @@* 3. The row keeps `launch: starting` and only gets its process identity from here. The reconcile* pass after the release then matches the process, sees a launch in progress, and does the* full ready → attach → announce sequence it already does for `agent_create`.+ *+ * A grid agent comes back onto its grid: the registry kept the launch it was created or retargeted+ * with (`gridLaunch`, credential included), and `buildLaunch` turns that back into the same env and+ * argv `agent_create` used. A row that only knows WHERE it pointed (`grid` without `gridLaunch`,+ * written before the credential was persisted) is not relaunched — on the engine's own login it would+ * spend the wrong account while looking identical — and is marked so the app can say why.*/import type { AgentEngine } from '../engines/types.js'@@ -31,6 +37,11 @@ export interface RestoreLaunch {env?: Record<string, string>}+export type RestoreLaunchResult = RestoreLaunch | { error: string; detail: string }++/** The row knows it was on a grid but not how to get back there. */+export const GRID_CREDENTIAL_REQUIRED = 'GRID_CREDENTIAL_REQUIRED'+export interface RestoreAgentsDeps {registry: {list(): RegisteredSession[]@@ -46,7 +57,9 @@ export interface RestoreAgentsDeps {/** The engine process still running in this row's pane, or null when tmux does not know the pane* at all — including when no tmux server is running — or the pane has become something else. */liveProcess: (entry: RegisteredSession, runtime: TmuxRuntimeRef) => Promise<ProcessIdentity | null>- buildLaunch: (entry: RegisteredSession, opts: { resumeSessionId?: string }) => RestoreLaunch+ /** The pane's launch — engine argv plus whatever puts it back on its grid / profile. A grid the+ * machine cannot honour (unsupported engine, tmux too old, config dir unwritable) is a refusal. */+ buildLaunch: (entry: RegisteredSession, opts: { resumeSessionId?: string }) => Promise<RestoreLaunchResult>createPane: (entry: RegisteredSession, launch: RestoreLaunch) => Promise<| { ok: true; runtime: TmuxRuntimeRef }| { ok: false; reason: string }@@ -126,10 +139,22 @@ export async function restoreAgents(deps: RestoreAgentsDeps): Promise<RestoreSumif (!entry.processIdentity) deps.registry.updateProcessIdentity(entry.agentId, live)continue}- // The registry keeps only where a grid agent pointed, never the credential the launch needs —- // and launching it on the engine's own login instead would spend the wrong account while- // looking identical. Refusing is the rule gridLaunch.ts already sets.- if (entry.grid) { summary.skipped.push({ agentId: entry.agentId, reason: 'grid agent; credential not persisted' }); continue }+ // A grid row without its launch: written before the credential was persisted, or a grid agent+ // discovery adopted from a pane the daemon never launched (it saw the endpoint, never the key).+ // Launching it on the engine's own login instead would spend the wrong account while looking+ // identical — refusing is the rule gridLaunch.ts already sets. Marked, not just skipped: the row+ // has no pane to come back to, and the app should be able to say why before discovery lets it go.+ if (entry.grid && !entry.gridLaunch) {+ const reason = 'grid agent; credential not persisted'+ summary.skipped.push({ agentId: entry.agentId, reason })+ deps.registry.setLaunch(entry.agentId, {+ state: 'failed',+ error: GRID_CREDENTIAL_REQUIRED,+ detail: `${entry.engine} was on a grid, but this machine no longer holds the credential to put it back there. Create it again from the app.`,+ })+ deps.log(`[restore] ${entry.engine} · agent ${entry.agentId} · skipped · ${reason}`)+ continue+ }missing.push({ entry, runtime })}if (!missing.length) return summary@@ -142,7 +167,13 @@ export async function restoreAgents(deps: RestoreAgentsDeps): Promise<RestoreSum// into this agent (route adoption requires either no identity or a matching pid).deps.registry.clearProcessIdentity(entry.agentId)const resumeSessionId = entry.sessionId || undefined- const launch = deps.buildLaunch(entry, resumeSessionId ? { resumeSessionId } : {})+ const launch = await deps.buildLaunch(entry, resumeSessionId ? { resumeSessionId } : {})+ if ('error' in launch) {+ summary.failed.push({ agentId: entry.agentId, reason: launch.detail })+ deps.registry.setLaunch(entry.agentId, { state: 'failed', error: launch.error, detail: launch.detail })+ deps.log(`[restore] ${entry.engine} · agent ${entry.agentId} · could not build its launch · ${launch.detail}`)+ continue+ }const created = await deps.createPane(entry, launch)if (!created.ok) {summary.failed.push({ agentId: entry.agentId, reason: created.reason })@@ -154,8 +185,11 @@ export async function restoreAgents(deps: RestoreAgentsDeps): Promise<RestoreSumdeps.registry.updateRuntimes(entry.agentId, [created.runtime], key)deps.registry.setLaunch(entry.agentId, { state: 'starting' })summary.restored.push(entry.agentId)+ // The grid is named because the pane gives nothing away: the engine looks exactly like one on+ // its own login. The key is never printed.deps.log(`[restore] ${entry.engine} · agent ${entry.agentId} · pane ${dead.paneId} → ${created.runtime.paneId}`- + (resumeSessionId ? ` · resuming ${resumeSessionId.slice(0, 8)}` : ' · fresh session'))+ + (resumeSessionId ? ` · resuming ${resumeSessionId.slice(0, 8)}` : ' · fresh session')+ + (entry.gridLaunch ? ` · grid ${entry.gridLaunch.networkName}` : ''))watches.push(() => watchRestoredPane(deps, entry, created.runtime, !!resumeSessionId, budgetMs))}})@@ -191,7 +225,12 @@ async function watchRestoredPane(deps.log(`[restore] ${engine} · agent ${agentId} · did not come back up resuming its session — retrying fresh`)deps.registry.inheritName(entry.sessionId, agentId)deps.registry.unbindSession(entry.sessionId)- const spawned = await deps.respawn(runtime, deps.buildLaunch(entry, {}))+ const launch = await deps.buildLaunch(entry, {})+ if ('error' in launch) {+ fail(launch.error, launch.detail)+ return false+ }+ const spawned = await deps.respawn(runtime, launch)if (!spawned.ok) {fail('ENGINE_DID_NOT_START', `${engine} could not be relaunched fresh: ${spawned.reason ?? 'unknown reason'}`)return falsediff --git a/cli/src/lib/terminalAgentDiscovery.codexHome.spec.ts b/cli/src/lib/terminalAgentDiscovery.codexHome.spec.tsnew file mode 100644index 000000000..bc36806d2--- /dev/null+++ b/cli/src/lib/terminalAgentDiscovery.codexHome.spec.ts@@ -0,0 +1,70 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import type { ProcessRow } from './tmux.js'+import type { TerminalBackend } from './terminalBackend.js'+import type { TerminalRootObservation, TerminalRuntimeRef } from './terminalTypes.js'++/**+ * The Codex profile a process runs under rides the LIVE discovery path, pinned the same way `grid`+ * is in `terminalAgentDiscovery.grid.spec.ts`: a probe wired on the wrong function stays green while+ * every discovered codex row arrives with `codexHome` undefined — and its transcript then fails+ * validation against the default profile. `codexHomeProbe.spec.ts` covers what the probe reads.+ */++const probeGatewayRuntime = vi.hoisted(() => vi.fn())+const probeGridAssignment = vi.hoisted(() => vi.fn())+const probeCodexHome = vi.hoisted(() => vi.fn())+const processRows = vi.hoisted(() => vi.fn())++vi.mock('./gatewayRuntime.js', () => ({ probeGatewayRuntime }))+vi.mock('./gridAssignment.js', () => ({ probeGridAssignment }))+vi.mock('./codexHomeProbe.js', () => ({ probeCodexHome }))+vi.mock('./tmux.js', async (importOriginal) => ({+ ...await importOriginal<typeof import('./tmux.js')>(),+ processRows,+}))++const { probeTerminalAgents } = await import('./terminalAgentDiscovery.js')++const START = 'Sat Aug 15 10:00:00 2026'+const row = (pid: number, parentPid: number, executable: string, args = executable): ProcessRow =>+ ({ pid, parentPid, executable, startMarker: START, args })++const TMUX_RUNTIME: TerminalRuntimeRef = { backend: 'tmux', paneId: '%1' }+const OTHER_RUNTIME: TerminalRuntimeRef = { backend: 'tmux', paneId: '%2' }++function backendWith(roots: TerminalRootObservation[]): TerminalBackend {+ return { name: 'tmux', instanceId: 'tmux', inventory: async () => ({ state: 'available', roots }) } as unknown as TerminalBackend+}++beforeEach(() => {+ probeGatewayRuntime.mockReset()+ probeGatewayRuntime.mockResolvedValue({ kind: null })+ probeGridAssignment.mockReset()+ probeGridAssignment.mockResolvedValue(null)+ probeCodexHome.mockReset()+ processRows.mockReset()+})++describe('Codex profile on the live terminal discovery path', () => {+ it('reports the profile off the process, and the probe decides for every engine', async () => {+ processRows.mockResolvedValue([row(10, 1, 'bash'), row(30, 10, 'codex'), row(20, 1, 'bash'), row(40, 20, 'claude')])+ probeCodexHome.mockImplementation(async (_identity: unknown, engine: string) => engine === 'codex' ? '/home/u/.codex-work' : null)+ const probe = await probeTerminalAgents(+ [backendWith([{ runtime: TMUX_RUNTIME, rootPid: 10, cwd: '/work' }, { runtime: OTHER_RUNTIME, rootPid: 20, cwd: '/work' }])],+ ['tmux'],+ [],+ 999,+ )+ const byEngine = Object.fromEntries(probe.agents.map((agent) => [agent.engine, agent.codexHome]))+ expect(byEngine).toEqual({ codex: '/home/u/.codex-work', claude: null })+ expect(probeCodexHome).toHaveBeenCalledTimes(2)+ for (const [identity] of probeCodexHome.mock.calls) expect(identity).toMatchObject({ startMarker: START })+ })++ it('passes an unreadable probe through as undefined, so the registry keeps what it knew', async () => {+ processRows.mockResolvedValue([row(10, 1, 'bash'), row(30, 10, 'codex')])+ probeCodexHome.mockResolvedValue(undefined)+ const probe = await probeTerminalAgents([backendWith([{ runtime: TMUX_RUNTIME, rootPid: 10, cwd: '/work' }])], ['tmux'], [], 999)+ expect(probe.agents[0]).toHaveProperty('codexHome', undefined)+ })+})diff --git a/cli/src/lib/terminalAgentDiscovery.ts b/cli/src/lib/terminalAgentDiscovery.tsindex 31e9a5c90..e223c1a19 100644--- a/cli/src/lib/terminalAgentDiscovery.ts+++ b/cli/src/lib/terminalAgentDiscovery.ts@@ -7,6 +7,7 @@ import {} from './engineBin.js'import { probeGatewayRuntime } from './gatewayRuntime.js'import { probeGridAssignment, type GridAssignment } from './gridAssignment.js'+import { probeCodexHome } from './codexHomeProbe.js'import type { TerminalBackend } from './terminalBackend.js'import {ambiguousAgentProcess,@@ -51,6 +52,12 @@ export interface DiscoveredTerminalAgent {* Backend-agnostic for the same reason `gateway` is: it is a fact about the process, not the pane.*/grid?: GridAssignment | null+ /**+ * Codex only: the CODEX_HOME profile the process was launched under, when it is not this machine's+ * default. null = the default profile (or not Codex); undefined = the probe could not read the+ * process, and the registry keeps what it already knows. See `codexHomeProbe.ts`.+ */+ codexHome?: string | null}export interface TerminalTargetProbe {@@ -245,6 +252,8 @@ export async function probeTerminalAgents(agent.gateway = runtime.kind// Same process, same cached read — the grid costs no extra `ps`.agent.grid = await probeGridAssignment(agent.processIdentity, agent.engine, agent.args)+ // And, for Codex, the profile it runs under — a fact about the process the row cannot otherwise learn.+ agent.codexHome = await probeCodexHome(agent.processIdentity, agent.engine)}))return { processTableAvailable: true, targets, ...discovered }}diff --git a/cli/src/lib/tmuxAgentDiscovery.ts b/cli/src/lib/tmuxAgentDiscovery.tsindex 6ae7da897..af81b226f 100644--- a/cli/src/lib/tmuxAgentDiscovery.ts+++ b/cli/src/lib/tmuxAgentDiscovery.ts@@ -16,6 +16,7 @@ import {import type { AgentEngine } from '../engines/types.js'import { probeGatewayRuntime } from './gatewayRuntime.js'import { probeGridAssignment, type GridAssignment } from './gridAssignment.js'+import { probeCodexHome } from './codexHomeProbe.js'import { isHarnessSession } from './harnessSessionLabel.js'import type { ProcessIdentity, RegisteredSession } from './registry.js'import {@@ -55,6 +56,8 @@ export interface DiscoveredTmuxAgent {* see `probeGridAssignment`.*/grid?: GridAssignment | null+ /** Codex only: the non-default CODEX_HOME the process runs under; same three answers as `grid`. */+ codexHome?: string | null}export type TmuxAgentProbe =@@ -255,6 +258,8 @@ export async function probeTmuxAgents(const runtime = await probeGatewayRuntime(agent.processIdentity, agent.args)agent.gateway = runtime.kindagent.grid = await probeGridAssignment(agent.processIdentity, agent.engine, agent.args)+ // And, for Codex, the profile it runs under — a fact about the process the row cannot otherwise learn.+ agent.codexHome = await probeCodexHome(agent.processIdentity, agent.engine)}))return probe}