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): preserve Codex startup diagnostics (#332)
lylye160a0a17304
diff --git a/server/src/__tests__/agents-computer-daemon-auth-hint.test.ts b/server/src/__tests__/agents-computer-daemon-auth-hint.test.tsindex 0c05cad..ede9c5a 100644--- a/server/src/__tests__/agents-computer-daemon-auth-hint.test.ts+++ b/server/src/__tests__/agents-computer-daemon-auth-hint.test.ts@@ -55,3 +55,11 @@ test('authFailureHint handles context overflow and poisoned body sentinels', ()assert.match(authFailureHint('qwen', 'lone surrogate split emoji poisoned'), /poisoned/)assert.match(authFailureHint('gemini', 'unrelated socket reset error'), /daemon terminal for details/)})++test('local startup failures get executable and sandbox guidance, not account advice', () => {+ const hint = authFailureHint('codex', 'process exited with code 1\nbwrap: execvp /home/quota/token/codex: No such file or directory')+ assert.match(hint, /executable path/)+ assert.match(hint, /sandbox/)+ assert.doesNotMatch(hint, /login|quota|unsandboxed|disable/i)+ assert.match(authFailureHint('codex', 'process terminated by SIGTERM'), /daemon terminal/)+})diff --git a/server/src/__tests__/agents-computer-engine-failure.test.ts b/server/src/__tests__/agents-computer-engine-failure.test.tsindex 4616c40..d7c4eda 100644--- a/server/src/__tests__/agents-computer-engine-failure.test.ts+++ b/server/src/__tests__/agents-computer-engine-failure.test.ts@@ -1,7 +1,7 @@import { test } from 'node:test'import assert from 'node:assert/strict'-import { classifyEngineFailure, engineDiagnosticText, engineFailureOf } from '../agents/computer/engine.js'+import { classifyEngineFailure, engineDiagnosticText, engineFailureOf, failurePreview } 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')@@ -17,6 +17,30 @@ test('a missing-session phrase is stale only when resume was attempted', () => {assert.equal(classifyEngineFailure('session not found', true), 'resume-not-found')})+test('local startup failures are distinct from provider and transport failures', () => {+ for (const diagnostic of [+ 'bwrap: execvp /opt/codex: No such file or directory',+ 'process terminated by SIGTERM\nbwrap: execvp /home/quota/token/codex: Permission denied',+ 'spawn /opt/codex ENOENT',+ 'spawn /opt/my tools/codex EACCES',+ ]) assert.equal(classifyEngineFailure(diagnostic), 'startup', diagnostic)++ assert.equal(classifyEngineFailure('No such file or directory: notes.txt'), 'unknown')+ assert.equal(classifyEngineFailure('process terminated by SIGTERM'), 'transport')+ assert.equal(classifyEngineFailure('connection timed out'), 'transport')+})++test('one-shot startup diagnostics survive the shorter operator notice', () => {+ const error = failurePreview({+ exitCode: 1,+ signalName: null,+ stderr: ['checking quota configuration\n'.repeat(100), 'bwrap: execvp /opt/codex: No such file or directory'],+ stdout: [],+ }).slice(0, 900)+ assert.match(error, /bwrap: execvp.*No such file or directory/)+ assert.equal(classifyEngineFailure(error), 'startup')+})+test('diagnostic extraction keeps engine errors but drops successful model prose', () => {const diagnostic = engineDiagnosticText(['{"type":"assistant","session_id":"abc","message":{"content":"session not found"}}',diff --git a/server/src/__tests__/agents-computer-engine.test.ts b/server/src/__tests__/agents-computer-engine.test.tsindex 0c2eb35..20d0825 100644--- a/server/src/__tests__/agents-computer-engine.test.ts+++ b/server/src/__tests__/agents-computer-engine.test.ts@@ -4,76 +4,24 @@* Run: node --import tsx --test server/src/__tests__/agents-computer-engine.test.ts*/import assert from 'node:assert/strict'-import { writeFileSync } from 'node:fs'import { chmod, lstat, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import { delimiter, dirname, join } from 'node:path'-import { afterEach, beforeEach, test } from 'node:test'+import { afterEach, test } from 'node:test'import { setTimeout as delay } from 'node:timers/promises'-import { claudeSecureFlags, type EngineHopReport, type EngineRunResult, getAdapter, headlessSpawnOptions, resolveSpawn, runnableEngineIds, secureEngineCapabilityReason } from '../agents/computer/engine.js'+import { type EngineHopReport, type EngineRunResult, getAdapter, headlessSpawnOptions, resolveSpawn, runnableEngineIds, secureEngineCapabilityReason } from '../agents/computer/engine.js'import { type ProviderProfile, providerProfileEnv } from '../agents/computer/provider-profiles.js'import { CLAUDE_CORE_ENV_KEYS, CLAUDE_TURN_ENV_KEYS } from '../agents/computer/claude-user-settings.js'const IS_WIN = process.platform === 'win32'-const original = { ...process.env }+const ORIGINAL_PATH = process.env.PATH+const ORIGINAL_PATHEXT = process.env.PATHEXT+const ORIGINAL_UNSANDBOXED = process.env.CUMORA_BYOA_ALLOW_UNSANDBOXEDconst tempDirs: string[] = []// Sessions spawn a child process. Track them so a FAILING assertion still tears// the child down — otherwise it outlives the test and the runner never exits.const liveSessions: Array<{ stop(): void | Promise<void> }> = []-test('Claude preserves an explicit model override and reloads changed providers after the active turn', async () => {- const root = await mkdtemp(join(tmpdir(), 'cumora-claude-provider-refresh-'))- tempDirs.push(root)- const binDir = join(root, 'bin')- const home = join(root, 'home')- const configDir = join(root, 'config')- await Promise.all([mkdir(binDir), mkdir(home), mkdir(configDir)])- const file = join(configDir, 'settings.json')- const saved = (endpoint: string) => JSON.stringify({- model: 'auto/local[1m]', env: { ANTHROPIC_BASE_URL: endpoint },- })- await writeFile(file, saved('https://first.example.test'))- await writeFakeCli(binDir, 'claude', `-if (process.argv.includes('--input-format')) {- process.stdin.on('data', () => process.stdout.write(JSON.stringify({- type: 'result', subtype: 'success', session_id: 'retained-thread', result: 'OK'- }) + '\\n'))-} else {- process.stdout.write(JSON.stringify({ argv: process.argv.slice(2) }) + '\\n')-}-`)- setFakeCliPath(binDir)- const env = secureClaudeEnv(root, { CLAUDE_CONFIG_DIR: configDir, ANTHROPIC_MODEL: 'explicit/main' })- const adapter = getAdapter('claude')- const probe = await adapter.probe({ cwd: home, env, tier: 'big', signal: AbortSignal.timeout(10_000) })- const argv = JSON.parse(probe.text).argv as string[]- assert.equal(argv[argv.indexOf('--model') + 1], 'explicit/main')- const session = adapter.startSession!({ home, env, onLog() {} })!- assert.ok(session)- liveSessions.push(session)- const turn = session.send('finish this turn')- writeFileSync(file, saved('https://second.example.test'))- assert.equal(session.alive, true)- assert.equal((await turn).exitCode, 0)- assert.equal(session.alive, false)- assert.equal(session.sessionId, 'retained-thread')-})--test('temporarily unreadable Claude provider settings cannot fall through to a different account', async () => {- const root = await mkdtemp(join(tmpdir(), 'cumora-claude-partial-settings-'))- tempDirs.push(root)- const configDir = join(root, 'config')- const binDir = join(root, 'bin')- await Promise.all([mkdir(configDir), mkdir(binDir)])- await writeFile(join(configDir, 'settings.json'), '{partial gateway update')- await writeFakeCli(binDir, 'claude', "process.stderr.write('fixture must not be invoked')")- setFakeCliPath(binDir)- await assert.rejects(getAdapter('claude').classify({- cwd: root, env: secureClaudeEnv(root, { CLAUDE_CONFIG_DIR: configDir }),- prompt: 'triage', signal: AbortSignal.timeout(10_000),- }), /Cannot read Claude provider settings/)-})-function secureClaudeEnv(root: string, overrides: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv {const base: NodeJS.ProcessEnv = { ...process.env }// withClaudeUserSettingsEnv only imports a key from settings.json when the@@ -107,7 +55,7 @@ async function writeFakeCli(binDir: string, name: string, source: string): Promiawait chmod(launcher, 0o755)}-function setFakeCliPath(binDir: string): void {+function useFakeCliPath(binDir: string): void {process.env.PATH = `${binDir}${delimiter}${process.env.PATH ?? ''}`}@@ -119,18 +67,14 @@ test('engine subprocesses always suppress Windows console windows', () => {})})-beforeEach(async () => {- const home = await mkdtemp(join(tmpdir(), 'cumora-engine-test-home-'))- tempDirs.push(home)- process.env.HOME = home- process.env.USERPROFILE = home- process.env.CODEX_HOME = join(home, 'personal-codex')-})-afterEach(async () => {for (const s of liveSessions.splice(0)) { try { await s.stop() } catch { /* already gone */ } }- for (const key of Object.keys(process.env)) if (!(key in original)) delete process.env[key]- Object.assign(process.env, original)+ if (ORIGINAL_PATH === undefined) delete process.env.PATH+ else process.env.PATH = ORIGINAL_PATH+ if (ORIGINAL_PATHEXT === undefined) delete process.env.PATHEXT+ else process.env.PATHEXT = ORIGINAL_PATHEXT+ if (ORIGINAL_UNSANDBOXED === undefined) delete process.env.CUMORA_BYOA_ALLOW_UNSANDBOXED+ else process.env.CUMORA_BYOA_ALLOW_UNSANDBOXED = ORIGINAL_UNSANDBOXEDawait Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })))})@@ -219,7 +163,7 @@ test('local engine failure returns stderr tail for observability', async () => {'claude',"process.stderr.write('Claude Code error: usage limit reached, no tokens left\\n')\nprocess.exit(1)\n",)- setFakeCliPath(binDir)+ useFakeCliPath(binDir)const logs: string[] = []const result = await getAdapter('claude').run({@@ -237,51 +181,7 @@ test('local engine failure returns stderr tail for observability', async () => {assert.deepEqual(logs, ['Claude Code error: usage limit reached, no tokens left'])})-test('Claude Bash remains sandboxed with private tools, network and credentials denied', () => {- const home = '/home/cumora-policy-agent'- const argv = claudeSecureFlags(home, {- PATH: dirname(process.execPath),- CLAUDE_CONFIG_DIR: join(home, 'missing-config'),- CUMORA_AGENT_MCP_SHIM: join(home, 'trusted', 'cumora-mcp'),- ANTHROPIC_API_KEY: 'fixture-provider-key',- GITHUB_TOKEN: 'fixture-github-token',- BASH_ENV: '/untrusted-shell-startup',- })- const tools = argv[argv.indexOf('--tools') + 1].split(',')- assert.ok(tools.includes('Bash'))- assert.ok(tools.includes('mcp__cumora__cli'))- const allowed = argv.slice(argv.indexOf('--allowedTools') + 1, argv.indexOf('--disallowedTools'))- assert.deepEqual(allowed,- [`Read(/${home}/**)`, `Edit(/${home}/**)`, 'Bash', 'mcp__cumora__cli'])- const disallowed = argv[argv.indexOf('--disallowedTools') + 1].split(',')- assert.equal(disallowed.includes('Bash'), false)- for (const tool of ['PowerShell', 'WebFetch', 'WebSearch']) {- assert.equal(tools.includes(tool), false)- assert.ok(disallowed.includes(tool))- }- assert.ok(argv.includes('--restricted'))- assert.equal(argv[argv.indexOf('--permission-mode') + 1], 'dontAsk')- assert.ok(argv.includes('--strict-mcp-config'))-- const { permissions, sandbox } = JSON.parse(argv[argv.indexOf('--settings') + 1])- assert.deepEqual(permissions.allow, allowed)- assert.ok(permissions.allow.includes('Bash'))- assert.equal(permissions.deny.includes('Bash'), false)- assert.ok(permissions.deny.includes(`Read(/${home}/bin/**)`))- assert.ok(permissions.deny.includes(`Edit(/${home}/bin/**)`))- assert.equal(sandbox.enabled, true)- assert.equal(sandbox.failIfUnavailable, true)- assert.equal(sandbox.allowUnsandboxedCommands, false)- assert.deepEqual(sandbox.excludedCommands, [])- assert.deepEqual(sandbox.network, { allowedDomains: [], strictAllowlist: true })- assert.ok(sandbox.filesystem.denyRead.includes('~/'))- assert.ok(sandbox.filesystem.allowRead.includes(home))- for (const name of ['ANTHROPIC_API_KEY', 'GITHUB_TOKEN', 'BASH_ENV']) {- assert.ok(sandbox.credentials.envVars.some((entry: { name: string; mode: string }) => entry.name === name && entry.mode === 'deny'))- }-})--async function checkClaudeSecureTransport(persistent: boolean): Promise<void> {+test('Claude secure mode is fail-closed and strips tool credentials', { skip: IS_WIN }, async () => {const root = await mkdtemp(join(tmpdir(), 'cumora-claude-secure-'))tempDirs.push(root)const binDir = join(root, 'bin')@@ -304,28 +204,21 @@ async function checkClaudeSecureTransport(persistent: boolean): Promise<void> {'claude',"process.stderr.write(JSON.stringify({ argv: process.argv.slice(2), scrub: process.env.CLAUDE_CODE_SUBPROCESS_ENV_SCRUB, coreEnv: { apiKey: process.env.ANTHROPIC_API_KEY, authToken: process.env.ANTHROPIC_AUTH_TOKEN, baseUrl: process.env.ANTHROPIC_BASE_URL, unrelated: process.env.UNRELATED_SECRET } }))\nprocess.exit(1)\n",)- setFakeCliPath(binDir)+ useFakeCliPath(binDir)const logs: string[] = []const mcpShim = join(root, 'trusted', 'cumora-mcp')- const args = {+ await getAdapter('claude').run({home,+ prompt: 'wake',env: secureClaudeEnv(root, {CLAUDE_CONFIG_DIR: configDir,ANTHROPIC_API_KEY: 'explicit-daemon-api-key',OPENAI_API_KEY: 'must-not-appear-in-settings',}),- onLog: (line: string) => logs.push(line),- }- if (persistent) {- const session = getAdapter('claude').startSession?.(args)- assert.ok(session)- liveSessions.push(session)- await session.send('wake')- await session.stop()- } else {- await getAdapter('claude').run({ ...args, prompt: 'wake', signal: new AbortController().signal })- }+ onLog: (line) => logs.push(line),+ signal: new AbortController().signal,+ })const captured = JSON.parse(logs[0] ?? '{}') as {argv?: string[]@@ -364,8 +257,6 @@ async function checkClaudeSecureTransport(persistent: boolean): Promise<void> {}assert.ok(settings.permissions?.allow?.includes(`Read(/${home}/**)`))assert.ok(settings.permissions?.allow?.includes(`Edit(/${home}/**)`))- assert.ok(settings.permissions?.allow?.includes('Bash'))- assert.equal(settings.permissions?.deny?.includes('Bash'), false)assert.ok(settings.permissions?.deny?.includes(`Read(/${home}/bin/**)`))assert.ok(settings.permissions?.deny?.includes(`Edit(/${home}/bin/**)`))assert.equal(settings.sandbox?.failIfUnavailable, true)@@ -378,12 +269,7 @@ async function checkClaudeSecureTransport(persistent: boolean): Promise<void> {}assert.doesNotMatch(settingsText, /must-not-appear-in-settings/)assert.doesNotMatch(settingsText, /settings-auth-token|explicit-daemon-api-key|provider\.example\.test/)-}--for (const persistent of [false, true]) {- test(`Claude secure ${persistent ? 'session' : 'one-shot'} preserves Bash and strips tool credentials`,- { skip: IS_WIN }, () => checkClaudeSecureTransport(persistent))-}+})test('Claude secure triage stays inside the custom provider model namespace', { skip: IS_WIN }, async () => {const root = await mkdtemp(join(tmpdir(), 'cumora-claude-provider-model-'))@@ -399,7 +285,7 @@ test('Claude secure triage stays inside the custom provider model namespace', {'claude',"process.stdout.write(JSON.stringify({ result: JSON.stringify({ argv: process.argv.slice(2) }) }))\n",)- setFakeCliPath(binDir)+ useFakeCliPath(binDir)const settingsPath = join(configDir, 'settings.json')await writeFile(settingsPath, JSON.stringify({@@ -461,7 +347,7 @@ if (argv.includes('--input-format')) {process.stdout.write(JSON.stringify({type:'result', subtype:'success', result:'OK'}) + '\\n')}`)- setFakeCliPath(binDir)+ useFakeCliPath(binDir)const preferences = {effortLevel: 'xhigh', modelSettings: { 'claude-opus-5': { effortLevel: 'medium' } },alwaysThinkingEnabled: true, language: 'Chinese',@@ -548,7 +434,7 @@ const reply = () => {if (argv.includes('--input-format')) require('node:readline').createInterface({ input: process.stdin }).on('line', reply)else { process.stdin.resume(); process.stdin.on('end', reply) }`)- setFakeCliPath(binDir)+ useFakeCliPath(binDir)for (const compatibility of [false, true]) {if (compatibility) process.env.CUMORA_BYOA_ALLOW_UNSANDBOXED = '1'else delete process.env.CUMORA_BYOA_ALLOW_UNSANDBOXED@@ -608,7 +494,7 @@ test('persistent Claude startup failure keeps stderr for first send', async () ='claude',"process.stderr.write('Claude Code error: subscription expired\\n')\nprocess.exit(1)\n",)- setFakeCliPath(binDir)+ useFakeCliPath(binDir)const logs: string[] = []const session = getAdapter('claude').startSession?.({@@ -648,7 +534,7 @@ test('persistent Claude classifies a rejected resume from its result event', asy'})\n' +'setInterval(() => {}, 1 << 30)\n',)- setFakeCliPath(binDir)+ useFakeCliPath(binDir)const session = getAdapter('claude').startSession?.({home,@@ -682,7 +568,7 @@ test('grok adapter seeds AGENTS.md and reports sessionId from stream-json', asyn'grok',`process.stdout.write(${JSON.stringify(`${grokEvents.map((event) => JSON.stringify(event)).join('\n')}\n`)})\n`,)- setFakeCliPath(binDir)+ useFakeCliPath(binDir)const adapter = getAdapter('grok')await adapter.seedHome(home, { id: 'iris', name: 'Iris', role: 'Designer', systemPrompt: null })@@ -736,7 +622,7 @@ test('resolveSpawn runs a native Windows executable without cmd.exe', { skip: !Iconst binDir = join(root, 'bin')await mkdir(binDir)await writeFile(join(binDir, 'codex.exe'), '', 'utf8')- process.env.PATH = `${binDir};${original.PATH ?? original.Path ?? ''}`+ process.env.PATH = `${binDir};${ORIGINAL_PATH ?? ''}`process.env.PATHEXT = '.EXE;.CMD;.BAT;.COM'const r = resolveSpawn('codex')@@ -772,7 +658,7 @@ test('Codex one-shot paths send prompts through stdin', async () => {await writeFile(launcher, '#!/bin/sh\nexec node "$(dirname "$0")/capture.js" "$@"\n', 'utf8')await chmod(launcher, 0o755)}- process.env.PATH = `${binDir}${delimiter}${original.PATH ?? original.Path ?? ''}`+ process.env.PATH = `${binDir}${delimiter}${ORIGINAL_PATH ?? ''}`const adapter = getAdapter('codex')const mcpShim = join(root, 'trusted', 'cumora-mcp')@@ -833,20 +719,6 @@ test('Codex one-shot paths send prompts through stdin', async () => {assert.equal(runCapture.argv?.some((arg) => arg.includes('dangerously')), false)assert.equal(runCapture.argv?.some((arg) => arg.includes('must-not-reach-tools')), false)assert.equal(runCapture.stdin, longPrompt)- assert.ok(runCapture.argv?.includes('service_tier="default"'))- for (const nativeFastMode of [true, false]) {- const speedLogs: string[] = []- await adapter.run({- home, prompt: 'wake', model: 'test-model', fastModel: 'auxiliary', nativeFastMode,- env: { ...process.env, CUMORA_AGENT_IPC_DIR: join(root, 'private-ipc'), CUMORA_AGENT_MCP_SHIM: mcpShim },- onLog: (line) => speedLogs.push(line), signal: new AbortController().signal,- })- const captured = JSON.parse(speedLogs.at(-1) ?? '{}') as { argv: string[] }- assert.ok(captured.argv.includes(`service_tier="${nativeFastMode ? 'fast' : 'default'}"`))- assert.equal(captured.argv.includes('features.fast_mode=true'), nativeFastMode)- assert.equal(captured.argv[captured.argv.indexOf('--model') + 1], 'test-model')- assert.ok(captured.argv.includes('--ignore-user-config'))- }const triagePrompt = 'triage prompt with spaces\nand a second line'const triage = await adapter.classify({@@ -863,7 +735,6 @@ test('Codex one-shot paths send prompts through stdin', async () => {assert.ok(triageCapture.argv?.includes('triage-model'))assert.equal(triageCapture.argv?.at(-1), '-')assert.equal(triageCapture.stdin, triagePrompt)- assert.ok(triageCapture.argv?.includes('service_tier="default"'))const probe = await adapter.probe({tier: 'big',@@ -876,7 +747,6 @@ test('Codex one-shot paths send prompts through stdin', async () => {assert.ok(probeCapture.argv?.includes('--ignore-user-config'))assert.equal(probeCapture.argv?.at(-1), '-')assert.equal(probeCapture.stdin, 'Connectivity check. Reply with exactly: OK')- assert.ok(probeCapture.argv?.includes('service_tier="default"'))})test('Claude and Codex one-shot adapters return structured engine failures', async () => {@@ -888,7 +758,7 @@ test('Claude and Codex one-shot adapters return structured engine failures', asyawait 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")- setFakeCliPath(binDir)+ useFakeCliPath(binDir)process.env.CUMORA_BYOA_ALLOW_UNSANDBOXED = '1'const signal = new AbortController().signal@@ -961,25 +831,128 @@ async function fakeCodexRejectingThread(root: string): Promise<string> {return binDir}-async function startFakeCodexSession(opts: { resume?: string } = {}) {+async function startFakeCodexSession(opts: { resume?: string; source?: string; onLog?: (line: string) => void } = {}) {process.env.CUMORA_BYOA_ALLOW_UNSANDBOXED = '1'const root = await mkdtemp(join(tmpdir(), 'cumora-codex-'))tempDirs.push(root)const home = join(root, 'home')await mkdir(home, { recursive: true })- const binDir = await fakeCodexRejectingThread(root)+ const binDir = join(root, 'bin')+ if (opts.source !== undefined) {+ await mkdir(binDir)+ await writeFakeCli(binDir, 'codex', opts.source)+ } else {+ await fakeCodexRejectingThread(root)+ }+ process.env.PATH = `${binDir}${delimiter}${process.env.PATH ?? ''}`const logs: string[] = []const session = getAdapter('codex').startSession!({home,- env: secureClaudeEnv(root, { PATH: `${binDir}:${process.env.PATH ?? ''}` }),+ env: secureClaudeEnv(root),resumeSessionId: opts.resume ?? null,- onLog: (l) => logs.push(l),+ onLog: (l) => { logs.push(l); opts.onLog?.(l) },})assert.ok(session, 'codex adapter must start a persistent session on this platform')liveSessions.push(session!)return { session: session!, logs }}+const BWRAP_STARTUP_ERROR = 'bwrap: execvp /missing/codex: No such file or directory'++for (const beforeSend of [true, false]) {+ test(`Codex preserves sandbox startup stderr when it exits ${beforeSend ? 'before' : 'after'} first send`, { skip: IS_WIN, timeout: 5000 }, async () => {+ let signalDeath!: () => void+ const died = new Promise<void>((resolve) => { signalDeath = resolve })+ const { session } = await startFakeCodexSession({+ source: `process.stderr.write('checking quota configuration\\n'.repeat(100) + ${JSON.stringify(`${BWRAP_STARTUP_ERROR}\n`)}, () => process.exit(1))`,+ onLog: (line) => { if (line.startsWith('[session] engine process died')) signalDeath() },+ })+ // The death notification proves the idle path ran; otherwise send is+ // queued synchronously before the process-close callback can run.+ if (beforeSend) await died+ const result = await session.send('wake')+ assert.notEqual(result.exitCode, 0)+ assert.match((result.error ?? '').slice(0, 900), /bwrap: execvp.*No such file or directory/)+ assert.match(result.failure?.diagnostic ?? '', /bwrap: execvp.*No such file or directory/)+ assert.equal(result.failure?.kind, 'startup')+ })+}++test('Codex excludes previous-turn stderr from a later process failure', { skip: IS_WIN, timeout: 5000 }, async () => {+ let signalFirstStderr!: () => void+ const firstStderr = new Promise<void>((resolve) => { signalFirstStderr = resolve })+ const { session } = await startFakeCodexSession({+ source: `+const send = (msg) => process.stdout.write(JSON.stringify(msg) + '\\n')+let turn = 0+require('node:readline').createInterface({ input: process.stdin }).on('line', (line) => {+ const msg = JSON.parse(line)+ if (msg.method === 'initialize') send({ id: msg.id, result: {} })+ if (msg.method === 'thread/start') send({ id: msg.id, result: { thread: { id: 'test-thread' } } })+ if (msg.method === 'turn/start') {+ if (++turn === 1) {+ process.stderr.write('quota exceeded first-turn-only diagnostic\\n', () => {+ send({ method: 'turn/completed', params: { turn: { status: 'completed' } } })+ })+ } else {+ process.stderr.write('second-turn-only diagnostic\\n', () => process.exit(1))+ }+ }+})`,+ onLog: (line) => { if (line === 'quota exceeded first-turn-only diagnostic') signalFirstStderr() },+ })+ // stdout/stderr are independent pipes: wait for both before the next send.+ const [first] = await Promise.all([session.send('first'), firstStderr])+ assert.equal(first.exitCode, 0)+ assert.equal(first.error, undefined)+ const second = await session.send('second')+ assert.match(second.error ?? '', /second-turn-only diagnostic/)+ assert.doesNotMatch(second.error ?? '', /quota|first-turn-only diagnostic/)+ assert.doesNotMatch(second.failure?.diagnostic ?? '', /quota|first-turn-only diagnostic/)+ assert.equal(second.failure?.kind, 'transport')+})++test('Codex does not classify an external SIGTERM as a sandbox startup failure', { skip: IS_WIN, timeout: 5000 }, async () => {+ let signalPid!: (pid: number) => void+ const started = new Promise<number>((resolve) => { signalPid = resolve })+ const { session } = await startFakeCodexSession({+ source: "process.stdout.write('fixture pid: ' + process.pid + '\\n')\nsetInterval(() => {}, 1 << 30)",+ onLog: (line) => { if (line.startsWith('fixture pid: ')) signalPid(Number(line.slice('fixture pid: '.length))) },+ })+ const pending = session.send('wake')+ process.kill(await started, 'SIGTERM')+ const result = await pending+ assert.match(result.error ?? '', /SIGTERM/)+ assert.equal(result.failure?.kind, 'transport')+})++test('Codex keeps process-failure diagnostics bounded', { skip: IS_WIN, timeout: 5000 }, async () => {+ const { session } = await startFakeCodexSession({+ source: "process.stderr.write('bounded stderr line\\n'.repeat(2000), () => process.exit(1))",+ })+ const result = await session.send('wake')+ assert.match(result.error ?? '', /bounded stderr line/)+ assert.ok((result.error?.length ?? 0) <= 4000)+ assert.ok((result.failure?.diagnostic.length ?? 0) <= 4000)+})++test('Codex does not report an unfinished turn as successful on process exit zero', { skip: IS_WIN, timeout: 5000 }, async () => {+ const { session } = await startFakeCodexSession({+ source: `+const send = (msg) => process.stdout.write(JSON.stringify(msg) + '\\n')+require('node:readline').createInterface({ input: process.stdin }).on('line', (line) => {+ const msg = JSON.parse(line)+ if (msg.method === 'initialize') send({ id: msg.id, result: {} })+ if (msg.method === 'thread/start') send({ id: msg.id, result: { thread: { id: 'test-thread' } } })+ if (msg.method === 'turn/start') process.exit(0)+})`,+ })+ const result = await session.send('unfinished')+ assert.notEqual(result.exitCode, 0)+ assert.ok(result.error)+ assert.ok(result.failure)+})+test('Codex Fast Mode reaches fresh, resumed and fallback threads without changing the model', { skip: IS_WIN }, async () => {const root = await mkdtemp(join(tmpdir(), 'cumora-codex-fast-'))tempDirs.push(root)@@ -1002,7 +975,7 @@ require('node:readline').createInterface({ input: process.stdin }).on('line', li}})`)- setFakeCliPath(binDir)+ useFakeCliPath(binDir)for (const nativeFastMode of [true, false]) {for (const resumeSessionId of [null, 'prior-thread', 'missing-thread']) {const logs: string[] = []@@ -1365,7 +1338,7 @@ test('a Grok ACP turn reports the model the engine announced', { skip: IS_WIN },assert.equal(result.model, 'grok-4.6', 'the turn must be priced on the real model, not left null')assert.equal(hops.length, 1)assert.equal(hops[0].model, 'grok-4.6', 'the ledger hop must name a real model, not the engine id')- assert.equal(hops[0].usage?.output_tokens, 4)+ assert.equal(hops[0]?.usage?.output_tokens, 4)})test('a Grok ACP turn still settles when no model is announced', { skip: IS_WIN }, async () => {@@ -1413,7 +1386,7 @@ if (argv.includes('--input-format')) {? capture() : JSON.stringify({type:'result', subtype:'success', result:'OK'})) + '\\n')}`)- setFakeCliPath(binDir)+ useFakeCliPath(binDir)const adapter = getAdapter('claude')const profiles: ProviderProfile[] = ['alpha', 'beta'].map((id, index) => ({id, label: id, baseUrl: `https://${id}.example.test`, model: `${id}/big`, fastModel: `${id}/small`,diff --git a/server/src/__tests__/agents-computer-turn-outcome.test.ts b/server/src/__tests__/agents-computer-turn-outcome.test.tsindex 5e3702e..c66d147 100644--- a/server/src/__tests__/agents-computer-turn-outcome.test.ts+++ b/server/src/__tests__/agents-computer-turn-outcome.test.ts@@ -66,6 +66,12 @@ test('an unexplained failure stays transient and keeps retrying', () => {}})+test('a sandbox startup failure does not become a provider throttle because of its path', () => {+ const error = 'process exited with code 1\nbwrap: execvp /home/quota/codex: No such file or directory'+ assert.equal(classifyTurnOutcome(error), 'transient')+ assert.equal(backoffUntilFor(classifyTurnOutcome(error), 1_000), null)+})+test('a throttle outranks an operator fix, exactly as the old chat path did', () => {// The old order was `!rateLimited && needsOperatorFix(...)`, so a message// matching both took the short cooldown and stayed out of the user's chat.diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.tsindex 4073709..ff6cdeb 100644--- a/server/src/agents/computer/daemon.ts+++ b/server/src/agents/computer/daemon.ts@@ -303,6 +303,9 @@ export type TurnOutcome =export function classifyTurnOutcome(engineError: string | null | undefined): TurnOutcome {if (!engineError) return 'ok'+ // Preserve normal retries for local startup failures, even when the path+ // happens to contain provider keywords such as "quota".+ if (classifyEngineFailure(engineDiagnosticProse(engineError)) === 'startup') return 'transient'if (isRateLimited(engineError)) return 'rate-limited'if (needsOperatorFix(engineError)) return 'operator-fix'return 'transient'@@ -819,6 +822,9 @@ export function isStaleResumeError(err: string): boolean {}export function authFailureHint(engine: EngineId, detail: string): string {+ if (classifyEngineFailure(engineDiagnosticProse(detail)) === 'startup') {+ return 'The local engine could not start. Check the executable path and sandbox configuration on that computer, then wake the agent again.'+ }if (CONTEXT_OVERFLOW_RE.test(detail)) {return 'The agent filled up its context window. Its session has been reset automatically — just wake the agent again and it will start fresh.'}diff --git a/server/src/agents/computer/engine.ts b/server/src/agents/computer/engine.tsindex f8f174e..cf95f72 100644--- a/server/src/agents/computer/engine.ts+++ b/server/src/agents/computer/engine.ts@@ -584,6 +584,7 @@ export interface EngineUsage {}export type EngineFailureKind =+ | 'startup'| 'resume-not-found'| 'context-overflow'| 'authentication'@@ -611,9 +612,16 @@ const RESUME_NOT_FOUND_RE = new RegExp([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/iconst ENGINE_RATE_LIMIT_RE = /rate.?limit|usage limit|quota|too many requests|overloaded|over capacity|credit balance is too low/iconst ENGINE_AUTH_RE = /not (?:logged in|authenticated|signed in)|(?<![\w./\\-])(?:sign|log)[ -]?in(?![\w/\\-]|\.\w)|\brun \/login(?![\w/\\-]|\.\w)|unauthori[sz]ed|forbidden|invalid (?:api )?key|authentication failed/i+const ENGINE_STARTUP_RE = /\bbwrap:\s*execvp\b|\bspawn(?: [^\n]+)? (?:ENOENT|EACCES)\b/iconst 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+function startupFailureLine(diagnostic: string): string | undefined {+ return diagnostic.split('\n').find((line) => ENGINE_STARTUP_RE.test(line))+}+export function classifyEngineFailure(diagnostic: string, hadResume = false): EngineFailureKind {+ // A local executable path can itself contain words such as "quota" or "token".+ if (ENGINE_STARTUP_RE.test(diagnostic)) return 'startup'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'@@ -1020,7 +1028,7 @@ export function failurePreview(args: {// salientError() already leads with this line, for exactly this reason, but// only the probe and handshake paths go through it — an ordinary turn lands// here instead. Lead with the cause and keep the full output behind it.- const rejected = argvRejection(detail)+ const rejected = startupFailureLine(detail) ?? argvRejection(detail)const body = rejected ? `${rejected}\n${detail}` : detailreturn `${prefix}\n${body}`.slice(0, MAX_FAILURE_CHARS)}@@ -2057,6 +2065,8 @@ class CodexSession implements EngineSession {* attach latency_ms to the hop report at turn/completed. */private turnStartedAt: number | null = nullprivate outBuf = ''+ private stderrTail = ''+ private hasSent = falseprivate threadId: string | nullprivate exited = falseprivate exitCode = 0@@ -2068,9 +2078,9 @@ class CodexSession implements EngineSession {// thread params WITHOUT threadId — reused to start a FRESH thread if a resume fails.private readonly baseThreadParams: Record<string, unknown>private ready = false- // Why the handshake died, when it did — so a send() landing after the teardown+ // Why the session died, when it did — so a send() landing after the teardown// reports the real cause instead of a generic "process gone".- private handshakeError: string | null = null+ private sessionError: string | null = nullprivate pending: { resolve: (r: EngineRunResult) => void } | null = nullprivate queuedPrompt: string | null = nullprivate activeTurnId: string | null = null@@ -2107,9 +2117,12 @@ class CodexSession implements EngineSession {: { method: 'thread/start', params }this.child = spawnEngineChild(bin, spawnArgs, { cwd: home, env, stdio: ['pipe', 'pipe', 'pipe'], shell: false })this.child.stdout?.on('data', (b: Buffer) => this.onStdout(b))- this.child.stderr?.on('data', (b: Buffer) => { for (const raw of b.toString('utf8').split('\n')) { const l = cleanLine(raw); if (l) this.onLog(l) } })+ this.child.stderr?.on('data', (b: Buffer) => {+ this.stderrTail = (this.stderrTail + b.toString('utf8')).slice(-MAX_FAILURE_CHARS)+ for (const raw of b.toString('utf8').split('\n')) { const l = cleanLine(raw); if (l) this.onLog(l) }+ })this.child.on('error', (err) => this.die(1, err.message))- this.child.on('close', (code, sig) => this.die(code ?? (sig ? 128 : 1), sig ? `terminated by ${sig}` : `exited with code ${code}`))+ this.child.on('close', (code, sig) => this.die(code ?? (sig ? 128 : 1), sig ? `process terminated by ${sig}` : `process exited with code ${code}`))// Begin the handshake once handlers are attached.queueMicrotask(() => { this.initializeId = this.req('initialize', { clientInfo: { name: 'cumora-daemon', version: '1.0.0' }, capabilities: { experimentalApi: true } }) })}@@ -2135,7 +2148,11 @@ class CodexSession implements EngineSession {send(prompt: string): Promise<EngineRunResult> {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))+ if (!this.alive) return Promise.resolve(classifyEngineResult({ exitCode: this.exitCode || 1, error: this.sessionError ?? 'engine session is not alive (process gone)', sessionId: this.threadId }, this.threadWasResume))+ // Only the first turn inherits output from process startup. Later turns+ // must not classify an old turn's stderr as their own failure.+ if (this.hasSent) this.stderrTail = ''+ this.hasSent = truereturn new Promise<EngineRunResult>((resolve) => {this.pending = { resolve }this.turnStart = { ...this.cum }@@ -2311,6 +2328,7 @@ class CodexSession implements EngineSession {private settle(error?: string): void {const p = this.pendingthis.pending = null+ this.stderrTail = ''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 {@@ -2327,12 +2345,18 @@ class CodexSession implements EngineSession {// use, protocol drift), so `alive` would keep advertising a usable session// and the daemon would reuse the zombie on every wake. Tear it down instead:// a !alive session is dropped and the next wake spawns a clean one.- if (!this.ready) { this.handshakeError = error; this.stop() }+ if (!this.ready) { this.sessionError = error; this.stop() }}private die(code: number, why: string): void {const alreadyDown = this.exitedthis.exited = true- this.exitCode = code+ // Exiting before turn/completed is a failed turn, even after a clean EOF.+ this.exitCode = code || 1+ const diagnostic = engineDiagnosticText(cleanLine(this.stderrTail))+ // The daemon displays only the first 900 characters. Keep the startup+ // cause ahead of noisy stderr so the notice retains both cause and kind.+ this.sessionError ??= [startupFailureLine(diagnostic), why, diagnostic]+ .filter(Boolean).join('\n').slice(0, MAX_FAILURE_CHARS)// Same idle-death visibility as ClaudeSession.die: a session dying with no// turn in flight must leave a trace, not silently vanish until the next wake.if (!alreadyDown) {@@ -2340,7 +2364,7 @@ class CodexSession implements EngineSession {}const p = this.pendingthis.pending = null- if (p) p.resolve(classifyEngineResult({ exitCode: code, error: why, sessionId: this.threadId }, this.threadWasResume))+ if (p) p.resolve(classifyEngineResult({ exitCode: this.exitCode, error: this.sessionError, sessionId: this.threadId }, this.threadWasResume))}}