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 support for resumed Claude and Codex sessions with legacy format and fork handling
0xken158df3f85041bf
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex abafaa967..a20ad2197 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -78,7 +78,7 @@ import { tmuxSupportsSessionEnv, TMUX_SESSION_ENV_MIN } from './lib/tmuxVersion.import { clearDeleted, isRecentlyDeleted, markDeleted } from './lib/deletedSessions.js'import { terminateDeletedAgent, checkPidRuntime } from './lib/deleteAgentFallback.js'import { AgentRestartCoordinator, restartAgent, type RestartAgentDeps } from './lib/restartAgent.js'-import { claudeContinuation, findLiveSession } from './lib/sessionRepair.js'+import { claudeContinuation, findLiveSession, findResumedTranscript } from './lib/sessionRepair.js'import { TmuxBackend } from './lib/tmuxBackend.js'import { DEFAULT_HOST_THEME, loadHostTheme, saveHostTheme, type HostTheme } from './lib/hostTheme.js'import { createAndRegisterPane } from './lib/createAgentPane.js'@@ -87,7 +87,7 @@ import { restoreAgents } from './lib/restoreAgents.js'import { buildLaunchOverrides, validateLaunchOverrides, type LaunchOverrides, type LaunchOverridesDeps, type LaunchOverridesResult, type LaunchSource } from './lib/launchOverrides.js'import { prepareCodexResume } from './engines/codex/portableHistory.js'import { buildHarnessSessionLabel } from './lib/harnessSessionLabel.js'-import { listTmuxPanes } from './lib/tmuxAgentDiscovery.js'+import { adoptLegacyHarnessSessions, listTmuxPanes } from './lib/tmuxAgentDiscovery.js'import { installedDsh } from './dsh/installed.js'import { dshVerdictPath, dshViewerName } from './dsh/manifest.js'import { catalogEntry } from './dsh/catalog.js'@@ -1410,6 +1410,14 @@ async function runForeground(session: AuthSession): Promise<void> {}console.log(`[terminal] enabled backends: ${terminalConfig.backends.join(', ')}`)if (tmuxBackend) {+ // Before the first inventory: sessions a pre-prefix build named `<engine>-<ts>` are renamed to+ // `harness-<engine>-<ts>` so discovery's whitelist sees the registry's own panes again.+ const ownedPanes = new Map(registry.list().flatMap((session) => session.runtimes+ .filter((runtime) => runtime.backend === 'tmux')+ .map((runtime) => [runtime.paneId, session.engine] as const)))+ for (const adopted of await adoptLegacyHarnessSessions(ownedPanes)) {+ console.log(`[terminal] renamed tmux session ${adopted.from} → ${adopted.to} (pane ${adopted.paneId}) · named by a build before the harness- prefix`)+ }const tmuxStartup = await tmuxBackend.inventory()console.log(tmuxStartup.state === 'available'? '[terminal] tmux: available'@@ -2793,8 +2801,13 @@ async function runForeground(session: AuthSession): Promise<void> {? await findAgyTranscript(env.AGY_HOME, sessionId) ?? undefined: observed.engine === 'copilot'? await findCopilotTranscript(env.COPILOT_HOME, sessionId) ?? undefined- : undefined- if ((observed.engine === 'cursor' || observed.engine === 'grok') && !transcriptPath) return+ : observed.engine === 'claude' || observed.engine === 'codex'+ ? await findResumedTranscript(observed.engine, sessionId, { codexHome: agent.codexHome ?? undefined }) ?? undefined+ : undefined+ // The registry refuses a claude/codex session without its file, so a resume of a transcript this+ // machine does not have is not a session — the hook that follows the user's next prompt will say.+ if ((observed.engine === 'cursor' || observed.engine === 'grok' || observed.engine === 'claude' || observed.engine === 'codex')+ && !transcriptPath) return} else {const attempts = repairAttempts.get(agent.agentId) ?? 0const lastAttempt = lastRepairAttempt.get(agent.agentId) ?? 0diff --git a/cli/src/lib/harnessSessionLabel.ts b/cli/src/lib/harnessSessionLabel.tsindex b7732eda2..7887f580a 100644--- a/cli/src/lib/harnessSessionLabel.ts+++ b/cli/src/lib/harnessSessionLabel.ts@@ -21,3 +21,14 @@ export function isHarnessSession(sessionName: string): boolean {export function isHarnessSessionFor(sessionName: string, engine: string): boolean {return sessionName.startsWith(`${HARNESS_SESSION_PREFIX}${engine}-`)}++/**+ * The label a build before the prefix (2026-08-29, `80a354e4`) gave the very same sessions:+ * `<engine>-<ms>`. A pane under one of these came through `agent_create` like any other, yet is+ * invisible to `isHarnessSession` — the daemon renames it on startup (`adoptLegacyHarnessSessions`)+ * rather than teaching discovery a second convention. The 13-digit millisecond stamp is what keeps+ * a user's own `work` or `claude-notes` session from matching.+ */+export function isLegacyHarnessSession(sessionName: string): boolean {+ return !isHarnessSession(sessionName) && /^[a-z][a-z0-9]*-\d{13}$/.test(sessionName)+}diff --git a/cli/src/lib/sessionRepair.spec.ts b/cli/src/lib/sessionRepair.spec.tsindex c99013939..461f1a8c1 100644--- a/cli/src/lib/sessionRepair.spec.ts+++ b/cli/src/lib/sessionRepair.spec.ts@@ -380,3 +380,36 @@ describe('claudeContinuation', () => {await expect(claudeContinuation('/nonexistent/path/session.jsonl')).resolves.toBeNull()})})++describe('findResumedTranscript', () => {+ // A `claude --resume <id>` / `codex resume <id>` names its session on argv, and discovery binds that+ // id without waiting for a hook — but only to a transcript this machine actually holds, because the+ // registry refuses a claude/codex session with no file behind it.+ it('finds a claude transcript by its id across the project folders', async () => {+ const root = tempRoot()+ const id = 'f56f0a36-aa58-4af1-a6e2-a77386122332'+ writeTranscript(root, '-home-agent-abc', id, '/home/agent/abc', STARTED_AT)+ writeTranscript(root, '-home-agent-proj', 'other-session', '/home/agent/proj', STARTED_AT)+ const { findResumedTranscript } = await load(root)++ await expect(findResumedTranscript('claude', id)).resolves.toBe(join(root, '-home-agent-abc', `${id}.jsonl`))+ await expect(findResumedTranscript('claude', 'f56f0a36-0000-4af1-a6e2-a77386122332')).resolves.toBeNull()+ })++ it('finds a codex rollout under the agent\'s own profile', async () => {+ const profile = tempRoot()+ const id = 'a1b2c3d4-1111-4a4a-8a8a-000000000003'+ const file = writeCodexRollout(profile, id, CWD, STARTED_AT)+ vi.resetModules()+ const { findResumedTranscript } = await import('./sessionRepair.js')++ await expect(findResumedTranscript('codex', id, { codexHome: profile })).resolves.toBe(file)+ })++ it('never treats an argv value that is not a session id as one', async () => {+ const root = tempRoot()+ const { findResumedTranscript } = await load(root)+ await expect(findResumedTranscript('claude', '../../etc/passwd')).resolves.toBeNull()+ await expect(findResumedTranscript('cursor', 'f56f0a36-aa58-4af1-a6e2-a77386122332')).resolves.toBeNull()+ })+})diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.tsindex d69a4140d..c17b87266 100644--- a/cli/src/lib/sessionRepair.ts+++ b/cli/src/lib/sessionRepair.ts@@ -21,7 +21,7 @@ import { promisify } from 'util'import { env } from '../config/env.js'import { museEvent, museWorkspaceRoot } from '../engines/muse/normalizer.js'import type { AgentEngine } from '../engines/types.js'-import { readCodexRolloutMeta } from '../engines/codex/rollout.js'+import { readCodexRolloutMeta, resolveCodexRollout } from '../engines/codex/rollout.js'import { agyConversationForPid, findAgyTranscript } from '../engines/agy/session.js'import { copilotSessionCwd, copilotSessionForPid, findCopilotTranscript } from '../engines/copilot/session.js'import { sqlitePreflightMessage } from './sqliteAvailability.js'@@ -433,3 +433,31 @@ export async function claudeContinuation(transcriptPath: string): Promise<Repair}return { sessionId: nextId, transcriptPath: nextPath }}++/**+ * The transcript behind a session id a claude/codex process names on its own command line+ * (`claude --resume <id>`, `codex resume <id>`) — the file `registry.register` insists on for those+ * two engines, which argv does not carry. Claude keeps one file per session under+ * `<projects>/<encoded cwd>/<id>.jsonl`; the cwd encoding is Claude's to define, so the project+ * folders are listed rather than the name derived. Codex names its rollout after the thread id, and+ * the rollout walker already knows that layout. Only a file that exists is returned: a resume of a+ * session this machine never wrote (or one that was deleted) binds nothing.+ */+export async function findResumedTranscript(+ engine: AgentEngine,+ sessionId: string,+ opts?: { codexHome?: string },+): Promise<string | null> {+ if (!/^[0-9a-f-]{16,}$/i.test(sessionId)) return null+ if (engine === 'codex') return resolveCodexRollout(sessionId, join(opts?.codexHome || env.CODEX_HOME, 'sessions'))+ if (engine !== 'claude') return null+ let projects: string[]+ try { projects = await readdir(env.CLAUDE_PROJECTS_DIR) } catch { return null }+ for (const project of projects) {+ const candidate = join(env.CLAUDE_PROJECTS_DIR, project, `${sessionId}.jsonl`)+ try {+ if ((await stat(candidate)).isFile()) return candidate+ } catch { /* not this project */ }+ }+ return null+}diff --git a/cli/src/lib/tmux.spec.ts b/cli/src/lib/tmux.spec.tsindex 576d5caf9..3ed39b39d 100644--- a/cli/src/lib/tmux.spec.ts+++ b/cli/src/lib/tmux.spec.ts@@ -263,11 +263,26 @@ describe('tmux process primitives', () => {expect(resumeSessionId('grok', 'grok -r 53d3843c-724e-47ff-ae3a-9fedfa328bba')).toBe('53d3843c-724e-47ff-ae3a-9fedfa328bba')expect(resumeSessionId('commandcode', 'cmd -r Greeting')).toBeNull()- expect(resumeSessionId('claude', 'claude --resume 53d3843c-724e-47ff-ae3a-9fedfa328bba')).toBeNull()- expect(resumeSessionId('codex', 'codex resume 53d3843c-724e-47ff-ae3a-9fedfa328bba')).toBeNull()expect(resumeSessionId('devin', 'devin --resume 53d3843c-724e-47ff-ae3a-9fedfa328bba')).toBeNull()})+ it('reads a claude/codex resume id from argv, but never the parent of a fork', () => {+ // A daemon that could not see the pane when SessionStart fired (a session named by an older build)+ // has only argv to learn the session from — measured on machine-remote-1, where six agents sat+ // sessionless for ten days and could not be forked.+ expect(resumeSessionId('claude', '/opt/agent-cli/.local/bin/claude --resume f56f0a36-aa58-4af1-a6e2-a77386122332'))+ .toBe('f56f0a36-aa58-4af1-a6e2-a77386122332')+ expect(resumeSessionId('claude', 'claude --dangerously-skip-permissions -r f4749d75-aef8-4d07-8031-48e2abecf7e5'))+ .toBe('f4749d75-aef8-4d07-8031-48e2abecf7e5')+ expect(resumeSessionId('codex', 'node /usr/local/bin/codex resume 53d3843c-724e-47ff-ae3a-9fedfa328bba --approve-for-me'))+ .toBe('53d3843c-724e-47ff-ae3a-9fedfa328bba')+ // `--resume <parent> --fork-session` writes a NEW session: the id on argv is the parent's.+ expect(resumeSessionId('claude', 'claude --resume 53d3843c-724e-47ff-ae3a-9fedfa328bba --fork-session')).toBeNull()+ // `codex fork <parent>` likewise names the parent, and is not a resume.+ expect(resumeSessionId('codex', 'codex fork 53d3843c-724e-47ff-ae3a-9fedfa328bba')).toBeNull()+ expect(resumeSessionId('claude', 'claude --continue')).toBeNull()+ })+it('reads bypass-permission mode from a live process argv via exact token match', () => {expect(bypassPermissionActive('claude', '/usr/local/bin/claude --permission-mode auto')).toBe(true)expect(bypassPermissionActive('claude', 'claude --permission-mode=auto --resume abc')).toBe(true)diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.tsindex 77796c83b..33494e851 100644--- a/cli/src/lib/tmux.ts+++ b/cli/src/lib/tmux.ts@@ -540,15 +540,23 @@ function selectEngineProcess(* SessionStart hook fires for a NEW session, so a pane that reattached to an old one is invisible to the* daemon until the user happens to type. Read from each CLI's own `--help` on 2026-08-03.*- * Two deliberate holes:- * - `--continue` / `-c` carries NO id on any of these CLIs. Nothing can be recovered from argv there.- * - claude and codex are absent: `registry.register` demands a transcript path for those two, which- * argv does not carry — and both DO fire SessionStart on resume, so there is nothing to repair.+ * One deliberate hole: `--continue` / `-c` carries NO id on any of these CLIs. Nothing can be+ * recovered from argv there.+ *+ * claude and codex DO fire SessionStart on resume, so their argv is normally redundant — but a hook+ * only helps a daemon that was listening for it. An agent whose SessionStart landed while the daemon+ * could not see its pane (a session named by an older build, before the `harness-` whitelist) sits+ * with no session until the user types again, and cannot be forked meanwhile. Their ids are read+ * here for that case; `registry.register` still demands the transcript, which sessionRepair's+ * `findResumedTranscript` derives from the id. `--fork-session` (claude) writes a NEW session, so+ * that argv names the PARENT and must not bind — `codex fork <id>` never matched `resume` to begin with.** The id pattern is a filter, not decoration: `-r` on Command Code takes "a name (use quotes for* multi-word names)", so a title would otherwise be registered as a session id.*/-const RESUME_ARGS: Partial<Record<RegisteredSession['engine'], { flags: string[]; id: RegExp }>> = {+const RESUME_ARGS: Partial<Record<RegisteredSession['engine'], { flags: string[]; id: RegExp; unless?: string[] }>> = {+ claude: { flags: ['--resume', '-r'], id: /^[0-9a-f-]{16,}$/i, unless: ['--fork-session'] },+ codex: { flags: ['resume'], id: /^[0-9a-f-]{16,}$/i },cursor: { flags: ['--resume'], id: /^[0-9a-f-]{16,}$/i },opencode: { flags: ['--session', '-s'], id: /^ses_[A-Za-z0-9]+$/ },// Kilo inherits opencode's resume flags and its `ses_` id prefix — measured on this machine's kilo.db:@@ -605,6 +613,10 @@ const LEGACY_BYPASS_FLAGS: Partial<Record<RegisteredSession['engine'], string[][export function resumeSessionId(engine: RegisteredSession['engine'], args: string): string | null {const spec = RESUME_ARGS[engine]if (!spec) return null+ if (spec.unless) {+ const tokens = argvTokens(args)+ if (spec.unless.some((flag) => tokens.includes(flag))) return null+ }for (const flag of spec.flags) {const escaped = flag.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')const value = new RegExp(`(?:^|\\s)${escaped}(?:=|\\s+)(\\S+)`, 'i').exec(args)?.[1]diff --git a/cli/src/lib/tmuxAgentDiscovery.ts b/cli/src/lib/tmuxAgentDiscovery.tsindex 5cd411216..4db1d722d 100644--- a/cli/src/lib/tmuxAgentDiscovery.ts+++ b/cli/src/lib/tmuxAgentDiscovery.ts@@ -17,7 +17,7 @@ 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 { buildHarnessSessionLabel, isHarnessSession, isLegacyHarnessSession } from './harnessSessionLabel.js'import { psEnv } from './childLocale.js'import type { ProcessIdentity, RegisteredSession } from './registry.js'import {@@ -147,6 +147,43 @@ export async function listTmuxPanes(): Promise<TmuxPaneInventory> {return { ok: true, panes: parsePanes(result.stdout).filter((pane) => isHarnessSession(pane.tmuxSessionName)) }}+export interface AdoptedLegacySession { from: string; to: string; paneId: string }++/**+ * Bring the sessions an older build created — `<engine>-<ts>`, from before the `harness-` prefix —+ * under the current convention, so the whitelist above sees them again. Only for panes the registry+ * owns (`ownedPanes`: pane id → the row's engine): a stray session that merely looks legacy is left+ * alone. One rename per session, whichever of its panes is met first.+ *+ * Measured on machine-remote-1: six agents from before the prefix sat dormant for ten days after the+ * whitelist landed — never re-observed, so their process identity was never refreshed and every hook+ * bind that followed was released on the spot ("process changed under tmux pane"). Each was on screen,+ * answering, and had no session to fork.+ */+export async function adoptLegacyHarnessSessions(+ ownedPanes: ReadonlyMap<string, string>,+ now: number = Date.now(),+): Promise<AdoptedLegacySession[]> {+ if (!ownedPanes.size) return []+ const result = await execText('tmux', ['list-panes', '-a', '-F', '#{pane_id}|#{pane_pid}|#{session_name}|#{pane_current_path}'], 2_000)+ if (!result.ok) return []+ const adopted: AdoptedLegacySession[] = []+ const seen = new Set<string>()+ for (const pane of parsePanes(result.stdout)) {+ const engine = ownedPanes.get(pane.tmuxPane)+ if (!engine || seen.has(pane.tmuxSessionName) || !isLegacyHarnessSession(pane.tmuxSessionName)) continue+ seen.add(pane.tmuxSessionName)+ // `now + n`: two sessions of one engine renamed in the same millisecond would otherwise collide.+ // Counted by session met, not by rename that succeeded, so a failed rename never hands its label+ // to the next one.+ const to = buildHarnessSessionLabel(engine, now + seen.size - 1)+ // `=name` is tmux's exact match; a bare name may also be read as a prefix or a pane target.+ const renamed = await execText('tmux', ['rename-session', '-t', `=${pane.tmuxSessionName}`, to], 2_000)+ if (renamed.ok) adopted.push({ from: pane.tmuxSessionName, to, paneId: pane.tmuxPane })+ }+ return adopted+}+function childrenByParent(rows: readonly ProcessRow[]): Map<number, ProcessRow[]> {const children = new Map<number, ProcessRow[]>()for (const row of rows) {diff --git a/cli/src/lib/tmuxLegacySessions.spec.ts b/cli/src/lib/tmuxLegacySessions.spec.tsnew file mode 100644index 000000000..aee9df7a4--- /dev/null+++ b/cli/src/lib/tmuxLegacySessions.spec.ts@@ -0,0 +1,85 @@+import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { delimiter, join } from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+import { isLegacyHarnessSession } from './harnessSessionLabel.js'+import { adoptLegacyHarnessSessions } from './tmuxAgentDiscovery.js'++const originalPath = process.env.PATH+const dirs: string[] = []++afterEach(() => {+ process.env.PATH = originalPath+ delete process.env.TMUX_LEGACY_CALLS+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })+})++/** A fake tmux: answers `list-panes` with the given inventory and records every call. */+function fakeTmux(panes: string): string {+ const dir = mkdtempSync(join(tmpdir(), 'tmux-legacy-'))+ dirs.push(dir)+ const calls = join(dir, 'calls')+ const tmux = join(dir, 'tmux')+ writeFileSync(tmux, `#!/bin/sh+printf '%s\\n' "$*" >> "$TMUX_LEGACY_CALLS"+case "$1" in+ list-panes) printf '${panes}' ;;+esac+`)+ chmodSync(tmux, 0o700)+ process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`+ process.env.TMUX_LEGACY_CALLS = calls+ return calls+}++describe('isLegacyHarnessSession', () => {+ it('recognises only the pre-prefix `<engine>-<ms>` label', () => {+ expect(isLegacyHarnessSession('claude-1787912296587')).toBe(true)+ expect(isLegacyHarnessSession('codex-1787549944131')).toBe(true)+ expect(isLegacyHarnessSession('harness-claude-1787912296587')).toBe(false)+ expect(isLegacyHarnessSession('work')).toBe(false)+ expect(isLegacyHarnessSession('claude-notes')).toBe(false)+ expect(isLegacyHarnessSession('claude-42')).toBe(false)+ })+})++describe('adoptLegacyHarnessSessions', () => {+ it('renames the registry\'s own pre-prefix sessions and nothing else', async () => {+ // The inventory seen on machine-remote-1: two sessions from before the prefix that the registry+ // owns, one already named right, one user session (`work`) that ALSO holds a registered pane, and+ // one legacy-looking session nobody registered.+ const calls = fakeTmux([+ '%%13|40496|claude-1787912296587|/home/agent/abc',+ '%%1|368|codex-1787549944131|/home/agent/proj',+ '%%18|32943|harness-codex-1789028699411|/home/agent/abc',+ '%%0|40087|work|/home/agent/proj',+ '%%7|700|claude-1787000000000|/tmp',+ ].join('\\n') + '\\n')+ const owned = new Map([['%13', 'claude'], ['%1', 'codex'], ['%18', 'codex'], ['%0', 'codex']])++ const adopted = await adoptLegacyHarnessSessions(owned, 1_800_000_000_000)++ expect(adopted).toEqual([+ { from: 'claude-1787912296587', to: 'harness-claude-1800000000000', paneId: '%13' },+ { from: 'codex-1787549944131', to: 'harness-codex-1800000000001', paneId: '%1' },+ ])+ expect(readFileSync(calls, 'utf8').trim().split('\n')).toEqual([+ 'list-panes -a -F #{pane_id}|#{pane_pid}|#{session_name}|#{pane_current_path}',+ 'rename-session -t =claude-1787912296587 harness-claude-1800000000000',+ 'rename-session -t =codex-1787549944131 harness-codex-1800000000001',+ ])+ })++ it('renames a session once even when several of its panes are registered', async () => {+ const calls = fakeTmux('%%2|20|claude-1787912296587|/a\\n%%3|30|claude-1787912296587|/b\\n')+ const adopted = await adoptLegacyHarnessSessions(new Map([['%2', 'claude'], ['%3', 'claude']]), 5)+ expect(adopted).toHaveLength(1)+ expect(readFileSync(calls, 'utf8').trim().split('\n').filter((call) => call.startsWith('rename-session'))).toHaveLength(1)+ })++ it('does not touch tmux at all when the registry owns no panes', async () => {+ const calls = fakeTmux('%%2|20|claude-1787912296587|/a\\n')+ await expect(adoptLegacyHarnessSessions(new Map())).resolves.toEqual([])+ expect(() => readFileSync(calls, 'utf8')).toThrow()+ })+})