Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
fix(byoa): isolate engine sessions and recover stale resumes (#231)
TianYia702da0396e3
diff --git a/server/src/__tests__/agents-computer-engine-failure.test.ts b/server/src/__tests__/agents-computer-engine-failure.test.tsnew file mode 100644index 0000000..4616c40--- /dev/null+++ b/server/src/__tests__/agents-computer-engine-failure.test.ts@@ -0,0 +1,40 @@+import { test } from 'node:test'+import assert from 'node:assert/strict'++import { classifyEngineFailure, engineDiagnosticText, engineFailureOf } from '../agents/computer/engine.js'++test('engine failures are classified into stable machine-readable kinds', () => {+ assert.equal(classifyEngineFailure('No conversation found with session ID: abc', true), 'resume-not-found')+ assert.equal(classifyEngineFailure('maximum context window exceeded'), 'context-overflow')+ assert.equal(classifyEngineFailure('429 Too Many Requests: rate limit reached'), 'rate-limit')+ assert.equal(classifyEngineFailure('Not logged in · Please run /login'), 'authentication')+ assert.equal(classifyEngineFailure('read ECONNRESET: socket hang up'), 'transport')+ assert.equal(classifyEngineFailure('the engine disliked something novel'), 'unknown')+})++test('a missing-session phrase is stale only when resume was attempted', () => {+ assert.equal(classifyEngineFailure('session not found', false), 'unknown')+ assert.equal(classifyEngineFailure('session not found', true), 'resume-not-found')+})++test('diagnostic extraction keeps engine errors but drops successful model prose', () => {+ const diagnostic = engineDiagnosticText([+ '{"type":"assistant","session_id":"abc","message":{"content":"session not found"}}',+ '{"type":"result","is_error":false,"result":"No conversation found"}',+ '{"type":"result","is_error":true,"result":"No conversation found with session ID: abc"}',+ '{"type":"error","error":{"message":"transport closed"}}',+ 'plain stderr detail',+ ].join('\n'))++ assert.match(diagnostic, /No conversation found with session ID/)+ assert.match(diagnostic, /transport closed/)+ assert.match(diagnostic, /plain stderr detail/)+ assert.doesNotMatch(diagnostic, /session_id/)+})++test('adapter classifications win and legacy error strings receive a fallback', () => {+ const explicit = { kind: 'authentication', message: 'sign in', diagnostic: 'raw sign in' } as const+ assert.equal(engineFailureOf({ exitCode: 1, error: 'other', failure: explicit }, true), explicit)+ assert.equal(engineFailureOf({ exitCode: 1, error: 'No conversation found with session ID: abc' }, true)?.kind, 'resume-not-found')+ assert.equal(engineFailureOf({ exitCode: 0 }, true), null)+})diff --git a/server/src/__tests__/agents-computer-engine-hot-switch.test.ts b/server/src/__tests__/agents-computer-engine-hot-switch.test.tsnew file mode 100644index 0000000..e73f871--- /dev/null+++ b/server/src/__tests__/agents-computer-engine-hot-switch.test.ts@@ -0,0 +1,63 @@+import assert from 'node:assert/strict'+import { mkdtemp, readFile, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import test from 'node:test'++import type { EngineId, EngineRunResult } from '../agents/computer/engine.js'+import { runWithSessionRecovery } from '../agents/computer/session-recovery.js'+import { EngineSessionStore } from '../agents/computer/session-store.js'++test('Claude to Codex to Claude never crosses session ownership and recovers a stale Claude session', async () => {+ const sessionsDir = await mkdtemp(join(tmpdir(), 'cumora-engine-hot-switch-'))+ const agentId = 'atlas-a745'+ const claude = new EngineSessionStore(sessionsDir, agentId, 'claude')+ const codex = new EngineSessionStore(sessionsDir, agentId, 'codex')+ const attempts: Array<{ engine: EngineId; resumeSessionId: string | null }> = []++ try {+ await claude.save('claude-session-old')++ // Claude becomes unavailable. The replacement Codex runner must see only+ // Codex-owned state and therefore starts a fresh thread.+ const codexResume = await codex.load()+ assert.equal(codexResume, null)+ const codexResult = await runWithSessionRecovery({+ resumeSessionId: codexResume,+ run: async (resumeSessionId): Promise<EngineRunResult> => {+ attempts.push({ engine: 'codex', resumeSessionId })+ return { exitCode: 0, sessionId: 'codex-session-new' }+ },+ reset: () => codex.save(null),+ })+ await codex.save(codexResult.sessionId ?? null)++ // When Claude returns, its runner restores the original Claude pointer,+ // never the Codex id. A stale target is cleared and this turn retries once.+ const claudeResume = await claude.load()+ assert.equal(claudeResume, 'claude-session-old')+ const claudeResult = await runWithSessionRecovery({+ resumeSessionId: claudeResume,+ run: async (resumeSessionId): Promise<EngineRunResult> => {+ attempts.push({ engine: 'claude', resumeSessionId })+ return resumeSessionId+ ? { exitCode: 1, error: `No conversation found with session ID: ${resumeSessionId}` }+ : { exitCode: 0, sessionId: 'claude-session-fresh' }+ },+ reset: () => claude.save(null),+ })+ await claude.save(claudeResult.sessionId ?? null)+ await Promise.all([claude.flush(), codex.flush()])++ assert.deepEqual(attempts, [+ { engine: 'codex', resumeSessionId: null },+ { engine: 'claude', resumeSessionId: 'claude-session-old' },+ { engine: 'claude', resumeSessionId: null },+ ])+ assert.equal(attempts.some(({ engine, resumeSessionId }) => engine === 'claude' && resumeSessionId === 'codex-session-new'), false)+ assert.equal(await readFile(claude.sessionFile, 'utf8'), 'claude-session-fresh\n')+ assert.equal(await readFile(codex.sessionFile, 'utf8'), 'codex-session-new\n')+ } finally {+ await rm(sessionsDir, { recursive: true, force: true })+ }+})diff --git a/server/src/__tests__/agents-computer-engine-inventory.test.ts b/server/src/__tests__/agents-computer-engine-inventory.test.tsindex 398eb14..4287f77 100644--- a/server/src/__tests__/agents-computer-engine-inventory.test.ts+++ b/server/src/__tests__/agents-computer-engine-inventory.test.ts@@ -5,6 +5,7 @@import { test } from 'node:test'import assert from 'node:assert/strict'import {+ EngineInventoryStabilizer,replaceEngineInventory,resolveAvailableEngine,shouldReportEngineSnapshot,@@ -40,3 +41,38 @@ test('a requested refresh reports an unchanged engine snapshot', () => {assert.equal(shouldReportEngineSnapshot(snapshot, snapshot), false)assert.equal(shouldReportEngineSnapshot(snapshot, snapshot, true), true)})++test('a transient version failure retains a previously runnable engine', () => {+ const stabilizer = new EngineInventoryStabilizer()+ const next = stabilizer.stabilize(['claude', 'codex'], ['claude', 'codex'], {+ runnable: ['codex'],+ blocked: [{ id: 'claude', reason: 'version temporarily unavailable', state: 'temporarily-unverifiable' }],+ })+ assert.deepEqual(next, ['claude', 'codex'])+})++test('confirmed incompatibility removes an engine immediately', () => {+ const stabilizer = new EngineInventoryStabilizer()+ const next = stabilizer.stabilize(['claude', 'codex'], ['claude', 'codex'], {+ runnable: ['codex'],+ blocked: [{ id: 'claude', reason: 'version below secure minimum', state: 'confirmed-incompatible' }],+ })+ assert.deepEqual(next, ['codex'])+})++test('an engine is removed only after three consecutive reliable PATH misses', () => {+ const stabilizer = new EngineInventoryStabilizer(3)+ const evaluated = { runnable: ['codex'] as const, blocked: [] }+ assert.deepEqual(stabilizer.stabilize(['claude', 'codex'], ['codex'], evaluated), ['claude', 'codex'])+ assert.deepEqual(stabilizer.stabilize(['claude', 'codex'], ['codex'], evaluated), ['claude', 'codex'])+ assert.deepEqual(stabilizer.stabilize(['claude', 'codex'], ['codex'], evaluated), ['codex'])+})++test('a successful detection resets the consecutive missing counter', () => {+ const stabilizer = new EngineInventoryStabilizer(3)+ const missing = { runnable: ['codex'] as const, blocked: [] }+ const healthy = { runnable: ['claude', 'codex'] as const, blocked: [] }+ assert.deepEqual(stabilizer.stabilize(['claude', 'codex'], ['codex'], missing), ['claude', 'codex'])+ assert.deepEqual(stabilizer.stabilize(['claude', 'codex'], ['claude', 'codex'], healthy), ['claude', 'codex'])+ assert.deepEqual(stabilizer.stabilize(['claude', 'codex'], ['codex'], missing), ['claude', 'codex'])+})diff --git a/server/src/__tests__/agents-computer-engine-version.test.ts b/server/src/__tests__/agents-computer-engine-version.test.tsindex ae9bade..7f91a4f 100644--- a/server/src/__tests__/agents-computer-engine-version.test.ts+++ b/server/src/__tests__/agents-computer-engine-version.test.ts@@ -10,7 +10,7 @@*/import assert from 'node:assert/strict'-import { mkdtemp, rm, writeFile } from 'node:fs/promises'+import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'import { test } from 'node:test'@@ -21,6 +21,7 @@ process.env.OPENAI_API_KEY ??= 'test-key'const {parseCliVersion, isCliOutdated, isCliVersionAtLeast, inferUpdateCommand,parseCursorAbout, parseGrokCheck, ENGINE_VERSION_SPECS, versionCommandInvocation,+ probeLocalEngineVersionWithRetry,} = await import('../agents/computer/cli-version.js')const { sanitizeDetectedEngines } = await import('../agents/computer/registry.js')@@ -53,6 +54,28 @@ test('Windows version probe replaces an extensionless npm shim with its runnable}})+test('an inconclusive local version probe retries and stops on the first concrete version', { skip: process.platform === 'win32' }, async () => {+ const root = await mkdtemp(join(tmpdir(), 'cumora-engine-version-retry-'))+ try {+ const counter = join(root, 'counter')+ const cli = join(root, 'claude')+ await writeFile(cli, [+ '#!/usr/bin/env node',+ "const fs = require('node:fs')",+ `const counter = ${JSON.stringify(counter)}`,+ "const n = Number(fs.existsSync(counter) ? fs.readFileSync(counter, 'utf8') : '0') + 1",+ "fs.writeFileSync(counter, String(n))",+ "if (n >= 3) process.stdout.write('claude 2.1.248\\n')",+ ].join('\n'))+ await chmod(cli, 0o755)++ assert.equal(await probeLocalEngineVersionWithRetry('claude', cli, [0, 1, 1]), '2.1.248')+ assert.equal(await readFile(counter, 'utf8'), '3')+ } finally {+ await rm(root, { recursive: true, force: true })+ }+})+test('isCliOutdated only fires when upstream is strictly newer', () => {assert.equal(isCliOutdated('1.2.3', '1.2.4'), true)assert.equal(isCliOutdated('1.2.3', '1.3.0'), true)diff --git a/server/src/__tests__/agents-computer-engine.test.ts b/server/src/__tests__/agents-computer-engine.test.tsindex a145278..f6c39ea 100644--- a/server/src/__tests__/agents-computer-engine.test.ts+++ b/server/src/__tests__/agents-computer-engine.test.ts@@ -447,6 +447,39 @@ test('persistent Claude startup failure keeps stderr for first send', async () =assert.match(logs[1] ?? '', /\[session\] engine process died .*exit 1/)})+test('persistent Claude classifies a rejected resume from its result event', async () => {+ const root = await mkdtemp(join(tmpdir(), 'cumora-claude-stale-resume-'))+ tempDirs.push(root)+ const binDir = join(root, 'bin')+ const home = join(root, 'home')+ await mkdir(binDir)+ await mkdir(home)+ await writeFakeCli(+ binDir,+ 'claude',+ "process.stdin.once('data', () => {\n" ++ " process.stdout.write(JSON.stringify({ type: 'result', subtype: 'error', is_error: true, session_id: 'claude-stale', result: 'No conversation found with session ID: claude-stale' }) + '\\n')\n" ++ '})\n' ++ 'setInterval(() => {}, 1 << 30)\n',+ )+ useFakeCliPath(binDir)++ const session = getAdapter('claude').startSession?.({+ home,+ env: secureClaudeEnv(root),+ model: null,+ fastModel: null,+ resumeSessionId: 'claude-stale',+ onLog: () => {},+ })+ assert.ok(session)+ liveSessions.push(session)++ const result = await session.send('wake')+ assert.equal(result.failure?.kind, 'resume-not-found')+ assert.match(result.failure?.diagnostic ?? '', /No conversation found/)+})+test('grok adapter seeds AGENTS.md and reports sessionId from stream-json', async () => {const root = await mkdtemp(join(tmpdir(), 'cumora-engine-grok-'))tempDirs.push(root)@@ -644,6 +677,46 @@ test('Codex one-shot paths send prompts through stdin', async () => {assert.equal(probeCapture.stdin, 'Connectivity check. Reply with exactly: OK')})+test('Claude and Codex one-shot adapters return structured engine failures', async () => {+ const root = await mkdtemp(join(tmpdir(), 'cumora-structured-engine-failures-'))+ tempDirs.push(root)+ const binDir = join(root, 'bin')+ const home = join(root, 'home')+ await mkdir(binDir)+ await mkdir(home)+ await writeFakeCli(binDir, 'claude', "process.stderr.write('No conversation found with session ID: claude-stale\\n')\nprocess.exit(1)\n")+ await writeFakeCli(binDir, 'codex', "process.stderr.write('429 Too Many Requests: rate limit reached\\n')\nprocess.exit(1)\n")+ useFakeCliPath(binDir)+ process.env.CUMORA_BYOA_ALLOW_UNSANDBOXED = '1'++ const signal = new AbortController().signal+ const claude = await getAdapter('claude').run({+ home,+ prompt: 'wake',+ env: secureClaudeEnv(root),+ model: null,+ fastModel: null,+ resumeSessionId: 'claude-stale',+ onLog: () => {},+ signal,+ })+ const codex = await getAdapter('codex').run({+ home,+ prompt: 'wake',+ env: secureClaudeEnv(root),+ model: null,+ fastModel: null,+ resumeSessionId: 'codex-existing',+ onLog: () => {},+ signal,+ })++ assert.equal(claude.failure?.kind, 'resume-not-found')+ assert.match(claude.failure?.diagnostic ?? '', /claude-stale/)+ assert.equal(codex.failure?.kind, 'rate-limit')+ assert.match(codex.failure?.diagnostic ?? '', /Too Many Requests/)+})+// ── Codex app-server handshake failures must kill the SESSION ────────────────// The handshake is one-shot: threadReq is consumed at the initialize ack, and// only a failed thread/resume re-issues a thread/start. So if the thread never@@ -711,6 +784,7 @@ test('a Codex session whose thread never opens dies instead of wedging', { skip:const first = await session.send('first wake')assert.notEqual(first.exitCode, 0, 'the rejected handshake must fail the turn')assert.match(String(first.error), /unsupported model for this account/)+ assert.equal(first.failure?.kind, 'unknown')// The session must NOT advertise itself as reusable: the daemon drops a// !alive session and spawns a clean one on the next wake.diff --git a/server/src/__tests__/agents-computer-session-recovery.test.ts b/server/src/__tests__/agents-computer-session-recovery.test.tsnew file mode 100644index 0000000..fa319f2--- /dev/null+++ b/server/src/__tests__/agents-computer-session-recovery.test.ts@@ -0,0 +1,71 @@+import { test } from 'node:test'+import assert from 'node:assert/strict'++import { runWithSessionRecovery } from '../agents/computer/session-recovery.js'++test('a missing resume target is cleared and retried fresh exactly once', async () => {+ const attempts: Array<string | null> = []+ let resets = 0+ const result = await runWithSessionRecovery({+ resumeSessionId: 'stale-id',+ run: async (resume) => {+ attempts.push(resume)+ return resume+ ? { exitCode: 1, error: 'No conversation found with session ID: stale-id' }+ : { exitCode: 0, sessionId: 'fresh-id' }+ },+ reset: async () => { resets += 1 },+ })++ assert.deepEqual(attempts, ['stale-id', null])+ assert.equal(resets, 1)+ assert.equal(result.sessionId, 'fresh-id')+})++test('a failed fresh retry is returned without a third attempt', async () => {+ const attempts: Array<string | null> = []+ const result = await runWithSessionRecovery({+ resumeSessionId: 'stale-id',+ run: async (resume) => {+ attempts.push(resume)+ return resume+ ? { exitCode: 1, error: 'session not found' }+ : { exitCode: 1, error: 'fresh start also failed' }+ },+ reset: async () => {},+ })++ assert.deepEqual(attempts, ['stale-id', null])+ assert.equal(result.failure?.kind, 'unknown')+})++test('ambiguous failures are never replayed', async () => {+ for (const error of [+ 'process exited with code 137',+ 'engine turn exceeded timeout',+ 'read ECONNRESET',+ 'unknown provider error',+ ]) {+ let attempts = 0+ let resets = 0+ const result = await runWithSessionRecovery({+ resumeSessionId: 'existing-id',+ run: async () => { attempts += 1; return { exitCode: 1, error } },+ reset: async () => { resets += 1 },+ })+ assert.equal(attempts, 1, error)+ assert.equal(resets, 0, error)+ assert.notEqual(result.failure?.kind, 'resume-not-found', error)+ }+})++test('a fresh turn never enters resume recovery', async () => {+ let attempts = 0+ const result = await runWithSessionRecovery({+ resumeSessionId: null,+ run: async () => { attempts += 1; return { exitCode: 1, error: 'session not found' } },+ reset: async () => assert.fail('fresh turn must not reset a session'),+ })+ assert.equal(attempts, 1)+ assert.equal(result.failure?.kind, 'unknown')+})diff --git a/server/src/__tests__/agents-computer-session-store.test.ts b/server/src/__tests__/agents-computer-session-store.test.tsnew file mode 100644index 0000000..590a8a5--- /dev/null+++ b/server/src/__tests__/agents-computer-session-store.test.ts@@ -0,0 +1,137 @@+import { afterEach, test } from 'node:test'+import assert from 'node:assert/strict'+import { mkdtemp, mkdir, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { EngineSessionStore, sessionIdPreview } from '../agents/computer/session-store.js'++const roots: string[] = []++async function temporaryRoot(): Promise<string> {+ const root = await mkdtemp(join(tmpdir(), 'cumora-session-store-'))+ roots.push(root)+ return root+}++afterEach(async () => {+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))+})++test('engine stores for one agent use independent paths and values', async () => {+ const root = await temporaryRoot()+ const claude = new EngineSessionStore(root, 'atlas-a745', 'claude')+ const codex = new EngineSessionStore(root, 'atlas-a745', 'codex')++ assert.equal(claude.sessionFile, join(root, 'atlas-a745', 'claude.session'))+ assert.equal(codex.sessionFile, join(root, 'atlas-a745', 'codex.session'))+ await claude.save('claude-session')+ assert.equal(await codex.load(), null)+ await codex.save('codex-session')++ assert.equal(await claude.load(), 'claude-session')+ assert.equal(await codex.load(), 'codex-session')+})++test('switching claude to codex and back preserves each engine session', async () => {+ const root = await temporaryRoot()+ await new EngineSessionStore(root, 'atlas-a745', 'claude').save('claude-before-fallback')+ await new EngineSessionStore(root, 'atlas-a745', 'codex').save('codex-during-fallback')++ assert.equal(await new EngineSessionStore(root, 'atlas-a745', 'claude').load(), 'claude-before-fallback')+})++test('clearing one engine does not remove another engine session', async () => {+ const root = await temporaryRoot()+ const claude = new EngineSessionStore(root, 'atlas-a745', 'claude')+ const codex = new EngineSessionStore(root, 'atlas-a745', 'codex')+ await Promise.all([claude.save('claude-id'), codex.save('codex-id')])+ await claude.save(null)++ assert.equal(await claude.load(), null)+ assert.equal(await codex.load(), 'codex-id')+})++test('missing and empty files load as no session, while whitespace is trimmed', async () => {+ const root = await temporaryRoot()+ const store = new EngineSessionStore(root, 'atlas-a745', 'claude')+ assert.equal(await store.load(), null)++ await mkdir(join(root, 'atlas-a745'), { recursive: true })+ await writeFile(store.sessionFile, '')+ assert.equal(await store.load(), null)+ await writeFile(store.sessionFile, ' session-with-newline \n')+ assert.equal(await store.load(), 'session-with-newline')+})++test('queued saves retain call order and flush observes the final value', async () => {+ const root = await temporaryRoot()+ const store = new EngineSessionStore(root, 'atlas-a745', 'claude')+ void store.save('old')+ void store.save(null)+ void store.save('new')+ await store.flush()++ assert.equal(await store.load(), 'new')+})++test('session files are private and contain one newline-terminated id', async () => {+ const root = await temporaryRoot()+ const store = new EngineSessionStore(root, 'atlas-a745', 'claude')+ await store.save('private-session')++ assert.equal(await readFile(store.sessionFile, 'utf8'), 'private-session\n')+ assert.equal((await stat(store.sessionFile)).mode & 0o777, 0o600)+})++test('a failed atomic replacement removes its temporary file', async () => {+ const root = await temporaryRoot()+ const store = new EngineSessionStore(root, 'atlas-a745', 'claude')+ await mkdir(store.sessionFile, { recursive: true }) // rename(file, directory) must fail+ await store.save('cannot-replace-directory')+ await store.flush()++ const entries = await readdir(join(root, 'atlas-a745'))+ assert.deepEqual(entries, ['claude.session'])+ assert.equal((await stat(store.sessionFile)).isDirectory(), true)+})++test('legacy session is quarantined without becoming an engine session', async () => {+ const root = await temporaryRoot()+ const legacy = join(root, 'atlas-a745.session')+ await writeFile(legacy, 'unknown-owner\n')+ const store = new EngineSessionStore(root, 'atlas-a745', 'claude')++ assert.equal(await store.quarantineLegacy(), true)+ assert.equal(await store.load(), null)+ const entries = await readdir(root)+ const quarantined = entries.find((entry) => entry.startsWith('atlas-a745.session.legacy-unscoped-'))+ assert.ok(quarantined)+ assert.equal(await readFile(join(root, quarantined), 'utf8'), 'unknown-owner\n')+ assert.equal(await store.quarantineLegacy(), false)+})++test('legacy quarantine leaves an existing engine-scoped session untouched', async () => {+ const root = await temporaryRoot()+ const store = new EngineSessionStore(root, 'atlas-a745', 'claude')+ await store.save('known-claude')+ await writeFile(join(root, 'atlas-a745.session'), 'unknown-owner')++ assert.equal(await store.quarantineLegacy(), true)+ assert.equal(await store.load(), 'known-claude')+})++test('a non-regular legacy path is ignored and never loaded', async () => {+ const root = await temporaryRoot()+ await mkdir(join(root, 'atlas-a745.session'))+ const store = new EngineSessionStore(root, 'atlas-a745', 'claude')++ assert.equal(await store.quarantineLegacy(), false)+ assert.equal(await store.load(), null)+})++test('session log previews never reveal the complete id', () => {+ const id = '01a06f71-1234-5678-9abc-def012345678'+ assert.equal(sessionIdPreview(id), '01a06f71')+ assert.doesNotMatch(sessionIdPreview(id), /1234/)+})diff --git a/server/src/agents/computer/cli-version.ts b/server/src/agents/computer/cli-version.tsindex 246ca94..81226c9 100644--- a/server/src/agents/computer/cli-version.ts+++ b/server/src/agents/computer/cli-version.ts@@ -400,3 +400,20 @@ export async function probeLocalEngineVersion(id: string, binPath: string | nullif (!spec || !binPath) return nullreturn versionFromOutput(await spawnCommand(binPath, spec.versionArgs, 6000))}++/** Retry only an inconclusive local version probe. A concrete version (whether+ * compatible or too old) is authoritative and returns immediately. Delays are+ * injectable so the retry contract can be tested without wall-clock sleeps. */+export async function probeLocalEngineVersionWithRetry(+ id: string,+ binPath: string | null,+ retryDelaysMs: readonly number[] = [0, 250, 1000],+): Promise<string | null> {+ if (!binPath) return null+ for (const delayMs of retryDelaysMs) {+ if (delayMs > 0) await new Promise<void>((resolve) => setTimeout(resolve, delayMs))+ const version = await probeLocalEngineVersion(id, binPath)+ if (version) return version+ }+ return null+}diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.tsindex edf780e..5bcb32f 100644--- a/server/src/agents/computer/daemon.ts+++ b/server/src/agents/computer/daemon.ts@@ -48,7 +48,9 @@ import {import { SKYPE_EMOTICONS_GUIDE } from '../skype-emoticons.js'import { finalizeTriage, isRateLimited, parseTriage } from '../triage-core.js'import { type ActionSurface, actionSurfaceFor, actionSurfaceText, calendarExampleText, postingMechanicsText } from './prompt-surface.js'-import { allowUnsandboxedByoa, detectEnginesWithStatus, ENGINE_IDS, type DetectedEngineSnapshot, type EngineHopReport, type EngineId, type EngineRunResult, type EngineSession, type EngineUsage, enrichDetectedEngines, evaluateRunnableEngines, getAdapter, runEngineDoctor, type RunnableEngineEvaluation, snapshotDetectedEngines } from './engine.js'+import { allowUnsandboxedByoa, detectEnginesWithStatus, ENGINE_IDS, engineFailureOf, type DetectedEngineSnapshot, type EngineHopReport, type EngineId, type EngineRunResult, type EngineSession, type EngineUsage, enrichDetectedEngines, evaluateRunnableEngines, getAdapter, runEngineDoctor, type RunnableEngineEvaluation, snapshotDetectedEngines } from './engine.js'+import { EngineSessionStore, sessionIdPreview } from './session-store.js'+import { runWithSessionRecovery } from './session-recovery.js'export { conversationHeader }@@ -82,7 +84,7 @@ export function createEngineRescanQueue(const CONFIG_DIR = join(homedir(), '.cumora')const CONFIG_PATH = join(CONFIG_DIR, 'computer.json')const AGENTS_ROOT = join(CONFIG_DIR, 'agents')-// Per-agent engine session id, persisted OUTSIDE the agent home (so the engine's+// Per-agent, per-engine session id, persisted OUTSIDE the agent home (so the engine's// own cwd can't clobber it). Survives a daemon restart so the next wake can// `--resume` the SAME engine session — recovering the in-turn context an// interrupted long task was building, instead of starting cold.@@ -922,6 +924,56 @@ export interface EngineInventory {current: EngineId[]}+/** Hysteresis for trustworthy scans. A previously runnable engine survives a+ * transient capability probe and two consecutive PATH misses. Confirmed+ * incompatibility removes it immediately because the security floor is not a+ * liveness signal and must never be debounced. */+export class EngineInventoryStabilizer {+ private readonly missingCounts = new Map<EngineId, number>()++ constructor(private readonly missingThreshold = 3) {}++ stabilize(+ previous: readonly EngineId[],+ installed: readonly EngineId[],+ evaluated: RunnableEngineEvaluation,+ ): EngineId[] {+ const installedSet = new Set(installed)+ const runnableSet = new Set(evaluated.runnable)+ const transientSet = new Set([+ ...evaluated.temporarilyUnverifiable ?? [],+ ...evaluated.blocked.filter((entry) => entry.state === 'temporarily-unverifiable').map((entry) => entry.id),+ ])+ const incompatibleSet = new Set(evaluated.blocked+ .filter((entry) => entry.state === 'confirmed-incompatible')+ .map((entry) => entry.id))+ const next: EngineId[] = []++ for (const id of previous) {+ if (incompatibleSet.has(id)) {+ this.missingCounts.delete(id)+ continue+ }+ if (installedSet.has(id)) {+ this.missingCounts.delete(id)+ if (runnableSet.has(id) || transientSet.has(id)) next.push(id)+ continue+ }+ const misses = (this.missingCounts.get(id) ?? 0) + 1+ this.missingCounts.set(id, misses)+ if (misses < this.missingThreshold) next.push(id)+ }++ for (const id of installed) {+ if (runnableSet.has(id)) {+ this.missingCounts.delete(id)+ if (!next.includes(id)) next.push(id)+ }+ }+ return next+ }+}+/** Replace the shared engine inventory after a trustworthy PATH scan. */export function replaceEngineInventory(inventory: EngineInventory, next: readonly EngineId[]): boolean {const current = inventory.current@@ -1401,7 +1453,7 @@ async function doPair(code: string, serverUrl: string, preferredEngine?: string)// engines list, which the server stores as available_engines[0] and uses as// the engine for the starter team and any agent assigned here without an// explicit override. (No separate column needed: "first = default".)- let engines = detected+ let engines = [...detected]if (preferredEngine) {if (!ENGINE_IDS.includes(preferredEngine as EngineId)) {throw new Error(`--engine must be one of: ${ENGINE_IDS.join(', ')} (got "${preferredEngine}")`)@@ -1581,7 +1633,8 @@ class AgentRunner {private binDir: stringprivate trustedCliDir: stringprivate ipcDir: string- private sessionFile: string+ private readonly engine: EngineId+ private readonly sessionStore: EngineSessionStoreprivate busy = falseprivate pendingRerun = false// Triage-trouble backoff: when the small-brain triage is rate-limited OR@@ -1664,6 +1717,7 @@ class AgentRunner {private readonly agent: AgentInfo,engine: EngineId,) {+ this.engine = enginethis.home = join(AGENTS_ROOT, agent.id)this.binDir = join(this.home, 'bin')// The fixed MCP server runs outside the model sandbox. Its source and the@@ -1673,7 +1727,7 @@ class AgentRunner {// granted only the two leaf request/response directories; Claude reaches// them through the fixed MCP bridge, not a model-controlled shell.this.ipcDir = join(CONFIG_DIR, '.runtime-cli-ipc', this.agent.id)- this.sessionFile = join(SESSIONS_DIR, `${agent.id}.session`)+ this.sessionStore = new EngineSessionStore(SESSIONS_DIR, agent.id, engine)this.adapter = getAdapter(engine)}@@ -1727,8 +1781,19 @@ class AgentRunner {* `--resume` the same session and recover the interrupted turn's context. */private setSessionId(id: string | null): void {if (id === this.sessionId) return+ const previous = this.sessionIdthis.sessionId = id- void this.persistSessionId()+ void this.sessionStore.save(id)+ if (id) console.log(`[computer] ${this.agent.id} saved ${this.engine} session ${sessionIdPreview(id)}`)+ else if (previous) console.log(`[computer] ${this.agent.id} cleared ${this.engine} session ${sessionIdPreview(previous)}`)+ }++ /** Defense in depth: the store and adapter are both fixed at construction.+ * Refuse resume if a future refactor ever lets those bindings diverge. */+ private resumeSessionId(): string | null {+ if (this.engine === this.adapter.id && this.sessionStore.engine === this.engine) return this.sessionId+ console.error(`[computer] ${this.agent.id} refused cross-engine resume: store=${this.sessionStore.engine}, runner=${this.engine}, adapter=${this.adapter.id}`)+ return null}/** True when an engine error means the session is unusable and the NEXT wake@@ -1780,25 +1845,79 @@ class AgentRunner {finally { if (this.activeEngineRun === run) this.activeEngineRun = null }}- private async persistSessionId(): Promise<void> {- try {- if (this.sessionId) {- await mkdir(SESSIONS_DIR, { recursive: true })- await writeFile(this.sessionFile, this.sessionId, 'utf8')- } else {- await rm(this.sessionFile, { force: true })+ /** Execute exactly one engine attempt. Session capture and the persistent to+ * one-shot transport fallback live here so chat and agenda cannot drift. */+ private async runEngineAttempt(delta: string, resumeSessionId: string | null): Promise<EngineRunResult> {+ const session = this.ensureEngineSession(resumeSessionId)+ const prompt = this.turnPrompt(session, delta)+ let result: EngineRunResult+ if (session) {+ const capture = setInterval(() => { if (session.sessionId) this.setSessionId(session.sessionId) }, 2000)+ capture.unref?.()+ try {+ result = await this.trackEngineRun(session.send(prompt))+ } finally {+ clearInterval(capture)+ }+ if (session.sessionId) this.setSessionId(session.sessionId)+ if (!session.alive) this.engineSession = null+ const persistentFailure = engineFailureOf(result, !!resumeSessionId)+ if (persistentFailure && !result.failure) result.failure = persistentFailure+ // A dead persistent transport that never reached the model is safe to+ // retry one-shot. Preserve the same resume target for continuity.+ if (result.error && !result.usage && !session.alive && persistentFailure?.kind !== 'resume-not-found') {+ this.persistentUnusable = true+ this.engineSession = null+ this.logEngineLine(`[engine] persistent session failed to produce a turn (${result.error.slice(0, 160)}) — falling back to one-shot for the rest of this process`)+ result = await this.trackEngineRun(this.adapter.run({+ home: this.home,+ prompt: this.turnPrompt(null, delta),+ env: this.engineEnv(),+ model: this.engineModel(),+ fastModel: this.engineFastModel(),+ resumeSessionId,+ onLog: (line) => this.logEngineLine(line),+ onHopUsage: (r) => this.onEngineHop(r, 'agent-turn'),+ signal: this.teardown.signal,+ }))}- } catch { /* best-effort — a lost session id just means a cold next wake */ }+ } else {+ result = await this.trackEngineRun(this.adapter.run({+ home: this.home,+ prompt,+ env: this.engineEnv(),+ model: this.engineModel(),+ fastModel: this.engineFastModel(),+ resumeSessionId,+ onLog: (line) => this.logEngineLine(line),+ onHopUsage: (r) => this.onEngineHop(r, 'agent-turn'),+ signal: this.teardown.signal,+ }))+ }+ if (result.sessionId) this.setSessionId(result.sessionId)+ return result+ }++ /** A missing resume target proves the model never began the requested turn,+ * so one fresh retry is safe. Every other failure returns immediately to+ * avoid duplicating tool side effects after an ambiguous crash or timeout. */+ private async runWithSessionRecovery(delta: string): Promise<EngineRunResult> {+ const resumeSessionId = this.resumeSessionId()+ return runWithSessionRecovery({+ resumeSessionId,+ run: (resume) => this.runEngineAttempt(delta, resume),+ reset: () => this.resetEngineSession(`${this.engine} resume target ${sessionIdPreview(resumeSessionId ?? '')} does not exist`),+ onFreshRetry: () => console.warn(`[computer] ${this.agent.id} retrying turn once with a fresh ${this.engine} session`),+ })}private async loadSessionId(): Promise<void> {- try {- const s = (await readFile(this.sessionFile, 'utf8')).trim()- if (s) {- this.sessionId = s- console.log(`[computer] ${this.agent.id} restored engine session ${s.slice(0, 8)} from disk — will --resume (continuity across restart)`)- }- } catch { /* no prior session on disk — start cold */ }+ await this.sessionStore.quarantineLegacy()+ const s = await this.sessionStore.load()+ if (s) {+ this.sessionId = s+ console.log(`[computer] ${this.agent.id} restored ${this.engine} session ${sessionIdPreview(s)} from disk — will --resume (continuity across restart)`)+ }}async start(): Promise<void> {@@ -1857,6 +1976,7 @@ class AgentRunner {session?.stop({ force: options.forceEngine }) ?? Promise.resolve(),this.activeEngineRun ?? Promise.resolve(),])+ await this.sessionStore.flush()}/** Does this runner's live config still match the latest server state? The@@ -1965,7 +2085,7 @@ class AgentRunner {* fallback, or custom args) — the caller then uses one-shot run(). If the* prior process has died it respawns, resuming this.sessionId so context* carries across the restart. */- private ensureEngineSession(): EngineSession | null {+ private ensureEngineSession(resumeSessionId = this.resumeSessionId()): EngineSession | null {if (!this.adapter.startSession) return nullif (this.persistentUnusable) return nullif (this.engineSession?.alive) return this.engineSession@@ -1974,7 +2094,7 @@ class AgentRunner {env: this.engineEnv(),model: this.engineModel(),fastModel: this.engineFastModel(),- resumeSessionId: this.sessionId,+ resumeSessionId,standingPrompt: this.standingPrompt(),onLog: (line) => this.logEngineLine(line),// Trajectory hook — every assistant hop (Claude) / turn-completed (Codex)@@ -2523,30 +2643,12 @@ class AgentRunner {this.memoryDigest(),runtimeGet<{ roster: string }>(this.cfg.serverUrl, '/roster', token).then((r) => r?.roster ?? '').catch(() => ''),])- const resumeSessionId = this.sessionId- const session = this.ensureEngineSession()- const prompt = this.turnPrompt(session, this.agendaDelta(ag.brief, memoryDigest, roster))- const engineRun = session- ? session.send(prompt)- : this.adapter.run({- home: this.home, prompt, env: this.engineEnv(),- model: this.engineModel(), fastModel: this.engineFastModel(),- resumeSessionId: this.sessionId, onLog: (line) => this.logEngineLine(line),- // Same trajectory hook as the persistent-session path so the- // one-shot fallback (or codex `exec` path) also lands hops in the- // universal ledger.- onHopUsage: (r) => this.onEngineHop(r, 'agent-turn'),- signal: this.teardown.signal,- })- const result = await this.trackEngineRun(engineRun)- if (session?.sessionId) this.setSessionId(session.sessionId)- if (session && !session.alive) this.engineSession = null- if (!session && result.sessionId) this.setSessionId(result.sessionId)+ const result = await this.runWithSessionRecovery(this.agendaDelta(ag.brief, memoryDigest, roster))exitCode = result.exitCodeturnUsage = result.usageturnModel = result.model- if (result.error) engineError = this.visibleEngineError(exitCode, result.error)- if (engineError && this.mustResetSession(engineError, !!resumeSessionId)) {+ if (result.error) engineError = this.visibleEngineError(exitCode, result.failure?.message ?? result.error)+ if (engineError && result.failure?.kind !== 'resume-not-found' && this.mustResetSession(engineError, false)) {await this.resetEngineSession(this.resetReason(engineError))}} catch (err) {@@ -2921,80 +3023,18 @@ class AgentRunner {runtimeGet<{ roster: string }>(this.cfg.serverUrl, '/roster', token).then((r) => r?.roster ?? '').catch(() => ''),])- const resumeSessionId = this.sessionId- let result: EngineRunResult- const session = this.ensureEngineSession()- // Standing scaffold rides the session's system-prompt file; send only the- // small per-turn delta when it does (else inline it — see turnPrompt).const delta = turnBackgroundBrief? this.manualBriefDelta(turnBackgroundBrief, memoryDigest, digest, roster): this.chatDelta(memoryDigest, triageNote, digest, roster)- const prompt = this.turnPrompt(session, delta)- if (session) {- // PERSISTENT path: feed this turn into the long-lived process — no cold- // start (the first turn paid it; turns 2..N reuse the booted process).- // Persist the session id EARLY (the engine reports it ~1-2s in) so an- // interrupt mid-turn — even on a brand-new session — still leaves a- // resumable id on disk, not just when the turn finishes.- const capture = setInterval(() => { if (session.sessionId) this.setSessionId(session.sessionId) }, 2000)- capture.unref?.()- try {- result = await this.trackEngineRun(session.send(prompt))- } finally {- clearInterval(capture)- }- if (session.sessionId) this.setSessionId(session.sessionId)- // Process died during/after the turn → drop it so the next wake respawns- // (with --resume this.sessionId to carry context across the restart).- if (!session.alive) this.engineSession = null- // A persistent process that dies without producing a turn is not a- // transient hiccup, it is this machine telling us the persistent- // transport does not work here. Retry THIS turn one-shot and stay- // there: the alternative is failing every wake forever, which is the- // shape the codex sandbox outage took.- // No usage means the model never ran — the process died in the- // transport, not mid-answer, so re-running the turn cannot duplicate- // work or double-charge.- if (result.error && !result.usage && !session.alive) {- this.persistentUnusable = true- this.engineSession = null- this.logEngineLine(`[engine] persistent session failed to produce a turn (${result.error.slice(0, 160)}) — falling back to one-shot for the rest of this process`)- result = await this.trackEngineRun(this.adapter.run({- home: this.home,- prompt: this.turnPrompt(null, delta),- env: this.engineEnv(),- model: this.engineModel(),- fastModel: this.engineFastModel(),- resumeSessionId,- onLog: (line) => this.logEngineLine(line),- onHopUsage: (r) => this.onEngineHop(r, 'agent-turn'),- signal: this.teardown.signal,- }))- if (result.sessionId) this.setSessionId(result.sessionId)- }- } else {- // One-shot path: Cursor/OpenCode, Codex fallback, or a custom args override.- result = await this.trackEngineRun(this.adapter.run({- home: this.home,- prompt,- env: this.engineEnv(),- model: this.engineModel(),- fastModel: this.engineFastModel(),- resumeSessionId,- onLog: (line) => this.logEngineLine(line),- onHopUsage: (r) => this.onEngineHop(r, 'agent-turn'),- signal: this.teardown.signal,- }))- if (result.sessionId) this.setSessionId(result.sessionId)- }+ const result = await this.runWithSessionRecovery(delta)exitCode = result.exitCodeturnUsage = result.usageturnModel = result.model- if (result.error) engineError = this.visibleEngineError(exitCode, result.error)+ if (result.error) engineError = this.visibleEngineError(exitCode, result.failure?.message ?? result.error)// A stale resume OR a context-window overflow means this session can't// be carried forward — drop it AND tear down any persistent process so// the next wake starts clean (otherwise --resume re-overflows forever).- if (engineError && this.mustResetSession(engineError, !!resumeSessionId)) {+ if (engineError && result.failure?.kind !== 'resume-not-found' && this.mustResetSession(engineError, false)) {await this.resetEngineSession(this.resetReason(engineError))}} catch (err) {@@ -3242,7 +3282,7 @@ async function doRun(serverOverride?: string): Promise<void> {if (serverOverride) cfg.serverUrl = serverOverridelet initialEngines: EngineId[]try {- initialEngines = (await requireLocalEngine()).runnable+ initialEngines = [...(await requireLocalEngine()).runnable]} catch (err) {console.error(`[computer] ${err instanceof Error ? err.message : String(err)}`)process.exitCode = 70@@ -3263,6 +3303,7 @@ async function doRun(serverOverride?: string): Promise<void> {}const runners = new Map<string, AgentRunner>()+ const engineInventoryStabilizer = new EngineInventoryStabilizer()const syncOnce = async (): Promise<void> => {let agents: AgentInfo[]@@ -3339,11 +3380,19 @@ async function doRun(serverOverride?: string): Promise<void> {const detected = await detectEnginesWithStatus()if (!detected.reliable) return // broken `which` / `where` — keep the last good listconst evaluated = await evaluateRunnableEngines(detected.engines)- const next = evaluated.runnable- const capabilityWarning = evaluated.blocked.map(({ id, reason }) => `${id} (${reason})`).join('; ')+ const next = engineInventoryStabilizer.stabilize(engineInventory.current, detected.engines, evaluated)+ const blocked = evaluated.blocked.filter(({ id }) => !next.includes(id))+ const retainedTransient = [...new Set([+ ...evaluated.temporarilyUnverifiable ?? [],+ ...evaluated.blocked.filter(({ id, state }) => state === 'temporarily-unverifiable' && next.includes(id)).map(({ id }) => id),+ ])]+ const capabilityWarning = [+ ...blocked.map(({ id, reason }) => `${id} (${reason})`),+ ...retainedTransient.map((id) => `${id} (version temporarily unverifiable; retaining last-known-good availability)`),+ ].join('; ')if (capabilityWarning !== lastCapabilityWarning) {lastCapabilityWarning = capabilityWarning- if (capabilityWarning) console.warn(`[computer] secure engine(s) disabled: ${capabilityWarning}`)+ if (capabilityWarning) console.warn(`[computer] secure engine capability update: ${capabilityWarning}`)}const previous = engineInventory.currentconst changed = replaceEngineInventory(engineInventory, next)@@ -3362,12 +3411,12 @@ async function doRun(serverOverride?: string): Promise<void> {// at — so an engine could disappear from the card with no explanation// anywhere they could see. They stay OUT of `next`: that list becomes// available_engines and picks an agent's adapter.- const blockedIds = evaluated.blocked.map(({ id }) => id)+ const blockedIds = blocked.map(({ id }) => id)// One enrich over the whole list: it maps entry-by-entry, so splitting it// bought nothing and only risked the two halves drifting apart.const snapshot = await enrichDetectedEngines([...await snapshotDetectedEngines(next),- ...await blockedSnapshotRows(evaluated.blocked),+ ...await blockedSnapshotRows(blocked),], forceReport)// Report on version drift too, not just install/uninstall — upgrading an// engine in place leaves the engine *list* identical, and that is exactlydiff --git a/server/src/agents/computer/engine.ts b/server/src/agents/computer/engine.tsindex 8db0704..f5c4564 100644--- a/server/src/agents/computer/engine.ts+++ b/server/src/agents/computer/engine.ts@@ -24,14 +24,14 @@*/import { type ChildProcess, execFile, execFileSync, spawn as nodeSpawn, type SpawnOptions } from 'node:child_process'import { randomUUID } from 'node:crypto'-import { existsSync, renameSync, rmSync, writeFileSync } from 'node:fs'+import { existsSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'import { access, lstat, mkdir, mkdtemp, rename, rm, writeFile } from 'node:fs/promises'import { homedir, tmpdir } from 'node:os'import { basename, dirname, join, delimiter as PATH_DELIMITER } from 'node:path'import { StringDecoder } from 'node:string_decoder'import { stripLoneSurrogates } from '../text-safety.js'import { isCustomAnthropicEndpoint, readClaudeUserSettings, withClaudeUserSettingsEnv } from './claude-user-settings.js'-import { isCliVersionAtLeast, probeEngineVersion, probeLocalEngineVersion } from './cli-version.js'+import { isCliVersionAtLeast, probeEngineVersion, probeLocalEngineVersionWithRetry } from './cli-version.js'import { discoverEngineModelCatalog, type EngineModelCatalog } from './model-catalog.js'const IS_WIN = process.platform === 'win32'@@ -386,8 +386,41 @@ export function runnableEngineIds(}export interface RunnableEngineEvaluation {- runnable: EngineId[]- blocked: Array<{ id: EngineId; reason: string }>+ /** Evaluation consumers only inspect this inventory; accepting readonly+ * arrays also keeps literal test fixtures and immutable snapshots type-safe. */+ runnable: readonly EngineId[]+ blocked: Array<{+ id: EngineId+ reason: string+ state?: 'confirmed-incompatible' | 'temporarily-unverifiable'+ }>+ /** Engines kept runnable from a last-known-good verification while their+ * current version command was temporarily inconclusive. */+ temporarilyUnverifiable?: EngineId[]+}++interface VerifiedEngineVersion {+ fingerprint: string+ minimum: string+ version: string+}++const verifiedEngineVersions = new Map<EngineId, VerifiedEngineVersion>()++/** Test seam and cache invalidation hook for a changed security policy. */+export function clearVerifiedEngineVersions(): void {+ verifiedEngineVersions.clear()+}++function engineBinaryFingerprint(path: string | null): string | null {+ if (!path) return null+ try {+ const real = realpathSync(path)+ const info = statSync(real)+ return `${real}:${info.dev}:${info.ino}:${info.size}:${info.mtimeMs}`+ } catch {+ return null+ }}export function secureEngineCapabilityReason(@@ -421,22 +454,41 @@ export async function evaluateRunnableEngines(if (allowUnsandboxedByoa(env)) return { runnable: candidates, blocked: [] }const snapshot = await snapshotDetectedEngines(candidates)- const versions = new Map<EngineId, string | null>(await Promise.all(snapshot.map(async (entry) => [- entry.id,- await probeLocalEngineVersion(entry.id, entry.path),- ] as const)))+ const probes = new Map(await Promise.all(snapshot.map(async (entry) => {+ const minimum = SECURE_ENGINE_MIN_VERSIONS[entry.id] ?? ''+ const fingerprint = engineBinaryFingerprint(entry.path)+ const probed = await probeLocalEngineVersionWithRetry(entry.id, entry.path)+ if (probed && fingerprint && minimum) {+ verifiedEngineVersions.set(entry.id, { fingerprint, minimum, version: probed })+ }+ const cached = verifiedEngineVersions.get(entry.id)+ const cachedVersion = !probed && fingerprint && cached?.fingerprint === fingerprint && cached.minimum === minimum+ ? cached.version+ : null+ return [entry.id, { version: probed ?? cachedVersion, temporarilyUnverifiable: !probed }] as const+ })))const linuxSandboxDeps = platform === 'linux'? { bwrap: await binOnPath('bwrap'), socat: await binOnPath('socat') }: { bwrap: true, socat: true }const runnable: EngineId[] = []const blocked: RunnableEngineEvaluation['blocked'] = []+ const temporarilyUnverifiable: EngineId[] = []for (const id of candidates) {- const version = versions.get(id) ?? null+ const probe = probes.get(id)+ const version = probe?.version ?? nullconst reason = secureEngineCapabilityReason(id, version, platform, linuxSandboxDeps)- if (reason) { blocked.push({ id, reason }); continue }+ if (reason) {+ blocked.push({+ id,+ reason,+ state: version ? 'confirmed-incompatible' : 'temporarily-unverifiable',+ })+ continue+ }runnable.push(id)+ if (probe?.temporarilyUnverifiable) temporarilyUnverifiable.push(id)}- return { runnable, blocked }+ return { runnable, blocked, temporarilyUnverifiable }}export interface EnginePersona {@@ -487,9 +539,92 @@ export interface EngineUsage {cache_creation_input_tokens?: number}+export type EngineFailureKind =+ | 'resume-not-found'+ | 'context-overflow'+ | 'authentication'+ | 'rate-limit'+ | 'transport'+ | 'unknown'++/** Machine-readable failure alongside the existing operator-facing error.+ * `diagnostic` retains the bounded engine output used for classification;+ * callers must not display it without the daemon's normal redaction. */+export interface EngineFailure {+ kind: EngineFailureKind+ message: string+ diagnostic: string+}++const RESUME_NOT_FOUND_RE = new RegExp([+ String.raw`\bno (?:such )?(?:\w+ )?(?:conversation|session|thread)s?\b`,+ String.raw`\b(?:conversation|session|thread)s?(?: id)?\b[^\n]{0,24}?\b(?:not found|no longer exists?|do(?:es)? not exist|doesn't exist|has expired|is expired|is invalid|is unknown)\b`,+ String.raw`\b(?:invalid|unknown|expired|stale|malformed) (?:\w+ )?(?:conversation|session|thread)s?\b`,+ String.raw`\b(?:could ?n(?:o|')?t|cannot|can't|unable to|failed to)\b[^\n]{0,24}?\bresume\b`,+ String.raw`\bthread/resume failed\b`,+].join('|'), 'i')++const ENGINE_CONTEXT_OVERFLOW_RE = /context window|context length|context_length_exceeded|maximum context|reached its context|prompt is too long|input is too long|too many tokens/i+const ENGINE_RATE_LIMIT_RE = /rate.?limit|usage limit|quota|too many requests|overloaded|over capacity|credit balance is too low/i+const ENGINE_AUTH_RE = /not (?:logged in|authenticated|signed in)|(?:please )?(?:sign|log) ?in|unauthori[sz]ed|forbidden|invalid (?:api )?key|authentication failed/i+const ENGINE_TRANSPORT_RE = /ECONN(?:RESET|REFUSED)|EPIPE|socket hang up|network|connection (?:closed|lost|terminated|timed out)|transport|process (?:exited|terminated)|failed to (?:spawn|write)/i++export function classifyEngineFailure(diagnostic: string, hadResume = false): EngineFailureKind {+ if (hadResume && RESUME_NOT_FOUND_RE.test(diagnostic)) return 'resume-not-found'+ if (ENGINE_CONTEXT_OVERFLOW_RE.test(diagnostic)) return 'context-overflow'+ if (ENGINE_RATE_LIMIT_RE.test(diagnostic)) return 'rate-limit'+ if (ENGINE_AUTH_RE.test(diagnostic)) return 'authentication'+ if (ENGINE_TRANSPORT_RE.test(diagnostic)) return 'transport'+ return 'unknown'+}++/** Extract diagnostic prose without mistaking a model-authored stream event for+ * an engine error. Failed result/error fields are retained; ordinary JSON event+ * structure and successful assistant text are discarded. */+export function engineDiagnosticText(raw: string): string {+ const out: string[] = []+ for (const line of raw.split('\n')) {+ const trimmed = line.trim()+ if (!trimmed.startsWith('{')) { out.push(line); continue }+ let event: { is_error?: unknown; result?: unknown; error?: unknown }+ try { event = JSON.parse(trimmed) } catch { continue }+ if (event.is_error === true && typeof event.result === 'string') out.push(event.result)+ if (typeof event.error === 'string') out.push(event.error)+ else if (event.error && typeof event.error === 'object') {+ const message = (event.error as { message?: unknown }).message+ if (typeof message === 'string') out.push(message)+ }+ }+ return out.join('\n').trim().slice(0, MAX_FAILURE_CHARS)+}++/** Add a structured classification to adapters that still return the legacy+ * string field. Adapter-provided classifications win over the generic fallback. */+export function engineFailureOf(result: EngineRunResult, hadResume = false): EngineFailure | null {+ if (result.failure) return result.failure+ if (!result.error) return null+ return {+ kind: classifyEngineFailure(result.error, hadResume),+ message: result.error,+ diagnostic: result.error,+ }+}++/** Normalize a run at the adapter boundary. Keeping this next to the shared+ * classifier gives every adapter the same vocabulary while still allowing a+ * protocol-aware adapter to provide a more precise failure first. */+function classifyEngineResult(result: EngineRunResult, hadResume = false): EngineRunResult {+ const failure = engineFailureOf(result, hadResume)+ if (failure && !result.failure) result.failure = failure+ return result+}+export interface EngineRunResult {exitCode: number+ /** Concise operator-facing compatibility field. New control flow must use+ * `failure.kind`, never parse this presentation string. */error?: string+ failure?: EngineFailure/** The engine session id parsed from this run's stream-json output, to be* fed back as `resumeSessionId` on the next wake. Null if the engine emits* no session id (e.g. Codex, or a non-stream-json flag override). */@@ -1128,6 +1263,10 @@ class ClaudeSession implements EngineSession {private readonly child: ChildProcessprivate readonly onLog: (line: string) => voidprivate readonly onHopUsage?: (r: EngineHopReport) => void+ /** True only until the first result from a process started with --resume.+ * Later turns are ordinary continuation and must not treat session wording in+ * model/tool output as a failed resume handshake. */+ private resumePending: booleanprivate outBuf = ''private sid: string | nullprivate curModel: string | null = null@@ -1152,6 +1291,7 @@ class ClaudeSession implements EngineSession {constructor(bin: string, args: string[], opts: EngineSessionArgs, carriesStandingPrompt: boolean) {this.onLog = opts.onLogthis.onHopUsage = opts.onHopUsage+ this.resumePending = !!opts.resumeSessionIdthis.sid = opts.resumeSessionId ?? nullthis.carriesStandingPrompt = carriesStandingPrompt// Cross-platform spawn: on Windows resolve the real claude(.cmd) + shell so a@@ -1171,12 +1311,12 @@ class ClaudeSession implements EngineSession {send(prompt: string): Promise<EngineRunResult> {if (this.pending) {- return Promise.resolve({ exitCode: 1, error: 'engine session busy — a turn is already in flight', sessionId: this.sid })+ return Promise.resolve(classifyEngineResult({ exitCode: 1, error: 'engine session busy — a turn is already in flight', sessionId: this.sid }, this.resumePending))}if (!this.alive) {const exitCode = this.exitCode || 1const detail = failurePreview({ exitCode, signalName: null, stderr: this.stderrTail, stdout: this.stdoutTail })- return Promise.resolve({ exitCode, error: detail || 'engine session is not alive (process gone)', sessionId: this.sid })+ return Promise.resolve(classifyEngineResult({ exitCode, error: detail || 'engine session is not alive (process gone)', sessionId: this.sid }, this.resumePending))}return new Promise<EngineRunResult>((resolve) => {this.pending = { resolve, stderr: [], stdout: [] }@@ -1230,7 +1370,7 @@ class ClaudeSession implements EngineSession {if (this.pending) pushTail(this.pending.stdout, line)this.onLog(line)if (!line.startsWith('{')) continue- let ev: { type?: unknown; session_id?: unknown; is_error?: unknown; subtype?: unknown; status?: unknown; result?: unknown; usage?: EngineUsage; model?: unknown; message?: { model?: unknown; usage?: EngineUsage; content?: unknown } }+ let ev: { type?: unknown; session_id?: unknown; is_error?: unknown; subtype?: unknown; status?: unknown; result?: unknown; error?: unknown; usage?: EngineUsage; model?: unknown; message?: { model?: unknown; usage?: EngineUsage; content?: unknown } }try { ev = JSON.parse(line) } catch { continue }if (typeof ev.session_id === 'string' && ev.session_id) this.sid = ev.session_id// Capture the real model id (assistant events carry message.model) for pricing.@@ -1273,11 +1413,23 @@ class ClaudeSession implements EngineSession {this.hopIndex = 0 // reset the per-turn hop counterthis.steerQueue = [] // turn ending — any unflushed steer falls to the daemon's coalesced rerunconst isErr = ev.is_error === true+ const diagnostic = isErr+ ? engineDiagnosticText([+ ...(this.pending?.stderr ?? []),+ ...(this.pending?.stdout ?? []),+ ].join('\n'))+ : ''+ const message = diagnostic || `engine turn error${typeof ev.subtype === 'string' ? ` (${ev.subtype})` : ''}: see log`+ const wasResume = this.resumePending+ this.resumePending = falsethis.settle({exitCode: isErr ? 1 : 0,- error: isErr- ? `engine turn error${typeof ev.subtype === 'string' ? ` (${ev.subtype})` : ''}: ${typeof ev.result === 'string' ? ev.result.slice(0, MAX_FAILURE_CHARS) : 'see log'}`- : undefined,+ error: isErr ? message : undefined,+ failure: isErr ? {+ kind: classifyEngineFailure(diagnostic || message, wasResume),+ message,+ diagnostic: diagnostic || message,+ } : undefined,sessionId: this.sid,usage: ev.usage && typeof ev.usage === 'object' ? ev.usage : undefined,model: this.curModel,@@ -1306,7 +1458,7 @@ class ClaudeSession implements EngineSession {if (this.pendingTimer) { clearTimeout(this.pendingTimer); this.pendingTimer = null }const p = this.pendingthis.pending = null- if (p) p.resolve(r)+ if (p) p.resolve(classifyEngineResult(r, this.resumePending))}/** Process died (error/close). Mark dead and fail any in-flight turn. */@@ -1605,6 +1757,7 @@ class ClaudeAdapter implements EngineAdapter {// Agent turns can be substantial engineering/design work. Preserve the// operator's reasoning preferences; only triage/doctor force thinking off.return spawnEngine(command, argv, { ...args, env }, { shell, stdinText: wantsStdinPrompt ? args.prompt : undefined })+ .then((result) => classifyEngineResult(result, !!args.resumeSessionId))}startSession(args: EngineSessionArgs): EngineSession | null {@@ -1867,8 +2020,8 @@ class CodexSession implements EngineSession {get sessionId(): string | null { return this.threadId }send(prompt: string): Promise<EngineRunResult> {- if (this.pending) return Promise.resolve({ exitCode: 1, error: 'engine session busy — a turn is already in flight', sessionId: this.threadId })- if (!this.alive) return Promise.resolve({ exitCode: this.exitCode || 1, error: this.handshakeError ?? 'engine session is not alive (process gone)', sessionId: this.threadId })+ if (this.pending) return Promise.resolve(classifyEngineResult({ exitCode: 1, error: 'engine session busy — a turn is already in flight', sessionId: this.threadId }, this.threadWasResume))+ if (!this.alive) return Promise.resolve(classifyEngineResult({ exitCode: this.exitCode || 1, error: this.handshakeError ?? 'engine session is not alive (process gone)', sessionId: this.threadId }, this.threadWasResume))return new Promise<EngineRunResult>((resolve) => {this.pending = { resolve }this.turnStart = { ...this.cum }@@ -2016,6 +2169,7 @@ class CodexSession implements EngineSession {private onThreadReady(threadId: string): void {this.threadId = threadId+ this.threadWasResume = falsethis.ready = trueif (this.queuedPrompt && this.pending) { const p = this.queuedPrompt; this.queuedPrompt = null; this.startTurn(p) }}@@ -2043,7 +2197,7 @@ class CodexSession implements EngineSession {private settle(error?: string): void {const p = this.pendingthis.pending = null- if (p) p.resolve({ exitCode: error ? 1 : 0, error, sessionId: this.threadId, usage: this.turnUsage(), model: this.model })+ if (p) p.resolve(classifyEngineResult({ exitCode: error ? 1 : 0, error, sessionId: this.threadId, usage: this.turnUsage(), model: this.model }, this.threadWasResume))}private failPending(error: string): void {if (this.pending) this.settle(error)@@ -2072,7 +2226,7 @@ class CodexSession implements EngineSession {}const p = this.pendingthis.pending = null- if (p) p.resolve({ exitCode: code, error: why, sessionId: this.threadId })+ if (p) p.resolve(classifyEngineResult({ exitCode: code, error: why, sessionId: this.threadId }, this.threadWasResume))}}@@ -2237,7 +2391,9 @@ class CodexAdapter implements EngineAdapter {// A rejected -c override aborts codex before it reads the prompt, so the// turn fails with a config error that never mentions Cumora. Say it once.noteCodexConfigRejection(res.error, args.onLog)- return res+ // `codex exec` does not accept a thread id, so this one-shot fallback+ // always starts fresh even if the daemon currently owns a saved id.+ return classifyEngineResult(res, false)})}@@ -5168,7 +5324,7 @@ export interface DetectedEngineSnapshot {/** Snapshot the installed engines, optionally in a caller-supplied order* (pairing puts the chosen default first). Does not spawn the CLIs. */-export async function snapshotDetectedEngines(ids?: EngineId[]): Promise<DetectedEngineSnapshot[]> {+export async function snapshotDetectedEngines(ids?: readonly EngineId[]): Promise<DetectedEngineSnapshot[]> {const present = ids ?? await detectEngines()return Promise.all(present.map(async (id) => {const bin = ADAPTERS[id].bindiff --git a/server/src/agents/computer/session-recovery.ts b/server/src/agents/computer/session-recovery.tsnew file mode 100644index 0000000..564b347--- /dev/null+++ b/server/src/agents/computer/session-recovery.ts@@ -0,0 +1,25 @@+import { engineFailureOf, type EngineRunResult } from './engine.js'++export interface SessionRecoveryArgs {+ resumeSessionId: string | null+ run: (resumeSessionId: string | null) => Promise<EngineRunResult>+ reset: () => Promise<void>+ onFreshRetry?: () => void+}++/** Resume once, then retry exactly once without a session only when the engine+ * explicitly proves the target is missing. Ambiguous failures are never replayed+ * because the first attempt may already have produced external side effects. */+export async function runWithSessionRecovery(args: SessionRecoveryArgs): Promise<EngineRunResult> {+ const first = await args.run(args.resumeSessionId)+ const failure = engineFailureOf(first, !!args.resumeSessionId)+ if (failure && !first.failure) first.failure = failure+ if (!args.resumeSessionId || failure?.kind !== 'resume-not-found') return first++ await args.reset()+ args.onFreshRetry?.()+ const fresh = await args.run(null)+ const freshFailure = engineFailureOf(fresh, false)+ if (freshFailure && !fresh.failure) fresh.failure = freshFailure+ return fresh+}diff --git a/server/src/agents/computer/session-store.ts b/server/src/agents/computer/session-store.tsnew file mode 100644index 0000000..cfcfbdd--- /dev/null+++ b/server/src/agents/computer/session-store.ts@@ -0,0 +1,96 @@+import { randomUUID } from 'node:crypto'+import { lstat, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'+import { dirname, join } from 'node:path'++import type { EngineId } from './engine.js'++export function sessionIdPreview(sessionId: string): string {+ return sessionId.slice(0, 8)+}++/** Engine-owned pointer to the engine's real transcript/session storage.+ *+ * Cumora deliberately stores only the opaque id. The engine owns the actual+ * transcript and is the only component allowed to interpret the id. Binding a+ * store instance to one EngineId makes cross-engine resume impossible by+ * construction while retaining each engine's continuity across fallback.+ */+export class EngineSessionStore {+ readonly sessionFile: string+ readonly engine: EngineId++ private readonly legacyFile: string+ private writes: Promise<void> = Promise.resolve()++ constructor(+ sessionsDir: string,+ private readonly agentId: string,+ engine: EngineId,+ ) {+ this.engine = engine+ this.sessionFile = join(sessionsDir, agentId, `${engine}.session`)+ this.legacyFile = join(sessionsDir, `${agentId}.session`)+ }++ async load(): Promise<string | null> {+ try {+ return (await readFile(this.sessionFile, 'utf8')).trim() || null+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {+ console.warn(`[computer] ${this.agentId} could not load ${this.engine} session:`, err instanceof Error ? err.message : err)+ }+ return null+ }+ }++ /** Queue a snapshot of the requested value. Each operation absorbs its own+ * failure so a single filesystem error cannot poison all later saves. */+ save(sessionId: string | null): Promise<void> {+ const snapshot = sessionId+ this.writes = this.writes.then(async () => {+ try {+ if (snapshot) await this.atomicWrite(snapshot)+ else await rm(this.sessionFile, { force: true })+ } catch (err) {+ console.warn(`[computer] ${this.agentId} could not persist ${this.engine} session:`, err instanceof Error ? err.message : err)+ }+ })+ return this.writes+ }++ /** Move the old engine-agnostic pointer aside. Its ownership cannot be+ * established safely, so it must never be offered to any engine. */+ async quarantineLegacy(): Promise<boolean> {+ try {+ const info = await lstat(this.legacyFile)+ if (!info.isFile()) {+ console.warn(`[computer] ${this.agentId} ignored legacy unscoped session because it is not a regular file`)+ return false+ }+ const stamp = new Date().toISOString().replace(/[:.]/g, '-')+ const quarantined = `${this.legacyFile}.legacy-unscoped-${stamp}-${randomUUID()}`+ await rename(this.legacyFile, quarantined)+ console.warn(`[computer] ${this.agentId} quarantined legacy unscoped session — engine ownership cannot be verified; ${this.engine} will start fresh unless it has an engine-scoped session`)+ return true+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return false+ console.warn(`[computer] ${this.agentId} could not quarantine legacy unscoped session; it will be ignored:`, err instanceof Error ? err.message : err)+ return false+ }+ }++ async flush(): Promise<void> {+ await this.writes+ }++ private async atomicWrite(sessionId: string): Promise<void> {+ await mkdir(dirname(this.sessionFile), { recursive: true })+ const temporary = `${this.sessionFile}.${process.pid}.${randomUUID()}.tmp`+ try {+ await writeFile(temporary, `${sessionId}\n`, { encoding: 'utf8', mode: 0o600 })+ await rename(temporary, this.sessionFile)+ } finally {+ await rm(temporary, { force: true }).catch(() => {})+ }+ }+}