Skip to content

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 Codex state and preserve sessions and login (#327)

Streliziaae9e21e61d06
diff --git a/agent-cli/build.mjs b/agent-cli/build.mjs
index c094bfc..cd3e995 100644
--- a/agent-cli/build.mjs
+++ b/agent-cli/build.mjs
@@ -1,6 +1,5 @@
-// Bundle the BYOA daemon into a single standalone, dependency-free Node
-// executable for the public `cumora` npm package. The daemon only uses Node
-// builtins + global fetch, so the output needs nothing installed beyond Node.
+// Bundle the BYOA daemon and its pure-JS helpers into a standalone Node
+// executable. The output needs nothing installed beyond Node.
import { build } from 'esbuild'
import { existsSync, chmodSync, readFileSync } from 'node:fs'
import { resolve, dirname } from 'node:path'
diff --git a/agent-cli/package.json b/agent-cli/package.json
index 1b414b7..cf9cdb1 100644
--- a/agent-cli/package.json
+++ b/agent-cli/package.json
@@ -11,7 +11,7 @@
"dist"
],
"engines": {
- "node": ">=18"
+ "node": ">=18.17"
},
"homepage": "https://cumora.ai",
"keywords": [
diff --git a/docs/BYOA.md b/docs/BYOA.md
index 8b85ea9..3b83593 100644
--- a/docs/BYOA.md
+++ b/docs/BYOA.md
@@ -35,6 +35,86 @@ model-generated commands.
---
+## Codex login and state isolation
+
+All Cumora Codex calls use `CODEX_HOME` and `CODEX_SQLITE_HOME` at
+`~/.cumora/codex-runtime/`, including triage, doctor, model discovery and
+unsandboxed compatibility mode. Personal config, memories and unrelated sessions
+stay separate. Model calls set `memories.generate_memories=false`
+and `memories.use_memories=false` to disable Codex's native memory; agents keep
+using Cumora's memory files.
+
+When the runtime has no independent login, Cumora reuses the personal
+`CODEX_HOME/auth.json` (default `~/.codex/auth.json`) through a hard link.
+Both clients refresh the same credential file. Before each new process or idle
+agent turn, Cumora follows replacement, account changes and logout in the
+personal home. A changed login restarts an idle app-server with its saved thread
+ID; an active turn finishes first. Existing independent runtime credentials
+are preserved.
+
+Sharing requires file-backed credentials on the same filesystem. If the personal
+login exists only in the OS keyring, or the filesystem cannot create hard links,
+sign in separately for Cumora:
+
+```sh
+cumora agent computer --codex-login
+```
+
+The command runs `codex login` on Windows, macOS and Linux; authentication
+errors and `--doctor` also point to it. While authentication is linked, logging
+in updates the shared personal credentials too. Use personal Codex to log out
+of the shared account. Account quota is shared. Codex still owns token refresh
+and recovery; a revoked or unrefreshable login requires signing in again.
+The persistent app-server and model discovery read the runtime's `config.toml`;
+add any needed `model` or
+`model_providers` settings there. Secure `exec` ignores user config.
+
+Main threads resume after daemon restarts: macOS/Linux use app-server, while
+Windows and app-server fallbacks use `exec --json` / `exec resume <thread-id>`.
+Triage and doctor use ephemeral sessions.
+
+**Upgrading existing agents:** file-backed personal logins are reused automatically;
+use the command above only when separate authentication is needed. Before starting
+each Codex runner, the daemon automatically migrates the thread referenced by
+`~/.cumora/sessions/<agent-id>/codex.session` from the old `CODEX_HOME`
+(default `~/.codex`), preserving its ID.
+
+- Revised and compressed rollouts and paginated ancestors are supported.
+ Only each ancestor's referenced prefix is copied; compressed prefixes become
+ plain JSONL. Personal credentials, databases and unrelated history stay put.
+- An existing state database selects the rollout through a read-only lookup,
+ which requires Node.js 22.13 or newer. Older Node.js preserves the pointer
+ and reports how to retry. Unarchive a current archived thread in its old home first.
+- Files publish atomically without replacing runtime history or newer pointers.
+ The new pointer is `codex.runtime.session`; the old one becomes
+ `codex.session.migrated`. Repeated migration leaves current sessions alone.
+- Missing, unreadable or incomplete state pauses only the affected agent and
+ preserves its old pointer. Each sync retries; unchanged errors log once per
+ process, and pending conversations receive a failure notice. Restore the
+ rollout to recover automatically, without restarting the daemon.
+
+If the daemon no longer knows a customized old home, retry manually:
+
+```sh
+CODEX_HOME=/path/to/original/codex-home cumora agent computer --migrate-codex-sessions
+```
+
+In PowerShell:
+
+```powershell
+$env:CODEX_HOME = 'C:\path\to\original\codex-home'
+cumora agent computer --migrate-codex-sessions
+```
+
+Use the original home as the source, not `~/.cumora/codex-runtime`; omit
+`CODEX_HOME` for `~/.codex`. The manual command attempts all agents and reports
+partial failures with a nonzero exit. After signing in, wake agents again to
+clear authentication failures.
+
+Migration leaves personal history and previously generated memories in place;
+review them through personal Codex separately. To start an old agent fresh,
+move its `codex.session` pointer aside while the daemon is stopped.
+
## The Computer — the unifying host concept
Rather than bolt BYOA on as a special case, **Computer** is a first-class
@@ -164,8 +244,9 @@ selected engine's sandbox.
roster. The invariant scaffold (CLI usage, the shared
`GLANCE_YIELD_RULES`, memory rules, privacy boundary) is delivered
once per persistent session out-of-band — `--append-system-prompt-file`
- for Claude. Secure-default Codex uses a one-shot `exec` because its
- app-server currently cannot exclude user config, MCP, hook, and rule layers.
+ for Claude and `developerInstructions` for Codex's persistent app-server.
+ Codex uses a dedicated state directory; Windows and explicit opt-outs use
+ the one-shot `exec` fallback.
Compatibility engines retain their native standing-prompt behavior only
after the operator explicitly enables unsandboxed BYOA.
6. The engine reads its home (`CLAUDE.md` / `AGENTS.md`, skills,
@@ -304,7 +385,8 @@ fail-closed host boundary:
`ANTHROPIC_BASE_URL` that won't parse is (it fails toward "custom"). Claude
Code 2.1.248 or newer is required. Linux/WSL2 also requires `bubblewrap` and
`socat`; a missing dependency fails the turn.
-- Codex runs one-shot with user config and exec-policy rules ignored. A custom
+- Codex uses an isolated runtime home. Its one-shot fallback ignores user
+ config and exec-policy rules. A custom
permission profile permits minimal runtime reads and writes only under the
agent home, disables command network, and gives model-spawned commands only
an explicit non-secret environment. Hooks, apps, remote plugins, multi-agent
@@ -325,8 +407,8 @@ server assignment cannot make one execute accidentally.
CUMORA_BYOA_ALLOW_UNSANDBOXED=1 cumora agent computer
```
-This opt-in also re-enables `CUMORA_*_ARGS` whole-argv overrides and Codex's
-persistent app-server path. Without it, opaque engine arguments are ignored
+This opt-in also re-enables `CUMORA_*_ARGS` whole-argv overrides.
+Without it, opaque engine arguments are ignored
because the daemon cannot prove that they preserve the sandbox.
### Claude reasoning and response preferences
diff --git a/package-lock.json b/package-lock.json
index 3c178d3..54b8bfa 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -44,6 +44,7 @@
"emoji-regex": "^10.6.0",
"express": "^5.2.1",
"framer-motion": "^11.11.17",
+ "fzstd": "0.1.1",
"highlight.js": "^11.11.1",
"ioredis": "^5.10.1",
"lib0": "^0.2.117",
@@ -9801,6 +9802,12 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/fzstd": {
+ "version": "0.1.1",
+ "resolved": "https://registry.npmjs.org/fzstd/-/fzstd-0.1.1.tgz",
+ "integrity": "sha512-dkuVSOKKwh3eas5VkJy1AW1vFpet8TA/fGmVA5krThl8YcOVE/8ZIoEA1+U1vEn5ckxxhLirSdY837azmbaNHA==",
+ "license": "MIT"
+ },
"node_modules/gauge": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/gauge/-/gauge-4.0.4.tgz",
diff --git a/package.json b/package.json
index f4af48c..1e8a1c8 100644
--- a/package.json
+++ b/package.json
@@ -89,6 +89,7 @@
"emoji-regex": "^10.6.0",
"express": "^5.2.1",
"framer-motion": "^11.11.17",
+ "fzstd": "0.1.1",
"highlight.js": "^11.11.1",
"ioredis": "^5.10.1",
"lib0": "^0.2.117",
diff --git a/server/src/__tests__/agents-computer-codex-runtime.test.ts b/server/src/__tests__/agents-computer-codex-runtime.test.ts
new file mode 100644
index 0000000..ea606c1
--- /dev/null
+++ b/server/src/__tests__/agents-computer-codex-runtime.test.ts
@@ -0,0 +1,794 @@
+import assert from 'node:assert/strict'
+import { execFile } from 'node:child_process'
+import { writeFileSync } from 'node:fs'
+import { chmod, lstat, mkdir, mkdtemp, readFile, readdir, rename, 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 { promisify } from 'node:util'
+import { fileURLToPath } from 'node:url'
+import { codexAuthFingerprint, codexRuntimeEnv, codexRuntimeHome, CODEX_SESSION_SCOPE } from '../agents/computer/codex-runtime.js'
+import { migrateCodexSession, migrateCodexSessions } from '../agents/computer/codex-session-migration.js'
+import { getAdapter } from '../agents/computer/engine.js'
+import { clearModelCatalogCache, discoverEngineModelCatalog } from '../agents/computer/model-catalog.js'
+import { EngineSessionStore } from '../agents/computer/session-store.js'
+import { runWithSessionRecovery } from '../agents/computer/session-recovery.js'
+
+const execFileAsync = promisify(execFile)
+const IS_WIN = process.platform === 'win32'
+const original = { ...process.env }
+let root: string
+let bin: string
+let capture: string
+let source: string
+let destination: string
+let pointers: string
+const id = '00000000-0000-4000-8000-000000000001'
+const revision = '00000000-0000-4000-8000-000000000002'
+const other = '00000000-0000-4000-8000-000000000003'
+const sqliteModule = 'node:sqlite'
+const sqlite = await import(sqliteModule).catch(() => null)
+
+// Real child processes verify the environment at the process boundary, not
+// just the output of an argv builder. No authentication or model calls.
+const fakeCodex = `
+const fs = require('node:fs')
+const record = value => fs.appendFileSync(process.env.CODEX_TEST_CAPTURE, JSON.stringify(value) + '\\n')
+let authAccount
+try { authAccount = JSON.parse(fs.readFileSync(require('node:path').join(process.env.CODEX_HOME, 'auth.json'), 'utf8')).tokens?.account_id } catch {}
+record({ argv: process.argv.slice(2), home: process.env.CODEX_HOME, sqlite: process.env.CODEX_SQLITE_HOME, authAccount })
+const send = value => process.stdout.write(JSON.stringify(value) + '\\n')
+if (process.argv.includes('--version')) {
+ const versionCalls = fs.readFileSync(process.env.CODEX_TEST_CAPTURE, 'utf8').trim().split('\\n')
+ .map(line => JSON.parse(line)).filter(call => call.argv?.includes('--version')).length
+ if (versionCalls <= Number(process.env.CODEX_TEST_VERSION_FAILURES || 0)) process.exit(1)
+ process.stdout.write('codex-cli 0.160.0\\n')
+} else if (process.argv.includes('app-server')) {
+ require('node:readline').createInterface({ input: process.stdin }).on('line', line => {
+ const m = JSON.parse(line)
+ record(m)
+ if (m.method === 'initialize') send({ id: m.id, result: {} })
+ if (m.method === 'model/list') send({ id: m.id, result: { data: [{ id: 'fixture', model: 'fixture', isDefault: true }] } })
+ if (m.method === 'thread/start' || m.method === 'thread/resume') send({ id: m.id, result: { thread: { id: m.params.threadId || 'fixture-thread' } } })
+ if (m.method === 'turn/start') {
+ send({ id: m.id, result: { turn: { id: 'turn-1' } } })
+ send({ method: 'turn/completed', params: { turn: { id: 'turn-1', status: 'completed' } } })
+ }
+ })
+} else if (process.argv.includes('exec')) {
+ process.stdin.resume()
+ process.stdin.on('end', () => {
+ if (!process.argv.includes('--json')) return process.stdout.write('ok\\n')
+ if (process.argv.includes('resume') && process.env.CODEX_TEST_RESUME_FAILURE) {
+ send({ type: 'turn.failed', error: { message: 'No session found with id: missing-thread' } })
+ return
+ }
+ const resume = process.argv.indexOf('resume')
+ send({ type: 'thread.started', thread_id: resume < 0 ? 'fixture-thread' : process.argv[resume + 1] })
+ send({ type: 'turn.completed', usage: { input_tokens: 12, cached_input_tokens: 5, output_tokens: 3 } })
+ })
+}
+`
+
+beforeEach(async () => {
+ root = await mkdtemp(join(tmpdir(), 'cumora-codex-runtime-'))
+ bin = join(root, 'bin')
+ capture = join(root, 'calls.jsonl')
+ await mkdir(bin)
+ process.env.HOME = root
+ process.env.USERPROFILE = root
+ source = join(root, 'personal-codex')
+ destination = codexRuntimeHome()
+ pointers = join(root, '.cumora', 'sessions')
+ process.env.PATH = `${bin}${delimiter}${original.PATH ?? original.Path ?? ''}`
+ process.env.CODEX_HOME = source
+ process.env.CODEX_SQLITE_HOME = join(root, 'personal-databases')
+ process.env.CODEX_TEST_CAPTURE = capture
+ process.env.CUMORA_BYOA_ALLOW_UNSANDBOXED = '0'
+ delete process.env.CUMORA_CODEX_ARGS
+ delete process.env.CUMORA_TRIAGE_ARGS
+ delete process.env.CUMORA_CODEX_NO_APP_SERVER
+ const script = join(bin, 'node_modules', '@openai', 'codex', 'bin', 'codex.js')
+ await mkdir(join(bin, 'node_modules', '@openai', 'codex', 'bin'), { recursive: true })
+ await writeFile(script, fakeCodex)
+ if (IS_WIN) {
+ await writeFile(join(bin, 'codex.cmd'), `@echo off\r\n"${process.execPath}" "%~dp0node_modules\\@openai\\codex\\bin\\codex.js" %*\r\n`)
+ } else {
+ await writeFile(join(bin, 'codex'), `#!/bin/sh\nexec node "${script}" "$@"\n`)
+ await chmod(join(bin, 'codex'), 0o755)
+ }
+})
+
+afterEach(async () => {
+ for (const key of Object.keys(process.env)) if (!(key in original)) delete process.env[key]
+ Object.assign(process.env, original)
+ clearModelCatalogCache()
+ await rm(root, { recursive: true, force: true })
+})
+
+async function calls(): Promise<Array<Record<string, any>>> {
+ return (await readFile(capture, 'utf8')).trim().split('\n').map(line => JSON.parse(line))
+}
+
+function runComputer(flag: string, env = process.env) {
+ return execFileAsync(process.execPath, ['--import', 'tsx', fileURLToPath(new URL('../cli-bin.ts', import.meta.url)),
+ 'agent', 'computer', flag], { env, windowsHide: true, timeout: 15_000 })
+}
+
+async function writeAuth(home: string, account: string): Promise<string> {
+ await mkdir(home, { recursive: true })
+ const path = join(home, 'auth.json')
+ await writeFile(path, JSON.stringify({ tokens: { account_id: account, access_token: `fixture-${account}` } }), { mode: 0o600 })
+ return path
+}
+
+test('Codex environment overrides personal storage without mutating the parent or copying personal data', async () => {
+ const env = { ...process.env }
+ const child = codexRuntimeEnv(env)
+ assert.equal(child.CODEX_HOME, join(root, '.cumora', 'codex-runtime'))
+ assert.equal(child.CODEX_SQLITE_HOME, child.CODEX_HOME)
+ assert.equal(env.CODEX_HOME, join(root, 'personal-codex'))
+ assert.equal(process.env.CODEX_HOME, env.CODEX_HOME)
+ assert.deepEqual(await readdir(child.CODEX_HOME!), [])
+})
+
+test('authentication stays shared in both directions without sharing personal config or history', async () => {
+ const personal = await writeAuth(source, 'original-account')
+ await writeFile(join(source, 'config.toml'), 'personal settings')
+ await writeFile(join(source, 'history.jsonl'), 'personal history')
+ codexRuntimeEnv()
+ const runtime = join(destination, 'auth.json')
+ codexRuntimeEnv({ ...process.env, CODEX_HOME: IS_WIN ? destination.toUpperCase() : destination })
+ const alias = join(root, 'runtime-alias')
+ await symlink(destination, alias, IS_WIN ? 'junction' : 'dir')
+ codexRuntimeEnv({ ...process.env, CODEX_HOME: alias })
+ assert.equal(JSON.parse(await readFile(join(destination, 'auth.shared.json'), 'utf8')).source, personal)
+ assert.equal((await lstat(runtime)).ino, (await lstat(personal)).ino)
+ assert.equal(await readFile(runtime, 'utf8'), await readFile(personal, 'utf8'))
+ const before = codexAuthFingerprint()
+ await writeAuth(destination, 'runtime-refreshed-token')
+ assert.equal(await readFile(personal, 'utf8'), await readFile(runtime, 'utf8'))
+ await writeAuth(source, 'personal-refreshed-token')
+ assert.equal(await readFile(runtime, 'utf8'), await readFile(personal, 'utf8'))
+ assert.notEqual(codexAuthFingerprint(), before)
+ assert.deepEqual(await readdir(destination), ['auth.json', 'auth.shared.json'])
+ assert.equal(await readFile(join(source, 'config.toml'), 'utf8'), 'personal settings')
+ assert.equal(await readFile(join(source, 'history.jsonl'), 'utf8'), 'personal history')
+})
+
+test('hard-linked authentication follows atomic replacement, logout and login after restart', async () => {
+ const personal = await writeAuth(source, 'original-account')
+ codexRuntimeEnv()
+ const runtime = join(destination, 'auth.json')
+ const replacement = await writeAuth(join(root, 'replacement'), 'new-account')
+ await rename(replacement, personal)
+ codexRuntimeEnv()
+ assert.equal(await readFile(runtime, 'utf8'), await readFile(personal, 'utf8'))
+ await rm(personal)
+ assert.equal(codexAuthFingerprint(), null)
+ await assert.rejects(readFile(runtime), { code: 'ENOENT' })
+ await writeAuth(source, 'signed-in-again')
+ // A new process must reconstruct the binding from disk, not an in-memory cache.
+ await runComputer('--codex-login')
+ assert.equal(await readFile(runtime, 'utf8'), await readFile(personal, 'utf8'))
+ assert.equal((await calls()).find(call => call.argv?.includes('login'))!.authAccount, 'signed-in-again')
+})
+
+test('an independent runtime login is preserved, including replacement of a previously shared file', async () => {
+ const personal = await writeAuth(source, 'personal-account')
+ const runtime = await writeAuth(destination, 'independent-account')
+ const independent = await readFile(runtime, 'utf8')
+ codexRuntimeEnv()
+ assert.equal(await readFile(runtime, 'utf8'), independent)
+ await assert.rejects(readFile(join(destination, 'auth.shared.json')), { code: 'ENOENT' })
+ await rm(runtime)
+ codexRuntimeEnv()
+ const replacement = await writeAuth(join(root, 'independent'), 'replacement-account')
+ await rename(replacement, runtime)
+ codexRuntimeEnv()
+ assert.equal(JSON.parse(await readFile(runtime, 'utf8')).tokens.account_id, 'replacement-account')
+ assert.equal(JSON.parse(await readFile(personal, 'utf8')).tokens.account_id, 'personal-account')
+ await assert.rejects(readFile(join(destination, 'auth.shared.json')), { code: 'ENOENT' })
+})
+
+test('unreadable shared-auth metadata fails closed without replacing either login', async () => {
+ const personal = await writeAuth(source, 'personal-account')
+ await mkdir(destination, { recursive: true })
+ await writeFile(join(destination, 'auth.shared.json'), '{private-invalid-metadata')
+ assert.throws(() => codexRuntimeEnv(), /Invalid Codex authentication link metadata/)
+ assert.equal(JSON.parse(await readFile(personal, 'utf8')).tokens.account_id, 'personal-account')
+ await assert.rejects(readFile(join(destination, 'auth.json')), { code: 'ENOENT' })
+})
+
+test('a changed personal home cannot resurrect authentication from the previous home', async () => {
+ await writeAuth(source, 'old-account')
+ codexRuntimeEnv()
+ const nextHome = join(root, 'next-personal-home')
+ const env = { ...process.env, CODEX_HOME: nextHome }
+ codexRuntimeEnv(env)
+ assert.equal(codexAuthFingerprint(), null)
+ await writeAuth(nextHome, 'new-account')
+ codexRuntimeEnv(env)
+ assert.equal(JSON.parse(await readFile(join(destination, 'auth.json'), 'utf8')).tokens.account_id, 'new-account')
+})
+
+test('exec, triage, doctor and catalog share the isolated home in secure and compatibility modes', async () => {
+ await writeAuth(source, 'shared-account')
+ const adapter = getAdapter('codex')
+ for (const mode of ['0', '1']) {
+ process.env.CUMORA_BYOA_ALLOW_UNSANDBOXED = mode
+ const env = { ...process.env, CUMORA_AGENT_IPC_DIR: join(root, 'ipc'), CUMORA_AGENT_MCP_SHIM: join(root, 'shim') }
+ const signal = AbortSignal.timeout(10_000)
+ const turn = await adapter.run({ home: root, env, prompt: 'hello', onLog() {}, signal })
+ assert.equal(turn.exitCode, 0, turn.error)
+ await adapter.classify({ cwd: root, env, prompt: 'triage', signal })
+ await adapter.probe({ cwd: root, env, tier: 'small', signal })
+ const catalog = await discoverEngineModelCatalog('codex', join(bin, IS_WIN ? 'codex.cmd' : 'codex'), true, env)
+ assert.equal(catalog.defaultModel, 'fixture')
+ }
+ const spawns = (await calls()).filter(call => call.argv)
+ assert.equal(spawns.length, 8)
+ for (const call of spawns) {
+ assert.equal(call.home, codexRuntimeHome())
+ assert.equal(call.sqlite, codexRuntimeHome())
+ assert.equal(call.authAccount, 'shared-account')
+ assert.ok(call.argv.includes('memories.generate_memories=false'))
+ assert.ok(call.argv.includes('memories.use_memories=false'))
+ }
+ const execs = spawns.filter(call => call.argv.includes('exec'))
+ assert.deepEqual(execs.map(call => call.argv.includes('--ephemeral')), [false, true, true, false, true, true])
+})
+
+test('one-shot turns save and resume the same thread, including after a session store restart', async () => {
+ const adapter = getAdapter('codex')
+ const store = new EngineSessionStore(pointers, 'atlas', 'codex', CODEX_SESSION_SCOPE)
+ const env = { ...process.env, CUMORA_AGENT_IPC_DIR: join(root, 'ipc'), CUMORA_AGENT_MCP_SHIM: join(root, 'shim') }
+ for (const mode of ['0', '1']) {
+ process.env.CUMORA_BYOA_ALLOW_UNSANDBOXED = mode
+ for (let i = 0; i < 2; i++) {
+ const reloaded = new EngineSessionStore(pointers, 'atlas', 'codex', CODEX_SESSION_SCOPE)
+ const hops: unknown[] = []
+ const result = await adapter.run({
+ home: root, env, prompt: 'hello', model: 'fixture-model',
+ resumeSessionId: await reloaded.load(), onLog() {}, onHopUsage: hop => hops.push(hop),
+ signal: AbortSignal.timeout(10_000),
+ })
+ assert.equal(result.exitCode, 0, result.error)
+ assert.equal(result.sessionId, 'fixture-thread')
+ assert.deepEqual(result.usage, { input_tokens: 7, cache_read_input_tokens: 5, output_tokens: 3 })
+ assert.equal(hops.length, 1)
+ await store.save(result.sessionId!)
+ }
+ }
+ const execs = (await calls()).filter(call => call.argv?.includes('exec'))
+ assert.deepEqual(execs.map(call => call.argv.includes('resume')), [false, true, true, true])
+ for (const call of execs) {
+ assert.ok(call.argv.includes('--json'))
+ assert.equal(call.argv.at(-1), '-')
+ assert.equal(call.argv.includes('--ephemeral'), false)
+ }
+})
+
+test('one-shot resume failures use the existing fresh-session recovery instead of returning success', async () => {
+ const adapter = getAdapter('codex')
+ let resets = 0
+ const result = await runWithSessionRecovery({
+ resumeSessionId: 'missing-thread',
+ reset: async () => { resets++ },
+ run: resumeSessionId => adapter.run({
+ home: root,
+ env: { ...process.env, CODEX_TEST_RESUME_FAILURE: '1', CUMORA_AGENT_IPC_DIR: join(root, 'ipc'), CUMORA_AGENT_MCP_SHIM: join(root, 'shim') },
+ prompt: 'hello', resumeSessionId, onLog() {}, signal: AbortSignal.timeout(10_000),
+ }),
+ })
+ assert.equal(resets, 1)
+ assert.equal(result.exitCode, 0, result.error)
+ assert.equal(result.sessionId, 'fixture-thread')
+})
+
+test('custom Codex arguments cannot re-enable native memory', async () => {
+ process.env.CUMORA_BYOA_ALLOW_UNSANDBOXED = '1'
+ process.env.CUMORA_TRIAGE_ARGS = '-c memories.generate_memories=true -c memories.use_memories=true'
+ process.env.CUMORA_CODEX_ARGS = `--json ${process.env.CUMORA_TRIAGE_ARGS}`
+ const adapter = getAdapter('codex')
+ const env = { ...process.env }
+ const signal = AbortSignal.timeout(10_000)
+ await adapter.run({ home: root, env, prompt: 'hello', onLog() {}, signal })
+ await adapter.classify({ cwd: root, env, prompt: 'triage', signal })
+ await adapter.probe({ cwd: root, env, tier: 'big', signal })
+ const records = await calls()
+ assert.equal(records[0].argv.filter((arg: string) => arg === '--json').length, 1)
+ assert.equal(records[2].argv.includes('--model'), false)
+ assert.equal(records[2].argv.includes('memories.generate_memories=true'), false)
+ for (const call of records.filter(call => call.argv)) {
+ for (const key of ['generate_memories', 'use_memories']) {
+ assert.ok(call.argv.lastIndexOf(`memories.${key}=false`) > call.argv.lastIndexOf(`memories.${key}=true`))
+ }
+ }
+})
+
+test('persistent sessions resume the same thread after restart; wake probes are ephemeral', { skip: IS_WIN }, async () => {
+ const adapter = getAdapter('codex')
+ const env = { ...process.env, CUMORA_AGENT_IPC_DIR: join(root, 'ipc'), CUMORA_AGENT_MCP_SHIM: join(root, 'shim') }
+ let id: string | null = null
+ for (let i = 0; i < 2; i++) {
+ const session = adapter.startSession!({ home: root, env, resumeSessionId: id, onLog() {} })
+ assert.ok(session)
+ try {
+ const result = await session.send('hello')
+ assert.equal(result.exitCode, 0)
+ assert.equal(session.sessionId, 'fixture-thread')
+ id = session.sessionId
+ } finally { await session.stop() }
+ }
+ assert.equal((await adapter.probeWake!({ cwd: root, env, signal: AbortSignal.timeout(10_000) })).ok, true)
+ const records = await calls()
+ assert.deepEqual(records.filter(call => call.method === 'thread/resume').map(call => call.params.threadId), ['fixture-thread'])
+ assert.deepEqual(records.filter(call => call.method === 'thread/start').map(call => call.params.ephemeral ?? false), [false, true])
+ for (const call of records.filter(call => call.argv)) {
+ assert.equal(call.home, codexRuntimeHome())
+ assert.ok(call.argv.includes('memories.generate_memories=false'))
+ assert.ok(call.argv.includes('memories.use_memories=false'))
+ assert.ok(call.argv.includes('default_permissions="cumora"'))
+ }
+})
+
+test('persistent sessions finish active turns and then resume with a changed or removed login', { skip: IS_WIN }, async () => {
+ const personal = await writeAuth(source, 'original-account')
+ const adapter = getAdapter('codex')
+ const env = { ...process.env, CUMORA_AGENT_IPC_DIR: join(root, 'ipc'), CUMORA_AGENT_MCP_SHIM: join(root, 'shim') }
+ const logs: string[] = []
+ const session = adapter.startSession!({ home: root, env, onLog: line => logs.push(line) })!
+ try {
+ assert.equal((await session.send('hello')).exitCode, 0)
+ const auth = await readFile(personal, 'utf8')
+ writeFileSync(personal, '{partial credential write')
+ assert.equal(session.alive, true)
+ writeFileSync(personal, auth)
+ const turn = session.send('finish this turn')
+ writeFileSync(personal, JSON.stringify({ tokens: { account_id: 'new-account' } }))
+ assert.equal(session.alive, true)
+ assert.equal((await turn).exitCode, 0)
+ assert.equal(session.alive, false)
+ assert.equal(session.sessionId, 'fixture-thread')
+ } finally { await session.stop() }
+ const resumed = adapter.startSession!({ home: root, env, resumeSessionId: session.sessionId, onLog: line => logs.push(line) })!
+ try {
+ assert.equal((await resumed.send('continue')).sessionId, 'fixture-thread')
+ await rm(personal)
+ assert.equal(resumed.alive, false)
+ } finally { await resumed.stop() }
+ assert.ok(logs.some(line => line.includes('login changed')))
+ assert.equal((await calls()).filter(call => call.argv?.includes('app-server'))[1].authAccount, 'new-account')
+})
+
+test('the login command uses the dedicated home and exits without pairing or starting a daemon', async () => {
+ if (IS_WIN) process.env.PATH = `${bin}${delimiter}${join(process.env.SystemRoot!, 'System32')}`
+ await runComputer('--codex-login')
+ const records = await calls()
+ assert.ok(records.some(call => call.argv?.includes('--version')))
+ const login = records.find(call => call.argv?.includes('login'))!
+ assert.deepEqual(login.argv, ['login'])
+ assert.equal(login.home, codexRuntimeHome())
+ assert.equal(login.sqlite, codexRuntimeHome())
+ assert.deepEqual(await readdir(join(root, '.cumora')), ['codex-runtime'])
+})
+
+test('login retries an inconclusive version probe without misreporting an installed CLI as missing', async () => {
+ for (const failures of [2, 3]) {
+ await rm(capture, { force: true })
+ const result = runComputer('--codex-login', { ...process.env, CODEX_TEST_VERSION_FAILURES: String(failures) })
+ if (failures === 2) await result
+ else await assert.rejects(result, error => {
+ const detail = error as Error & { code: number; stderr: string }
+ assert.equal(detail.code, 2)
+ assert.match(detail.stderr, /found on PATH.*version could not be verified/)
+ assert.doesNotMatch(detail.stderr, /npm install|unavailable on PATH/)
+ return true
+ })
+ const records = await calls()
+ assert.equal(records.filter(call => call.argv?.includes('--version')).length, 3)
+ assert.equal(records.some(call => call.argv?.includes('login')), failures === 2)
+ }
+})
+
+test('login without Codex reports installation instructions without an uncaught stack', async () => {
+ const emptyPath = join(root, 'empty-path')
+ await mkdir(emptyPath)
+ await assert.rejects(runComputer('--codex-login', { ...process.env, PATH: emptyPath }), error => {
+ const result = error as Error & { code: number; stderr: string }
+ assert.equal(result.code, 2)
+ assert.match(result.stderr, /Codex CLI is unavailable on PATH.*npm install -g @openai\/codex/)
+ assert.doesNotMatch(result.stderr, /\n\s+at |UnhandledPromiseRejection/)
+ return true
+ })
+})
+
+test('migration copies only referenced rollouts, preserves IDs and personal data, and is repeatable', async () => {
+ const name = join('2026', '10', '03', originalName)
+ const path = await rollout(name, { id, cwd: join(root, '.cumora', 'agents', 'atlas') })
+ const transcript = await readFile(path, 'utf8')
+ await writeFile(join(source, 'auth.json'), 'private-auth')
+ await writeFile(join(source, 'sessions', 'personal.jsonl'), 'private-chat')
+ const legacy = await pointer()
+ const store = new EngineSessionStore(pointers, 'atlas', 'codex', CODEX_SESSION_SCOPE)
+ const result = await runComputer('--migrate-codex-sessions')
+ assert.match(result.stdout, /Migrated 1 Codex session/)
+ assert.equal(await readFile(join(destination, 'sessions', name), 'utf8'), transcript)
+ assert.equal(await store.load(), id)
+ assert.equal(await readFile(`${legacy}.migrated`, 'utf8'), id)
+ assert.equal(await readFile(path, 'utf8'), transcript)
+ assert.equal(await readFile(join(source, 'auth.json'), 'utf8'), 'private-auth')
+ assert.deepEqual(await readdir(codexRuntimeHome()), ['sessions'])
+ assert.deepEqual(await migrateCodexSessions(), [])
+ await store.save('newer-thread')
+ // Retries preserve newer sessions; resets must not resurrect a legacy thread.
+ await pointer()
+ assert.deepEqual(await migrateCodexSessions(), [])
+ assert.equal(await store.load(), 'newer-thread')
+ await store.save(null)
+ assert.deepEqual(await migrateCodexSessions(), [])
+ assert.equal(await store.load(), null)
+ await pointer('atlas', ' \n ')
+ assert.deepEqual(await migrateCodexSessions(), [])
+ assert.equal(await store.load(), null)
+})
+
+test('an unavailable legacy rollout fails migration without switching the session pointer', async () => {
+ await pointer('atlas', 'missing-thread')
+ await assert.rejects(migrateCodexSessions(), /old session pointer has been preserved/)
+ assert.deepEqual(await readdir(join(pointers, 'atlas')), ['codex.session'])
+})
+
+test('daemon migrates automatically, isolates failures, deduplicates retries and recovers without restart', async () => {
+ const agentThreads = [['blocked', revision], ['healthy', id]]
+ const missingRollout = `rollout-2026-10-03T00-00-00-${revision}.jsonl`
+ await rollout(originalName, { id })
+ for (const [agent, thread] of agentThreads) await pointer(agent, thread)
+ await writeFile(join(root, '.cumora', 'computer.json'), JSON.stringify({
+ serverUrl: 'http://fixture.local', computerId: 'fixture-computer', deviceToken: 'fixture-token',
+ }))
+
+ const script = (recover: boolean) => `
+ import assert from 'node:assert/strict'
+ import { writeFile, access } from 'node:fs/promises'
+ const { ENGINE_IDS, getAdapter } = await import(${JSON.stringify(new URL('../agents/computer/engine.ts', import.meta.url).href)})
+ // Do not probe engines installed on the developer's machine.
+ for (const id of ENGINE_IDS) if (id !== 'codex') getAdapter(id).bin = 'cumora-fixture-missing-' + id
+ const { runComputerDaemon } = await import(${JSON.stringify(new URL('../agents/computer/daemon.ts', import.meta.url).href)})
+ const errors = []
+ const logError = console.error
+ console.error = (...args) => { errors.push(args.join(' ')); logError(...args) }
+ const connected = new Set()
+ let scans = 0
+ let notices = 0
+ let noticeAttempts = 0
+ let blockedTokens = 0
+ let pendingConversation = 'fixture-conversation'
+ const interval = globalThis.setInterval
+ globalThis.setInterval = (fn, ms, ...args) => interval(fn, ms === 60_000 ? 40 : ms, ...args)
+ const agents = ['blocked', 'healthy', 'new-user'].map(id => ({
+ id, name: id, engine: 'codex', role: null, systemPrompt: null, model: null, fastModel: null,
+ }))
+ // Exercise real daemon reconciliation and runners without a backend,
+ // credentials, messages or model calls. All fetches stay inside this fixture.
+ globalThis.fetch = async (url, options = {}) => {
+ const path = new URL(url).pathname
+ if (path === '/api/computers/me/agents') { scans++; return Response.json(agents) }
+ if (path.endsWith('/runtime-token')) {
+ if (path.split('/')[3] === 'blocked') blockedTokens++
+ return Response.json({ token: path.split('/')[3], expiresInSeconds: 3600 })
+ }
+ if (path === '/runtime/inbox') return Response.json({ rows: [{ conversation_id: pendingConversation }] })
+ if (path === '/runtime/notices') {
+ if (++noticeAttempts === 1) return new Response('', { status: 503 })
+ const body = JSON.parse(options.body)
+ assert.match(body.text, /Codex session could not be migrated/)
+ assert.match(body.text, /migrate-codex-sessions/)
+ assert.match(body.dedupeKey, /codex_migration_failed:blocked:/)
+ notices++
+ return Response.json({ posted: true })
+ }
+ if (path.endsWith('wake-stream')) connected.add(options.headers.Authorization.slice(7))
+ if (path.endsWith('stream')) return new Response(new ReadableStream({ start() {} }), { headers: { 'Content-Type': 'text/event-stream' } })
+ if (path === '/api/computers/heartbeat' || path === '/api/computers/me/engines') return Response.json({})
+ throw new Error('Unexpected fixture request: ' + path)
+ }
+ const waitFor = async (condition) => {
+ const deadline = Date.now() + 8000
+ while (!condition()) {
+ assert.ok(Date.now() < deadline, 'daemon did not reach expected state: ' + [...connected] + '; scans=' + scans)
+ await new Promise(resolve => setTimeout(resolve, 10))
+ }
+ }
+ await runComputerDaemon([])
+ await waitFor(() => scans >= 4 && connected.has('healthy') && connected.has('new-user'))
+ if (${recover}) {
+ assert.equal(connected.has('blocked'), false)
+ assert.equal(errors.filter(line => line.includes('blocked paused:')).length, 1)
+ assert.equal(notices, 1)
+ assert.equal(noticeAttempts, 2)
+ assert.equal(blockedTokens, 1)
+ pendingConversation = 'new-conversation'
+ await waitFor(() => notices === 2)
+ assert.equal(noticeAttempts, 3)
+ assert.equal(blockedTokens, 1)
+ await assert.rejects(access(${JSON.stringify(join(root, '.cumora', '.runtime-cli-ipc', 'blocked'))}), { code: 'ENOENT' })
+ await writeFile(${JSON.stringify(join(source, 'sessions', missingRollout))}, ${JSON.stringify(`${JSON.stringify({ type: 'session_meta', payload: { id: revision } })}\n`)})
+ await waitFor(() => connected.has('blocked'))
+ assert.equal(errors.filter(line => line.includes('blocked paused:')).length, 1)
+ assert.equal(notices, 2)
+ } else {
+ await waitFor(() => connected.has('blocked'))
+ assert.deepEqual(errors, [])
+ }
+ assert.equal(process.exitCode, undefined)
+ process.exit(0)
+ `
+ for (const recover of [true, false]) {
+ const result = await execFileAsync(process.execPath, ['--import', 'tsx', '--input-type=module', '-e', script(recover)], {
+ env: process.env, windowsHide: true, timeout: 15_000,
+ })
+ assert.match(result.stdout, /healthy restored codex session/)
+ assert.match(result.stdout, /blocked restored codex session/)
+ assert.doesNotMatch(result.stderr, /new-user paused:/)
+ for (const [agent, thread] of agentThreads) {
+ assert.equal(await new EngineSessionStore(pointers, agent, 'codex', CODEX_SESSION_SCOPE).load(), thread)
+ assert.equal(await readFile(join(pointers, agent, 'codex.session.migrated'), 'utf8'), thread)
+ }
+ for (const name of [originalName, missingRollout]) {
+ assert.equal(await readFile(join(destination, 'sessions', name), 'utf8'), await readFile(join(source, 'sessions', name), 'utf8'))
+ }
+ }
+})
+
+async function pointer(agent = 'atlas', thread = id): Promise<string> {
+ const path = join(pointers, agent, 'codex.session')
+ await mkdir(dirname(path), { recursive: true })
+ await writeFile(path, thread)
+ return path
+}
+
+async function rollout(name: string, metadata: Record<string, unknown>, directory = 'sessions', prefix = ''): Promise<string> {
+ const path = join(source, directory, name)
+ await mkdir(dirname(path), { recursive: true })
+ await writeFile(path, prefix + JSON.stringify({ type: 'session_meta', payload: metadata }) + '\n')
+ return path
+}
+
+const originalName = `rollout-2026-10-03T00-00-00-${id}.jsonl`
+const revisedName = `rollout-2026-10-06T00-00-00-${id}_${revision}.jsonl`
+// A Zstandard-compressed metadata record, generated once with Node's encoder.
+const compressedMetadata = Buffer.from('KLUv/SBQPQIAlAN7InR5cGUiOiJzZXNzaW9uX21ldGEiLCJwYXlsb2FkIjp7ImlkIjoiMC0tNDAwMC04MDAwMSJ9fQoEADsJoISphJsMlAE=', 'base64')
+
+test('migration selects the revised rollout and leaves unrelated history behind', async () => {
+ await pointer()
+ await rollout(originalName, { id, version: 'obsolete' })
+ const latest = await rollout(revisedName, { id, version: 'current' })
+ await rollout(`rollout-2026-10-06T00-00-00-${other}.jsonl`, { id: other })
+ assert.equal(await migrateCodexSession('atlas'), true)
+ assert.deepEqual(await readdir(join(destination, 'sessions')), [revisedName])
+ assert.equal(await readFile(join(destination, 'sessions', revisedName), 'utf8'), await readFile(latest, 'utf8'))
+ assert.equal(await readFile(join(pointers, 'atlas', 'codex.runtime.session'), 'utf8'), id + '\n')
+})
+
+test('a legacy backup rename failure preserves both pointers and does not block runtime resume on retry', async () => {
+ const legacy = await pointer()
+ await rollout(originalName, { id })
+ await mkdir(`${legacy}.migrated`)
+ // A nonempty directory blocks rename on both POSIX and Windows.
+ await writeFile(join(`${legacy}.migrated`, 'keep'), 'existing backup')
+ await assert.rejects(migrateCodexSession('atlas'), /old session pointer has been preserved/)
+ assert.equal(await readFile(legacy, 'utf8'), id)
+ assert.equal(await migrateCodexSession('atlas'), false)
+ await assert.rejects(readFile(legacy), { code: 'ENOENT' })
+ await mkdir(legacy)
+ assert.equal(await migrateCodexSession('atlas'), false)
+ assert.deepEqual(await readdir(legacy), [])
+ assert.equal(await readFile(join(pointers, 'atlas', 'codex.runtime.session'), 'utf8'), id + '\n')
+ assert.equal(await readFile(join(`${legacy}.migrated`, 'keep'), 'utf8'), 'existing backup')
+})
+
+test('SQLite selection wins over filename timestamps, including uncheckpointed WAL rows', { skip: !sqlite }, async () => {
+ await pointer()
+ const selected = await rollout(originalName, { id, version: 'selected' })
+ await rollout(revisedName, { id, version: 'unselected' })
+ const sqliteHome = join(root, 'separate-sqlite-home')
+ await mkdir(sqliteHome)
+ process.env.CODEX_SQLITE_HOME = sqliteHome
+ const databasePath = join(sqliteHome, 'state_5.sqlite')
+ const database = new sqlite!.DatabaseSync(databasePath)
+ try {
+ database.exec('PRAGMA journal_mode=WAL; CREATE TABLE threads (id TEXT PRIMARY KEY, rollout_path TEXT)')
+ database.prepare('INSERT INTO threads VALUES (?, ?)').run(id, selected)
+ const before = await readFile(databasePath)
+ assert.equal(await migrateCodexSession('atlas'), true)
+ assert.deepEqual(await readdir(join(destination, 'sessions')), [originalName])
+ assert.deepEqual(await readFile(databasePath), before)
+ assert.deepEqual(await readdir(destination), ['sessions'])
+ } finally { database.close() }
+})
+
+test('a missing database-selected rollout cannot silently fall back to old history', { skip: !sqlite }, async () => {
+ process.env.CODEX_SQLITE_HOME = source
+ const legacy = await pointer()
+ await rollout(originalName, { id })
+ const database = new sqlite!.DatabaseSync(join(source, 'state_5.sqlite'))
+ database.exec('CREATE TABLE threads (id TEXT PRIMARY KEY, rollout_path TEXT)')
+ database.prepare('INSERT INTO threads VALUES (?, ?)').run(id, join(source, 'sessions', revisedName))
+ database.close()
+ await assert.rejects(migrateCodexSession('atlas'), /selected by Codex's database is unavailable/)
+ assert.equal(await readFile(legacy, 'utf8'), id)
+})
+
+test('older Node.js reports how to read database selection without guessing or moving the pointer', { skip: !!sqlite }, async () => {
+ process.env.CODEX_SQLITE_HOME = source
+ const legacy = await pointer()
+ await rollout(originalName, { id })
+ await writeFile(join(source, 'state_5.sqlite'), '')
+ await assert.rejects(migrateCodexSession('atlas'), /requires Node\.js 22\.13 or newer/)
+ assert.equal(await readFile(legacy, 'utf8'), id)
+ await assert.rejects(readdir(destination), { code: 'ENOENT' })
+})
+
+test('compressed rollouts migrate with identity validation on older Node.js versions too', async () => {
+ await pointer()
+ await mkdir(join(source, 'sessions'), { recursive: true })
+ await writeFile(join(source, 'sessions', originalName + '.zst'), compressedMetadata)
+ assert.equal(await migrateCodexSession('atlas'), true)
+ assert.deepEqual(await readFile(join(destination, 'sessions', originalName + '.zst')), compressedMetadata)
+})
+
+test('migration follows archived history_base, excluding unrelated threads and later personal messages', async () => {
+ await pointer('atlas', other)
+ const ancestor = await rollout(originalName, { id, history_mode: 'paginated' }, 'archived_sessions')
+ const prefix = await readFile(ancestor)
+ await writeFile(ancestor, Buffer.concat([prefix, Buffer.from('{"type":"response_item","payload":{"text":"private later message"}}\n')]))
+ const currentName = `rollout-2026-10-06T00-00-00-${other}_${revision}.jsonl`
+ const current = await rollout(currentName, {
+ id: other, session_id: id, history_mode: 'paginated',
+ history_base: { thread_id: id, end_ordinal_exclusive: 1, end_byte_offset: prefix.length },
+ })
+ await rollout(`rollout-2026-10-06T00-00-00-${revision}.jsonl`, { id: revision })
+ assert.equal(await migrateCodexSession('atlas'), true)
+ assert.deepEqual(await readFile(join(destination, 'archived_sessions', originalName)), prefix)
+ assert.match(await readFile(ancestor, 'utf8'), /private later message/)
+ assert.equal(await readFile(join(destination, 'sessions', currentName), 'utf8'), await readFile(current, 'utf8'))
+ assert.deepEqual(await readdir(join(destination, 'sessions')), [currentName])
+})
+
+test('a compressed ancestor is published as the exact uncompressed prefix', async () => {
+ await pointer('atlas', other)
+ await mkdir(join(source, 'archived_sessions'), { recursive: true })
+ await writeFile(join(source, 'archived_sessions', originalName + '.zst'), compressedMetadata)
+ const prefix = Buffer.from(JSON.stringify({ type: 'session_meta', payload: { id } }) + '\n')
+ await rollout(`rollout-2026-10-06T00-00-00-${other}_${revision}.jsonl`, {
+ id: other, history_mode: 'paginated',
+ history_base: { thread_id: id, end_ordinal_exclusive: 1, end_byte_offset: prefix.length },
+ })
+ assert.equal(await migrateCodexSession('atlas'), true)
+ assert.deepEqual(await readFile(join(destination, 'archived_sessions', originalName)), prefix)
+ assert.deepEqual(await readdir(join(destination, 'archived_sessions')), [originalName])
+})
+
+for (const [offset, reason] of [
+ [-1, /does not end at a complete record/],
+ [1, /history_base extends beyond source rollout/],
+] as const) {
+ test(`history prefix with length offset ${offset} fails before copying any state`, async () => {
+ const legacy = await pointer()
+ const ancestor = await rollout(originalName, { id, history_mode: 'paginated' })
+ await rollout(revisedName, {
+ id, history_mode: 'paginated',
+ history_base: { thread_id: id, end_ordinal_exclusive: 1, end_byte_offset: (await readFile(ancestor)).length + offset },
+ })
+ await assert.rejects(migrateCodexSession('atlas'), reason)
+ assert.equal(await readFile(legacy, 'utf8'), id)
+ await assert.rejects(readdir(destination), { code: 'ENOENT' })
+ })
+}
+
+test('migration never overwrites a rollout already used by the isolated runtime', async () => {
+ await pointer()
+ const path = await rollout(originalName, { id })
+ const runtimePath = join(destination, 'sessions', originalName)
+ await mkdir(dirname(runtimePath), { recursive: true })
+ const newer = (await readFile(path, 'utf8')) + '{"type":"response_item","payload":{"text":"new runtime turn"}}\n'
+ await writeFile(runtimePath, newer)
+ assert.equal(await migrateCodexSession('atlas'), true)
+ assert.equal(await readFile(runtimePath, 'utf8'), newer)
+})
+
+test('automatic and manual migration can race without replacing the winning pointer', async () => {
+ await pointer()
+ await rollout(originalName, { id })
+ const results = await Promise.all([
+ migrateCodexSession('atlas'),
+ migrateCodexSession('atlas'),
+ ])
+ assert.deepEqual(results.sort(), [false, true])
+ const store = new EngineSessionStore(pointers, 'atlas', 'codex', CODEX_SESSION_SCOPE)
+ assert.equal(await store.load(), id)
+ await store.save('new-runtime-thread')
+ assert.equal(await migrateCodexSession('atlas'), false)
+ assert.equal(await store.load(), 'new-runtime-thread')
+ assert.deepEqual(await readdir(join(pointers, 'atlas')), ['codex.runtime.session', 'codex.session.migrated'])
+})
+
+test('an incomplete existing rollout is preserved and temporary copies are cleaned up', async () => {
+ const legacy = await pointer()
+ const path = await rollout(originalName, { id })
+ await writeFile(path, (await readFile(path, 'utf8')) + '{"type":"response_item","payload":{"text":"original turn"}}\n')
+ const runtimePath = join(destination, 'sessions', originalName)
+ await mkdir(dirname(runtimePath), { recursive: true })
+ const incomplete = JSON.stringify({ type: 'session_meta', payload: { id } }) + '\n'
+ await writeFile(runtimePath, incomplete)
+ await assert.rejects(migrateCodexSession('atlas'), /history_base extends beyond source rollout/)
+ assert.equal(await readFile(runtimePath, 'utf8'), incomplete)
+ assert.equal(await readFile(legacy, 'utf8'), id)
+ assert.deepEqual(await readdir(dirname(runtimePath)), [originalName])
+})
+
+test('an unreadable runtime pointer pauses migration before copying or replacing state', async () => {
+ const legacy = await pointer()
+ await rollout(originalName, { id })
+ await mkdir(join(pointers, 'atlas', 'codex.runtime.session'))
+ await assert.rejects(migrateCodexSession('atlas'), /old session pointer has been preserved/)
+ assert.equal(await readFile(legacy, 'utf8'), id)
+ await assert.rejects(readdir(destination), { code: 'ENOENT' })
+})
+
+test('incomplete or cyclic pagination preserves the pointer before copying any history', async () => {
+ const legacy = await pointer()
+ for (const sourceId of [other, revision]) {
+ await rollout(revisedName, {
+ id, history_mode: 'paginated',
+ history_base: { thread_id: sourceId, end_ordinal_exclusive: 5, end_byte_offset: 100 },
+ })
+ await assert.rejects(migrateCodexSession('atlas'), /missing source rollout|cyclic history_base/)
+ assert.equal(await readFile(legacy, 'utf8'), id)
+ await assert.rejects(readdir(destination), { code: 'ENOENT' })
+ }
+})
+
+test('metadata parsing skips blank and malformed records but rejects unreadable or mismatched histories', async () => {
+ const legacy = await pointer()
+ const path = await rollout(originalName, { id }, 'sessions', '\n{broken json\n{"type":"event_msg","payload":{}}\n')
+ assert.equal(await migrateCodexSession('atlas'), true)
+ await rm(join(pointers, 'atlas', 'codex.runtime.session'))
+ for (const text of ['', '{broken json\n', JSON.stringify({ type: 'session_meta', payload: { id: other } })]) {
+ await writeFile(legacy, id)
+ await writeFile(path, text)
+ await assert.rejects(migrateCodexSession('atlas'), {
+ name: 'Error', message: /no readable session metadata|belongs to another thread/,
+ })
+ assert.equal(await readFile(legacy, 'utf8'), id)
+ }
+})
+
+test('an archived current thread reports unarchive instructions and preserves its pointer', async () => {
+ const legacy = await pointer()
+ await rollout(originalName, { id }, 'archived_sessions')
+ await assert.rejects(migrateCodexSession('atlas'), /thread is archived.*codex unarchive/)
+ assert.equal(await readFile(legacy, 'utf8'), id)
+})
+
+test('bulk migration continues after failures and reports partial success', async () => {
+ const legacy = await pointer('broken', other)
+ await pointer('healthy')
+ await rollout(originalName, { id })
+ await assert.rejects(migrateCodexSessions(), err => {
+ assert.ok(err instanceof AggregateError)
+ assert.ok(err.message.includes(`Migrated 1 Codex session(s) (healthy) to ${destination}`))
+ assert.match(err.message, /Personal Codex data was left in place; failed 1/)
+ return true
+ })
+ assert.equal(await readFile(legacy, 'utf8'), other)
+ assert.equal(await readFile(join(pointers, 'healthy', 'codex.runtime.session'), 'utf8'), id + '\n')
+})
+
+test('using the runtime itself as the source produces an actionable error without moving the pointer', async () => {
+ const legacy = await pointer()
+ await assert.rejects(migrateCodexSession('atlas', source, pointers, source), /source and destination Codex homes are the same/)
+ assert.equal(await readFile(legacy, 'utf8'), id)
+})
diff --git a/server/src/__tests__/agents-computer-codex-strict-config.test.ts b/server/src/__tests__/agents-computer-codex-strict-config.test.ts
index cf7fb44..b02e732 100644
--- a/server/src/__tests__/agents-computer-codex-strict-config.test.ts
+++ b/server/src/__tests__/agents-computer-codex-strict-config.test.ts
@@ -27,11 +27,12 @@ import assert from 'node:assert/strict'
import { getAdapter } from '../agents/computer/engine.js'
const IS_WIN = process.platform === 'win32'
-const ORIGINAL_PATH = process.env.PATH
+const original = { ...process.env }
const tempDirs: string[] = []
afterEach(async () => {
- process.env.PATH = ORIGINAL_PATH
+ for (const key of Object.keys(process.env)) if (!(key in original)) delete process.env[key]
+ Object.assign(process.env, original)
await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })))
})
@@ -46,6 +47,9 @@ interface Fixture { root: string; home: string; env: NodeJS.ProcessEnv }
async function fixture(homeName: string): Promise<Fixture> {
const root = await mkdtemp(join(tmpdir(), 'cumora-codex-cfg-'))
tempDirs.push(root)
+ process.env.HOME = root
+ process.env.USERPROFILE = root
+ process.env.CODEX_HOME = join(root, 'personal-codex')
const binDir = join(root, 'bin')
// The reporter asked specifically for a home with ordinary separators and
// spaces: that is where the quoting in the override has to hold up.
@@ -59,7 +63,7 @@ async function fixture(homeName: string): Promise<Fixture> {
root, home,
env: {
...process.env,
- PATH: `${binDir}${delimiter}${ORIGINAL_PATH ?? ''}`,
+ PATH: `${binDir}${delimiter}${original.PATH ?? original.Path ?? ''}`,
CUMORA_AGENT_IPC_DIR: join(root, 'ipc'),
CUMORA_AGENT_MCP_SHIM: join(root, 'shim.mjs'),
},
diff --git a/server/src/__tests__/agents-computer-daemon-auth-hint.test.ts b/server/src/__tests__/agents-computer-daemon-auth-hint.test.ts
index a46bd9e..d46ecb8 100644
--- a/server/src/__tests__/agents-computer-daemon-auth-hint.test.ts
+++ b/server/src/__tests__/agents-computer-daemon-auth-hint.test.ts
@@ -1,7 +1,7 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { authFailureHint } from '../agents/computer/daemon.js'
-import { ENGINE_IDS, type EngineId } from '../agents/computer/engine.js'
+import { classifyEngineFailure, ENGINE_IDS, type EngineId } from '../agents/computer/engine.js'
test('authFailureHint provides specific guidance for every supported engine', () => {
for (const engine of ENGINE_IDS) {
@@ -26,6 +26,28 @@ test('authFailureHint correctly mentions the relevant CLI/tool for each engine',
assert.match(authFailureHint('antigravity', 'quota exceeded'), /agy/)
})
+test('Codex authentication guidance signs in to the isolated runtime', () => {
+ for (const detail of [
+ 'Not logged in',
+ 'Please sign in to continue',
+ 'Please sign in.',
+ 'Sign in to Codex',
+ 'Sign in with your ChatGPT account to continue',
+ 'You need to sign in before continuing',
+ 'Your sign-in has expired',
+ 'Log in to continue',
+ 'Please run /login',
+ ]) {
+ assert.equal(classifyEngineFailure(detail), 'authentication')
+ assert.match(authFailureHint('codex', detail), /cumora agent computer --codex-login/)
+ }
+ for (const file of ['sign-in.md', 'docs/sign-in.md', 'docs/signin.md', 'C:\\docs\\sign-in.md']) {
+ const detail = `filesystem failed while writing ${file}: EIO`
+ assert.equal(classifyEngineFailure(detail), 'unknown')
+ assert.match(authFailureHint('codex', detail), /daemon terminal for details/)
+ }
+})
+
test('authFailureHint handles context overflow and poisoned body sentinels', () => {
assert.match(authFailureHint('gemini', 'context window overflowed max tokens'), /context window/)
assert.match(authFailureHint('qwen', 'lone surrogate split emoji poisoned'), /poisoned/)
diff --git a/server/src/__tests__/agents-computer-engine.test.ts b/server/src/__tests__/agents-computer-engine.test.ts
index c2f566d..6244f31 100644
--- a/server/src/__tests__/agents-computer-engine.test.ts
+++ b/server/src/__tests__/agents-computer-engine.test.ts
@@ -7,16 +7,14 @@ import assert from 'node:assert/strict'
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, test } from 'node:test'
+import { afterEach, beforeEach, test } from 'node:test'
import { setTimeout as delay } from 'node:timers/promises'
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_PATH = process.env.PATH
-const ORIGINAL_PATHEXT = process.env.PATHEXT
-const ORIGINAL_UNSANDBOXED = process.env.CUMORA_BYOA_ALLOW_UNSANDBOXED
+const original = { ...process.env }
const 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.
@@ -67,14 +65,18 @@ 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 */ } }
- 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_UNSANDBOXED
+ for (const key of Object.keys(process.env)) if (!(key in original)) delete process.env[key]
+ Object.assign(process.env, original)
await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })))
})
@@ -551,7 +553,7 @@ test('resolveSpawn runs a native Windows executable without cmd.exe', { skip: !I
const binDir = join(root, 'bin')
await mkdir(binDir)
await writeFile(join(binDir, 'codex.exe'), '', 'utf8')
- process.env.PATH = `${binDir};${ORIGINAL_PATH ?? ''}`
+ process.env.PATH = `${binDir};${original.PATH ?? original.Path ?? ''}`
process.env.PATHEXT = '.EXE;.CMD;.BAT;.COM'
const r = resolveSpawn('codex')
@@ -587,7 +589,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 ?? ''}`
+ process.env.PATH = `${binDir}${delimiter}${original.PATH ?? original.Path ?? ''}`
const adapter = getAdapter('codex')
const mcpShim = join(root, 'trusted', 'cumora-mcp')
diff --git a/server/src/agents/computer/codex-runtime.ts b/server/src/agents/computer/codex-runtime.ts
new file mode 100644
index 0000000..17fdf84
--- /dev/null
+++ b/server/src/agents/computer/codex-runtime.ts
@@ -0,0 +1,102 @@
+import { createHash, randomUUID } from 'node:crypto'
+import { type BigIntStats, linkSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { isAbsolute, join, relative, resolve } from 'node:path'
+
+// Keep pointers to the isolated runtime separate from pre-upgrade threads.
+export const CODEX_SESSION_SCOPE = 'runtime'
+export const CODEX_LOGIN_COMMAND = 'cumora agent computer --codex-login'
+export const CODEX_MIGRATE_COMMAND = 'cumora agent computer --migrate-codex-sessions'
+export const CODEX_RUNTIME_CONFIG_ARGS = [
+ '-c', 'memories.generate_memories=false',
+ '-c', 'memories.use_memories=false',
+]
+
+export function codexRuntimeHome(): string {
+ return join(homedir(), '.cumora', 'codex-runtime')
+}
+
+interface SharedAuth { source: string; fileId: string }
+let sharingFailureNoted = false
+
+function fileId(info: BigIntStats): string { return `${info.dev}:${info.ino}` }
+
+function authFileText(path: string): string | null {
+ try { return readFileSync(path, 'utf8') }
+ catch (err) {
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null
+ throw err
+ }
+}
+
+/** Share auth.json in place, retaining ownership information across daemon restarts. */
+function syncSharedAuth(home: string, sourceHome?: string): void {
+ const target = join(home, 'auth.json')
+ const marker = join(home, 'auth.shared.json')
+ const text = authFileText(marker)
+ let shared: SharedAuth | null = null
+ if (text !== null) {
+ try { shared = JSON.parse(text) }
+ catch { throw new Error(`Invalid Codex authentication link metadata: ${marker}`) }
+ if (!shared || typeof shared.source !== 'string' || !isAbsolute(shared.source)
+ || typeof shared.fileId !== 'string' || !/^\d+:\d+$/.test(shared.fileId)) {
+ throw new Error(`Invalid Codex authentication link metadata: ${marker}`)
+ }
+ }
+ const current = lstatSync(target, { bigint: true, throwIfNoEntry: false })
+ if (current && (!shared || fileId(current) !== shared.fileId)) {
+ // An independently configured runtime login always takes precedence.
+ if (shared) rmSync(marker, { force: true })
+ return
+ }
+ const source = sourceHome && relative(sourceHome, home) !== ''
+ ? join(resolve(sourceHome), 'auth.json') : shared?.source
+ if (!source) return
+ const original = statSync(source, { bigint: true, throwIfNoEntry: false })
+ if (original && !original.isFile()) throw new Error(`Codex authentication source is not a file: ${source}`)
+ if (current && original && fileId(current) === fileId(original)
+ && (shared?.source === source || relative(realpathSync(source), realpathSync(target)) === '')) return
+ if (current) rmSync(target)
+ let linkedId = shared?.fileId
+ if (original) {
+ try { linkSync(realpathSync(source), target) }
+ catch (err) {
+ if ((err as NodeJS.ErrnoException).code === 'EEXIST') return
+ // shortcut: hard links require one volume; use separate login on other filesystems.
+ if (!sharingFailureNoted) {
+ sharingFailureNoted = true
+ console.warn(`[codex] cannot share the personal login (${(err as NodeJS.ErrnoException).code ?? 'filesystem error'}); run ${CODEX_LOGIN_COMMAND} to sign in separately.`)
+ }
+ return
+ }
+ linkedId = fileId(lstatSync(target, { bigint: true }))
+ }
+ if (!linkedId || (shared?.source === source && shared.fileId === linkedId)) return
+ const temporary = `${marker}.${randomUUID()}.tmp`
+ try {
+ writeFileSync(temporary, JSON.stringify({ source, fileId: linkedId }), { flag: 'wx', mode: 0o600 })
+ renameSync(temporary, marker)
+ } catch (err) {
+ const linked = lstatSync(target, { bigint: true, throwIfNoEntry: false })
+ if (linked && fileId(linked) === linkedId) rmSync(target)
+ throw err
+ } finally { rmSync(temporary, { force: true }) }
+}
+
+/** Idle app-server processes must reload after login, logout or token rotation. */
+export function codexAuthFingerprint(home = codexRuntimeHome()): string | null | undefined {
+ syncSharedAuth(home)
+ const text = authFileText(join(home, 'auth.json'))
+ if (text === null) return null
+ // Codex writes credentials in place; a partial write is not an account change.
+ try { JSON.parse(text) } catch { return undefined }
+ return createHash('sha256').update(text).digest('hex')
+}
+
+/** Only Codex children get this environment; other engines keep their homes. */
+export function codexRuntimeEnv(env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
+ const home = codexRuntimeHome()
+ mkdirSync(home, { recursive: true, mode: 0o700 })
+ syncSharedAuth(home, env.CODEX_HOME || join(homedir(), '.codex'))
+ return { ...env, CODEX_HOME: home, CODEX_SQLITE_HOME: home }
+}
diff --git a/server/src/agents/computer/codex-session-migration.ts b/server/src/agents/computer/codex-session-migration.ts
new file mode 100644
index 0000000..b00885f
--- /dev/null
+++ b/server/src/agents/computer/codex-session-migration.ts
@@ -0,0 +1,247 @@
+import { randomUUID } from 'node:crypto'
+import { createReadStream, createWriteStream } from 'node:fs'
+import { link, mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'
+import { homedir } from 'node:os'
+import { basename, dirname, join, relative, resolve, sep } from 'node:path'
+import { createInterface } from 'node:readline'
+import { Readable } from 'node:stream'
+import { pipeline } from 'node:stream/promises'
+import { decompress } from 'fzstd'
+import { CODEX_SESSION_SCOPE, codexRuntimeHome } from './codex-runtime.js'
+import { EngineSessionStore } from './session-store.js'
+
+function missingAsNull(err: NodeJS.ErrnoException): null {
+ if (err.code !== 'ENOENT') throw err
+ return null
+}
+
+async function entries(path: string, recursive = true): Promise<string[]> {
+ return await readdir(path, { recursive }).catch(missingAsNull) ?? []
+}
+
+interface Rollout {
+ path: string
+ timestamp: string
+ threadId: string
+ rolloutId: string
+ endByteOffset?: number
+}
+
+interface SessionMetadata {
+ id: string
+ history_mode?: 'legacy' | 'paginated'
+ history_base?: { thread_id: string; end_ordinal_exclusive: number; end_byte_offset: number } | null
+}
+
+const uuid = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
+const rolloutName = new RegExp(`^rollout-(\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2})-(${uuid})(?:_(${uuid}))?\\.jsonl(?:\\.zst)?$`, 'i')
+
+async function rolloutsIn(home: string): Promise<Rollout[]> {
+ const rollouts = new Map<string, Rollout>()
+ for (const directory of ['sessions', 'archived_sessions']) {
+ for (const entry of await entries(join(home, directory))) {
+ const match = rolloutName.exec(basename(entry))
+ if (!match) continue
+ const path = join(directory, entry)
+ const key = path.replace(/\.zst$/, '')
+ // Codex prefers the plain representation while compression publishes its replacement.
+ if (!rollouts.has(key) || !path.endsWith('.zst')) {
+ rollouts.set(key, { path, timestamp: match[1], threadId: match[2], rolloutId: match[3] ?? match[2] })
+ }
+ }
+ }
+ return [...rollouts.values()]
+}
+
+async function rolloutMetadata(path: string, minimumBytes = 0): Promise<SessionMetadata> {
+ const bytes = path.endsWith('.zst') ? decompress(await readFile(path)) : null
+ if (minimumBytes > 0 && minimumBytes > (bytes?.byteLength ?? (await stat(path)).size)) {
+ throw new Error(`history_base extends beyond source rollout ${path}`)
+ }
+ if (minimumBytes > 0) {
+ let lastByte = bytes?.[minimumBytes - 1]
+ if (!bytes) {
+ const file = await open(path, 'r')
+ try {
+ const buffer = Buffer.alloc(1)
+ await file.read(buffer, 0, 1, minimumBytes - 1)
+ lastByte = buffer[0]
+ } finally { await file.close() }
+ }
+ if (lastByte !== 10) throw new Error(`history_base does not end at a complete record in ${path}`)
+ }
+ const input = bytes ? Readable.from([bytes]) : createReadStream(path, { encoding: 'utf8' })
+ const lines = createInterface({ input, crlfDelay: Infinity })
+ try {
+ for await (const line of lines) {
+ let metadata
+ try { metadata = JSON.parse(line) } catch { continue }
+ if (metadata?.type === 'session_meta' && typeof metadata.payload?.id === 'string') {
+ if (metadata.payload.history_mode && !['legacy', 'paginated'].includes(metadata.payload.history_mode)) {
+ throw new Error(`unsupported history mode in ${path}`)
+ }
+ return metadata.payload
+ }
+ if (metadata?.type === 'response_item') break
+ }
+ throw new Error(`rollout has no readable session metadata: ${path}`)
+ } finally {
+ lines.close()
+ input.destroy()
+ }
+}
+
+async function selectedRollout(id: string, home: string, rollouts: Rollout[]): Promise<Rollout> {
+ const candidates = rollouts.filter(rollout => rollout.threadId === id)
+ if (!candidates.length) throw new Error(`its rollout is unavailable in ${home}`)
+ const sqliteHome = process.env.CODEX_SQLITE_HOME || home
+ const databases = (await entries(sqliteHome, false)).filter(path => /^state_\d+\.sqlite$/.test(path))
+ .sort((a, b) => Number(b.match(/\d+/)![0]) - Number(a.match(/\d+/)![0]))
+ let selected: Rollout | undefined
+ if (databases.length) {
+ // Read only the selected path; never migrate personal database rows.
+ const sqliteModule = 'node:sqlite'
+ let sqlite
+ try { sqlite = await import(sqliteModule) } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== 'ERR_UNKNOWN_BUILTIN_MODULE') throw err
+ throw new Error('reading Codex\'s selected rollout from SQLite requires Node.js 22.13 or newer; retry this one-time migration with a newer Node.js')
+ }
+ const database = new sqlite.DatabaseSync(join(sqliteHome, databases[0]), { readOnly: true })
+ try {
+ const row = database.prepare('SELECT rollout_path FROM threads WHERE id = ?').get(id)
+ if (row) {
+ const path = relative(resolve(home), resolve(String(row.rollout_path))).replace(/\.zst$/, '')
+ selected = candidates.find(rollout => rollout.path.replace(/\.zst$/, '') === path)
+ if (!selected) throw new Error(`the rollout selected by Codex's database is unavailable: ${row.rollout_path}`)
+ }
+ } finally { database.close() }
+ }
+ // Match Codex's filesystem fallback, including its same-second rollout-ID tie-breaker.
+ selected ??= candidates.filter(rollout => rollout.path.startsWith(`sessions${sep}`))
+ .sort((a, b) => b.timestamp.localeCompare(a.timestamp) || b.rolloutId.localeCompare(a.rolloutId))[0]
+ if (!selected || selected.path.startsWith('archived_sessions')) {
+ throw new Error(`thread is archived in ${home}; run \`codex unarchive ${id}\` with CODEX_HOME set to that home, then retry migration`)
+ }
+ return selected
+}
+
+async function rolloutHistory(current: Rollout, home: string, rollouts: Rollout[]): Promise<Rollout[]> {
+ const history: Rollout[] = []
+ const seen = new Set<string>()
+ for (;;) {
+ if (seen.has(current.rolloutId)) throw new Error(`cyclic history_base at ${current.path}`)
+ seen.add(current.rolloutId)
+ const metadata = await rolloutMetadata(join(home, current.path), current.endByteOffset)
+ if (metadata.id !== current.threadId) throw new Error(`rollout belongs to another thread: ${current.path}`)
+ history.push(current)
+ const base = metadata.history_base
+ if (!base) return history.reverse()
+ if (metadata.history_mode !== 'paginated'
+ || !Number.isSafeInteger(base.end_ordinal_exclusive) || base.end_ordinal_exclusive < 1
+ || !Number.isSafeInteger(base.end_byte_offset) || base.end_byte_offset < 1) {
+ throw new Error(`invalid history_base in ${current.path}`)
+ }
+ const sources = rollouts.filter(rollout => rollout.rolloutId === base.thread_id)
+ if (sources.length !== 1) {
+ throw new Error(`${sources.length ? 'ambiguous' : 'missing'} source rollout ${base.thread_id} referenced by ${current.path}`)
+ }
+ current = { ...sources[0], endByteOffset: base.end_byte_offset }
+ }
+}
+
+/** Publish complete files without truncating a rollout another agent already uses. */
+async function copyRollout(rollout: Rollout, sourceHome: string, destinationHome: string): Promise<void> {
+ const source = join(sourceHome, rollout.path)
+ const destination = join(destinationHome, rollout.endByteOffset ? rollout.path.replace(/\.zst$/, '') : rollout.path)
+ await mkdir(dirname(destination), { recursive: true, mode: 0o700 })
+ const temporary = `${destination}.${randomUUID()}.tmp${destination.endsWith('.zst') ? '.zst' : ''}`
+ try {
+ const input = source.endsWith('.zst') && rollout.endByteOffset
+ ? Readable.from([decompress(await readFile(source)).subarray(0, rollout.endByteOffset)])
+ : createReadStream(source, { end: rollout.endByteOffset ? rollout.endByteOffset - 1 : undefined })
+ await pipeline(input, createWriteStream(temporary, { flags: 'wx', mode: 0o600 }))
+ const metadata = await rolloutMetadata(temporary, rollout.endByteOffset)
+ if (metadata.id !== rollout.threadId) throw new Error(`copied rollout belongs to another thread: ${source}`)
+ try { await link(temporary, destination) }
+ catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err
+ const requiredBytes = rollout.endByteOffset ?? (temporary.endsWith('.zst')
+ ? decompress(await readFile(temporary)).byteLength
+ : (await stat(temporary)).size)
+ const existing = await rolloutMetadata(destination, requiredBytes)
+ if (existing.id !== rollout.threadId) throw new Error(`destination rollout belongs to another thread: ${destination}`)
+ }
+ } finally {
+ await rm(temporary, { force: true }).catch(() => {})
+ }
+}
+
+/** Copy an agent's referenced rollout before switching its session pointer.
+ * No legacy pointer means there is nothing to migrate (including new users). */
+export async function migrateCodexSession(
+ agentId: string,
+ sourceHome = process.env.CODEX_HOME || join(homedir(), '.codex'),
+ sessionsDir = join(homedir(), '.cumora', 'sessions'),
+ destinationHome = codexRuntimeHome(),
+): Promise<boolean> {
+ const legacy = join(sessionsDir, agentId, 'codex.session')
+ const store = new EngineSessionStore(sessionsDir, agentId, 'codex', CODEX_SESSION_SCOPE)
+ let id = ''
+ try {
+ if (!await stat(legacy).catch(missingAsNull)) return false
+ // A read error is not an absent pointer: never overwrite unreadable state.
+ const runtime = await readFile(store.sessionFile, 'utf8').catch(missingAsNull)
+ if (runtime?.trim()) {
+ await rename(legacy, `${legacy}.migrated`).catch(async () => {
+ await rm(legacy, { force: true }).catch(() => {})
+ })
+ return false
+ }
+ id = (await readFile(legacy, 'utf8')).trim()
+ if (id) {
+ if (resolve(sourceHome) === resolve(destinationHome)) throw new Error('source and destination Codex homes are the same')
+ const rollouts = await rolloutsIn(sourceHome)
+ const current = await selectedRollout(id, sourceHome, rollouts)
+ const history = await rolloutHistory(current, sourceHome, rollouts)
+ for (const rollout of history) await copyRollout(rollout, sourceHome, destinationHome)
+ // Migration must report pointer-write failures instead of starting fresh.
+ const temporary = `${store.sessionFile}.${randomUUID()}.migrating`
+ try {
+ await writeFile(temporary, `${id}\n`, { mode: 0o600, flag: 'wx' })
+ try { await link(temporary, store.sessionFile) }
+ catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err
+ if (!(await readFile(store.sessionFile, 'utf8')).trim()) throw err
+ return false
+ }
+ } finally { await rm(temporary, { force: true }).catch(() => {}) }
+ }
+ await rename(legacy, `${legacy}.migrated`).catch(missingAsNull)
+ return !!id
+ } catch (err) {
+ throw new Error(`Cannot migrate Codex ${id ? `thread ${id}` : 'session'} for ${agentId}: ${err instanceof Error ? err.message : String(err)}. The old session pointer has been preserved.`, { cause: err })
+ }
+}
+
+/** Manual retry for all saved agents. Daemon startup migrates them individually
+ * so one unavailable rollout cannot stop other agents from being hosted. */
+export async function migrateCodexSessions(
+ sourceHome?: string,
+ sessionsDir = join(homedir(), '.cumora', 'sessions'),
+ destinationHome?: string,
+): Promise<string[]> {
+ const pointers = (await entries(sessionsDir))
+ .filter(path => basename(path) === 'codex.session')
+ const migrated: string[] = []
+ const failures: Error[] = []
+ for (const pointer of pointers) {
+ const agentId = basename(dirname(pointer))
+ try {
+ if (await migrateCodexSession(agentId, sourceHome, sessionsDir, destinationHome)) migrated.push(agentId)
+ } catch (err) { failures.push(err instanceof Error ? err : new Error(String(err))) }
+ }
+ if (failures.length) {
+ throw new AggregateError(failures, `Migrated ${migrated.length} Codex session(s)${migrated.length ? ` (${migrated.join(', ')})` : ''} to ${destinationHome ?? codexRuntimeHome()}. Personal Codex data was left in place; failed ${failures.length}:\n${failures.map(err => err.message).join('\n')}`)
+ }
+ return migrated
+}
diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.ts
index ae88e25..4fedba9 100644
--- a/server/src/agents/computer/daemon.ts
+++ b/server/src/agents/computer/daemon.ts
@@ -50,8 +50,10 @@ 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, engineFailureOf, type DetectedEngineSnapshot, type EngineHopReport, type EngineId, type EngineRunResult, type EngineSession, type EngineUsage, enrichDetectedEngines, evaluateRunnableEngines, getAdapter, runEngineDoctor, type RunnableEngineEvaluation, snapshotDetectedEngines } from './engine.js'
+import { allowUnsandboxedByoa, classifyEngineFailure, detectEnginesWithStatus, ENGINE_IDS, engineFailureOf, type DetectedEngineSnapshot, type EngineHopReport, type EngineId, type EngineRunResult, type EngineSession, type EngineUsage, enrichDetectedEngines, evaluateRunnableEngines, getAdapter, loginCodexRuntime, runEngineDoctor, type RunnableEngineEvaluation, snapshotDetectedEngines } from './engine.js'
import { EngineSessionStore, sessionIdPreview } from './session-store.js'
+import { CODEX_LOGIN_COMMAND, CODEX_MIGRATE_COMMAND, CODEX_SESSION_SCOPE, codexRuntimeHome } from './codex-runtime.js'
+import { migrateCodexSession, migrateCodexSessions } from './codex-session-migration.js'
import { runWithSessionRecovery } from './session-recovery.js'
export { conversationHeader }
@@ -582,6 +584,7 @@ function parseArgs(argv: string[]): {
pair?: string; server?: string; engine?: string; provider?: string
installService?: boolean; uninstallService?: boolean; restart?: boolean; stop?: boolean
status?: boolean; logs?: boolean; version?: boolean; doctor?: boolean; help?: boolean
+ codexLogin?: boolean; migrateCodexSessions?: boolean
} {
const out: ReturnType<typeof parseArgs> = {}
for (let i = 0; i < argv.length; i++) {
@@ -601,6 +604,8 @@ function parseArgs(argv: string[]): {
else if (argv[i] === '--status') out.status = true
else if (argv[i] === '--logs') out.logs = true
else if (argv[i] === '--doctor' || argv[i] === 'doctor') out.doctor = true
+ else if (argv[i] === '--codex-login') out.codexLogin = true
+ else if (argv[i] === '--migrate-codex-sessions') out.migrateCodexSessions = true
else if (argv[i] === '--version' || argv[i] === '-v') out.version = true
}
return out
@@ -668,6 +673,18 @@ async function runtimeGet<T>(
} catch { return null }
}
+async function failureConversationIds(serverUrl: string, token: string, conversationId: string | null): Promise<string[]> {
+ if (conversationId) return [conversationId]
+ // A diagnostic lookup must not advance the agent's inbox freshness baseline.
+ const inbox = await runtimeGet<RuntimeInboxResponse>(serverUrl, '/inbox?probe=1', token)
+ const ids = new Set<string>()
+ for (const row of inbox?.rows ?? []) {
+ if (typeof row.conversation_id === 'string' && row.conversation_id) ids.add(row.conversation_id)
+ if (ids.size >= 5) break
+ }
+ return [...ids]
+}
+
/** Should this 20s fallback tick actually drain the inbox?
*
* Yes when the wake-stream is not provably alive: never connected, or silent
@@ -801,14 +818,14 @@ export function authFailureHint(engine: EngineId, detail: string): string {
if (POISONED_BODY_RE.test(detail)) {
return 'A malformed character (a split emoji) had poisoned the agent\'s session. It has been reset automatically — just wake the agent again.'
}
- if (!/(auth|login|token|quota|credit|billing|subscription|rate limit|usage limit|api key)/i.test(detail)) {
+ if (classifyEngineFailure(detail) !== 'authentication' && !/(auth|login|token|quota|credit|billing|subscription|rate limit|usage limit|api key)/i.test(detail)) {
return 'Check the daemon terminal for details, then wake the agent again.'
}
if (engine === 'claude') {
return 'Open Claude Code on that computer and sign in, refresh quota, or add credits, then wake the agent again.'
}
if (engine === 'codex') {
- return 'Open Codex on that computer and refresh its login or quota, then wake the agent again.'
+ return `Run \`${CODEX_LOGIN_COMMAND}\` on that computer to sign in to Cumora's isolated Codex runtime (or check the account quota), then wake the agent again.`
}
if (engine === 'grok') {
return 'Open Grok Build on that computer and run `grok login`, or set XAI_API_KEY, then wake the agent again.'
@@ -843,7 +860,7 @@ function missingEngineMessage(): string {
'',
'Secure default — install and sign in to at least one of:',
' - Claude Code: install the `claude` CLI, then run `claude` once to sign in',
- ' - Codex: install the `codex` CLI, then run `codex` once to sign in',
+ ` - Codex: install the \`codex\` CLI, then run \`${CODEX_LOGIN_COMMAND}\``,
'',
'Unsandboxed compatibility engines (explicit opt-in required):',
' - Grok Build: install the `grok` CLI, then run `grok login` once',
@@ -917,6 +934,8 @@ function helpText(): string {
' Cumora -> You -> Computers -> Add a computer)',
' --server <url> Cumora server URL (default: ' + DEFAULT_SERVER + ')',
' --engine <id> force an engine: ' + ENGINE_IDS.join(' | ') + '',
+ ' --codex-login sign in to Cumora\'s isolated Codex runtime',
+ ' --migrate-codex-sessions copy existing Cumora Codex threads into that runtime',
'',
'Background service:',
' --install-service install + start the background supervisor',
@@ -1860,7 +1879,8 @@ export class AgentRunner {
// The profile is a third dimension of session identity alongside agent and
// engine: a different endpoint/account owns a different transcript, so its
// session id must never be offered to another profile's provider.
- this.sessionStore = new EngineSessionStore(SESSIONS_DIR, agent.id, engine, providerProfileFingerprint(provider) || undefined)
+ this.sessionStore = new EngineSessionStore(SESSIONS_DIR, agent.id, engine,
+ engine === 'codex' ? CODEX_SESSION_SCOPE : providerProfileFingerprint(provider) || undefined)
this.adapter = getAdapter(engine)
}
@@ -2324,7 +2344,7 @@ export class AgentRunner {
})
}
const hint = authFailureHint(this.adapter.id, args.error)
- const conversationIds = await this.failureConversationIds(args.token, args.conversationId)
+ const conversationIds = await failureConversationIds(this.cfg.serverUrl, args.token, args.conversationId)
await Promise.all(conversationIds.map((conversationId) => runtimeBest(this.cfg.serverUrl, '/notices', args.token, {
conversationId,
agentId: this.agent.id,
@@ -2335,20 +2355,6 @@ export class AgentRunner {
})))
}
- private async failureConversationIds(token: string, conversationId: string | null): Promise<string[]> {
- if (conversationId) return [conversationId]
- // PROBE: we're only looking up convo ids to notify of an engine failure —
- // we don't show these messages to the agent. Use ?probe=1 so the server
- // does NOT advance the freshness-preflight baseline for this read.
- const inbox = await runtimeGet<RuntimeInboxResponse>(this.cfg.serverUrl, '/inbox?probe=1', token)
- const ids = new Set<string>()
- for (const row of inbox?.rows ?? []) {
- if (typeof row.conversation_id === 'string' && row.conversation_id) ids.add(row.conversation_id)
- if (ids.size >= 5) break
- }
- return [...ids]
- }
-
/** Preload global + current-project memory indexes. Existing
* `memory/MEMORY.md` stays GLOBAL; project work lives under
* `memory/projects/<id>/MEMORY.md`. A no-project wake injects global
@@ -3496,6 +3502,7 @@ async function doRun(serverOverride?: string): Promise<void> {
}
const runners = new Map<string, AgentRunner>()
+ const codexMigrationFailures = new Map<string, { message: string; reported: Set<string>; token: string; tokenExpiresAt: number }>()
const engineInventoryStabilizer = new EngineInventoryStabilizer()
const syncOnce = async (): Promise<void> => {
@@ -3540,6 +3547,46 @@ async function doRun(serverOverride?: string): Promise<void> {
runners.delete(agent.id)
await existing.stop({ forceEngine: true })
}
+ if (engine === 'codex') {
+ try {
+ // Migrate before creating a runner or broker. A missing transcript
+ // pauses only this agent; retry on the next sync without log spam.
+ await migrateCodexSession(agent.id)
+ codexMigrationFailures.delete(agent.id)
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err)
+ const remedy = `Restore the rollout in the original Codex home, or run \`${CODEX_MIGRATE_COMMAND}\` with CODEX_HOME set to that home. Migration retries automatically.`
+ let failure = codexMigrationFailures.get(agent.id)
+ if (!failure || failure.message !== message) {
+ failure = { message, reported: new Set(), token: '', tokenExpiresAt: 0 }
+ codexMigrationFailures.set(agent.id, failure)
+ console.error(`[computer] ${agent.id} paused: ${message} ${remedy}`)
+ }
+ try {
+ if (!failure.token || Date.now() >= failure.tokenExpiresAt - TOKEN_REFRESH_SKEW_MS) {
+ const { token, expiresInSeconds } = await api<{ token: string; expiresInSeconds: number }>(cfg.serverUrl, `/api/agents/${agent.id}/runtime-token`, {
+ method: 'POST', headers: { Authorization: `Bearer ${cfg.deviceToken}` },
+ body: JSON.stringify({ providerProfile: agent.providerProfile ?? null }),
+ })
+ failure.token = token
+ failure.tokenExpiresAt = Date.now() + expiresInSeconds * 1000
+ }
+ const { token, reported } = failure
+ const conversationIds = await failureConversationIds(cfg.serverUrl, token, null)
+ await Promise.all(conversationIds.filter(id => !reported.has(id)).map(async conversationId => {
+ const result = await runtimeBest(cfg.serverUrl, '/notices', token, {
+ conversationId,
+ noticeKind: 'byoa_engine_failed',
+ text: `${agent.name} is paused because its Codex session could not be migrated: ${conciseError(message).split(homedir()).join('~')}\n${remedy}`,
+ dedupeKey: `codex_migration_failed:${agent.id}:${conversationId}:${hashText(message)}`,
+ dedupeTtlSec: 900,
+ })
+ if (result !== null) reported.add(conversationId)
+ }))
+ } catch { /* Retry notification on the next sync without blocking other agents. */ }
+ continue
+ }
+ }
const runner = new AgentRunner(cfg, agent, engine, provider)
runners.set(agent.id, runner)
console.log(`[computer] hosting agent ${agent.name} (${agent.id}) on ${engine}`)
@@ -3547,6 +3594,9 @@ async function doRun(serverOverride?: string): Promise<void> {
}
// Agents removed from this computer: stop their runners.
const live = new Set(agents.map((a) => a.id))
+ for (const id of codexMigrationFailures.keys()) {
+ if (!live.has(id)) codexMigrationFailures.delete(id)
+ }
for (const [id, runner] of runners) {
if (!live.has(id)) {
runners.delete(id)
@@ -4211,6 +4261,7 @@ export async function restartService(hooks: RestartServiceHooks = {}): Promise<v
export const ONE_SHOT_FLAGS = [
'stop', 'status', 'restart', 'logs', 'version', 'install-service',
'uninstall-service', 'pair', 'doctor', 'provider', 'help',
+ 'codex-login', 'migrate-codex-sessions',
] as const
const ONE_SHOT_FLAG_RE = new RegExp(`--(?:${ONE_SHOT_FLAGS.join('|')})\\b`)
@@ -4613,7 +4664,9 @@ async function runDoctor(providerId?: string): Promise<void> {
// The binary is not always the engine id — cursor ships `cursor-agent`,
// antigravity ships `agy`. missingEngineMessage() in this file gets that
// right; this line used to contradict it.
- console.log(` install the \`${getAdapter(r.id)?.bin ?? r.id}\` CLI and run it once to sign in, then re-run --doctor\n`)
+ console.log(r.id === 'codex'
+ ? ` install the \`codex\` CLI, run \`${CODEX_LOGIN_COMMAND}\`, then re-run --doctor\n`
+ : ` install the \`${getAdapter(r.id)?.bin ?? r.id}\` CLI and run it once to sign in, then re-run --doctor\n`)
continue
}
console.log(`● ${r.id} — ${r.path}`)
@@ -4675,6 +4728,12 @@ export async function runComputerDaemon(argv: string[]): Promise<void> {
const serverUrl = (args.server || DEFAULT_SERVER).replace(/\/+$/, '')
if (args.help) { console.log(helpText()); return }
if (args.version) { console.log(CURRENT_VERSION); return }
+ if (args.codexLogin) { await loginCodexRuntime(); return }
+ if (args.migrateCodexSessions) {
+ const agents = await migrateCodexSessions()
+ console.log(`Migrated ${agents.length} Codex session(s) to ${codexRuntimeHome()}${agents.length ? `: ${agents.join(', ')}` : ''}. Personal Codex data was left in place.`)
+ return
+ }
if (args.doctor) { await runDoctor(args.provider); return }
if (args.restart) { await restartService(); return }
if (args.stop) { await stopService(); return }
diff --git a/server/src/agents/computer/engine.ts b/server/src/agents/computer/engine.ts
index 9b64604..a533434 100644
--- a/server/src/agents/computer/engine.ts
+++ b/server/src/agents/computer/engine.ts
@@ -33,6 +33,7 @@ import { stripLoneSurrogates } from '../text-safety.js'
import { isCustomAnthropicEndpoint, readClaudeUserSettings, withClaudeUserSettingsEnv } from './claude-user-settings.js'
import { isCliVersionAtLeast, probeEngineVersion, probeLocalEngineVersionWithRetry, versionCommandInvocation } from './cli-version.js'
import { discoverEngineModelCatalog, type EngineModelCatalog } from './model-catalog.js'
+import { CODEX_RUNTIME_CONFIG_ARGS, codexAuthFingerprint, codexRuntimeEnv } from './codex-runtime.js'
const IS_WIN = process.platform === 'win32'
@@ -381,6 +382,24 @@ function resolveCodexSpawn(): CodexSpawn {
return { command: node, argsPrefix: [script], shell: false, wantsStdinPrompt: false }
}
+/** Interactive setup uses exactly the same home as every background call. */
+export async function loginCodexRuntime(): Promise<void> {
+ const bin = await resolveBinPath('codex')
+ if (!bin || !await probeLocalEngineVersionWithRetry('codex', bin)) {
+ throw new Error(bin
+ ? 'Codex CLI was found on PATH, but its version could not be verified. Check `codex --version`, then rerun `cumora agent computer --codex-login`.'
+ : 'Codex CLI is unavailable on PATH. Install it with `npm install -g @openai/codex`, then rerun `cumora agent computer --codex-login`.')
+ }
+ const { command, shell, argsPrefix } = resolveCodexSpawn()
+ return new Promise((resolve, reject) => {
+ const child = spawn(command, [...argsPrefix, 'login'], {
+ env: codexRuntimeEnv(), stdio: 'inherit', shell,
+ })
+ child.once('error', reject)
+ child.once('close', code => code === 0 ? resolve() : reject(new Error(`Codex login exited with code ${code}`)))
+ })
+}
+
export type EngineId = 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode' | 'pi' | 'gemini' | 'qwen' | 'antigravity' | 'zcode'
/** The pairable engine ids, in the daemon's default detection order. */
@@ -596,7 +615,7 @@ 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/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_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_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 {
@@ -1915,18 +1934,8 @@ export function noteCodexConfigRejection(err: string | undefined, onLog?: (line:
return true
}
-/** The `-c` sandbox profile without the `exec`-only tail, so the persistent
- * app-server path is confined by exactly the same profile as the one-shot path.
- * This is the set production has since run clean: zero config rejections across
- * every turn on 0.11.1 daemons. */
+/** Shared sandbox profile for exec, persistent sessions and wake probes. */
function codexSecureConfigOverrides(args: { home: string; env: NodeJS.ProcessEnv }, readOnly = false): string[] {
- const full = codexSecureExecArgs(args, readOnly)
- const exec = full.indexOf('exec')
- // Everything before `-a never exec …` is the config profile.
- return exec === -1 ? full : full.slice(0, Math.max(0, exec - 2))
-}
-
-function codexSecureExecArgs(args: { home: string; env: NodeJS.ProcessEnv }, readOnly = false): string[] {
const workspaceAccess = readOnly ? 'read' : 'write'
const filesystemEntries = [
'":minimal"="read"',
@@ -1975,7 +1984,11 @@ function codexSecureExecArgs(args: { home: string; env: NodeJS.ProcessEnv }, rea
const mcp = `mcp_servers.cumora={command=${tomlString(process.execPath)},args=[${tomlString(mcpShim)}],env={CUMORA_AGENT_IPC_DIR=${tomlString(ipcDir)}},required=true,enabled_tools=["cli"],default_tools_approval_mode="approve"}`
secureArgs.push('-c', mcp)
}
- return [...secureArgs, '-a', 'never', 'exec', '--ignore-user-config', '--ignore-rules']
+ return secureArgs
+}
+
+function codexSecureExecArgs(args: { home: string; env: NodeJS.ProcessEnv }, readOnly = false): string[] {
+ return [...codexSecureConfigOverrides(args, readOnly), '-a', 'never', 'exec', '--ignore-user-config', '--ignore-rules']
}
/** A persistent Codex session over the app-server JSON-RPC protocol
@@ -1987,6 +2000,8 @@ function codexSecureExecArgs(args: { home: string; env: NodeJS.ProcessEnv }, rea
* serially; each resolves on that turn's `turn/completed`. */
class CodexSession implements EngineSession {
private readonly child: ChildProcess
+ private readonly authHome: string
+ private readonly authFingerprint: string | null | undefined
private readonly onLog: (line: string) => void
private readonly onHopUsage?: (r: EngineHopReport) => void
/** Wall-clock when the CURRENT turn started (turn/start request sent), used to
@@ -2018,6 +2033,8 @@ class CodexSession implements EngineSession {
private turnStart = { input: 0, cached: 0, output: 0 }
constructor(bin: string, spawnArgs: string[], home: string, env: NodeJS.ProcessEnv, opts: EngineSessionArgs) {
+ this.authHome = env.CODEX_HOME!
+ this.authFingerprint = codexAuthFingerprint(this.authHome)
this.onLog = opts.onLog
this.onHopUsage = opts.onHopUsage
this.threadId = opts.resumeSessionId ?? null
@@ -2046,7 +2063,18 @@ class CodexSession implements EngineSession {
queueMicrotask(() => { this.initializeId = this.req('initialize', { clientInfo: { name: 'cumora-daemon', version: '1.0.0' }, capabilities: { experimentalApi: true } }) })
}
- get alive(): boolean { return !this.exited && this.child.stdin?.writable === true }
+ get alive(): boolean {
+ if (this.exited || this.child.stdin?.writable !== true) return false
+ if (!this.pending) {
+ const auth = codexAuthFingerprint(this.authHome)
+ if (auth !== undefined && auth !== this.authFingerprint) {
+ this.onLog('[codex] login changed; restarting the session with its saved thread')
+ void this.stop({ force: true })
+ return false
+ }
+ }
+ return true
+ }
get sessionId(): string | null { return this.threadId }
send(prompt: string): Promise<EngineRunResult> {
@@ -2265,38 +2293,23 @@ class CodexAdapter implements EngineAdapter {
readonly bin = 'codex'
classify(args: EngineClassifyArgs): Promise<EngineClassifyResult> {
- // Codex on a ChatGPT account can't pick an arbitrary small model
- // (`gpt-5-mini` is rejected), but it DOES accept `gpt-5.4-mini` — Cumora's
- // support tier — so that's the local cerebellum here. Cheap model, no big
- // brain, no cloud. Override with CUMORA_TRIAGE_MODEL if your codex auth has
- // a different small model.
+ // gpt-5.4-mini works with ChatGPT auth; arbitrary small API models do not.
const flags = allowUnsandboxedByoa() ? extraArgs('CUMORA_TRIAGE_ARGS') : []
- const model = ['--model', args.model || 'gpt-5.4-mini']
- const { command, shell, argsPrefix } = resolveCodexSpawn()
- const codexArgs = flags.length
- ? ['exec', ...flags, '-']
- : allowUnsandboxedByoa()
- ? ['exec', ...model, '--skip-git-repo-check', '-']
- : [...codexSecureExecArgs({ home: args.cwd, env: args.env }, true), ...model, '--skip-git-repo-check', '-']
- const argv = [...argsPrefix, ...codexArgs]
- return spawnCapture(command, argv, {
- cwd: args.cwd, env: args.env, signal: args.signal, onLog: args.onLog, shell,
- stdinText: args.prompt,
- })
+ return this.capture(args, flags.length ? flags : ['--model', args.model || 'gpt-5.4-mini', '--skip-git-repo-check'])
}
probe(args: EngineProbeArgs): Promise<EngineClassifyResult> {
- // 'small' → gpt-5.4-mini (the cerebellum); 'big' → omit --model so Codex uses
- // its default model. `exec` non-interactive, no bypass/sandbox flags needed
- // for a tool-free one-token reply.
+ // Omit --model for the big tier so Codex uses its configured default.
const model = args.tier === 'small' ? ['--model', triageModel('gpt-5.4-mini')] : []
+ return this.capture({ ...args, prompt: DOCTOR_PROMPT }, [...model, '--skip-git-repo-check'])
+ }
+
+ private capture(args: EngineClassifyArgs, flags: string[]): Promise<EngineClassifyResult> {
+ const env = codexRuntimeEnv(args.env)
const { command, shell, argsPrefix } = resolveCodexSpawn()
- const codexArgs = allowUnsandboxedByoa()
- ? ['exec', ...model, '--skip-git-repo-check', '-']
- : [...codexSecureExecArgs({ home: args.cwd, env: args.env }, true), ...model, '--skip-git-repo-check', '-']
- const argv = [...argsPrefix, ...codexArgs]
- return spawnCapture(command, argv, {
- cwd: args.cwd, env: args.env, signal: args.signal, shell, stdinText: DOCTOR_PROMPT,
+ const exec = allowUnsandboxedByoa() ? ['exec'] : codexSecureExecArgs({ home: args.cwd, env }, true)
+ return spawnCapture(command, [...argsPrefix, ...exec, '--ephemeral', ...flags, ...CODEX_RUNTIME_CONFIG_ARGS, '-'], {
+ cwd: args.cwd, env, signal: args.signal, onLog: args.onLog, shell, stdinText: args.prompt,
})
}
@@ -2305,12 +2318,12 @@ class CodexAdapter implements EngineAdapter {
// any of these is true, the wake path collapses to `codex exec ...` which
// probe() already covers — running the JSON-RPC probe would just add a false
// signal. Mark skipped and let doctor hide the line.
- if (!allowUnsandboxedByoa()
- || unsafeEngineArgs('CUMORA_CODEX_ARGS').length
+ if (unsafeEngineArgs('CUMORA_CODEX_ARGS').length
|| process.env.CUMORA_CODEX_NO_APP_SERVER === '1'
|| IS_WIN) {
return Promise.resolve({ ok: true, detail: '', skipped: true })
}
+ args = { ...args, env: codexRuntimeEnv(args.env) }
// The real wake spawns `codex app-server --listen stdio://` and drives a
// JSON-RPC handshake (initialize → thread/start). The realistic breaks here
// are: app-server subcommand removed/renamed; protocol field names changed
@@ -2330,7 +2343,8 @@ class CodexAdapter implements EngineAdapter {
try { child.stdin?.end() } catch { /* ignore */ }
void terminateEngineTree(child).then(() => resolve(r))
}
- const appServerArgs = [...argsPrefix, 'app-server', '--listen', 'stdio://']
+ const secure = allowUnsandboxedByoa() ? [] : codexSecureConfigOverrides({ home: args.cwd, env: args.env }, true)
+ const appServerArgs = [...argsPrefix, ...secure, ...CODEX_RUNTIME_CONFIG_ARGS, 'app-server', '--listen', 'stdio://']
const child = spawnEngineChild(command, appServerArgs, {
cwd: args.cwd, env: args.env, stdio: ['pipe', 'pipe', 'pipe'], shell,
})
@@ -2373,7 +2387,7 @@ class CodexAdapter implements EngineAdapter {
// params shape CodexSession uses — so a field-name break shows up.
writeRpc({ jsonrpc: '2.0', method: 'initialized', params: {} })
writeRpc({ jsonrpc: '2.0', id: threadId, method: 'thread/start',
- params: { cwd: args.cwd, ...codexThreadSecurityParams(), experimentalRawEvents: true } })
+ params: { cwd: args.cwd, ...codexThreadSecurityParams(), experimentalRawEvents: true, ephemeral: true } })
continue
}
if (initialized && !threadAcked && msg.id === threadId && msg.result) {
@@ -2408,58 +2422,63 @@ class CodexAdapter implements EngineAdapter {
// filesystem/network/environment profile and reaches Cumora only through
// local IPC. Historical full-access flags and argv overrides remain
// available exclusively behind the explicit compatibility opt-in.
+ args = { ...args, env: codexRuntimeEnv(args.env) }
const flags = unsafeEngineArgs('CUMORA_CODEX_ARGS')
const base = flags.length
? ['exec', ...flags]
: allowUnsandboxedByoa()
? ['exec', '--dangerously-bypass-approvals-and-sandbox', '--skip-git-repo-check']
: [...codexSecureExecArgs(args), '--skip-git-repo-check']
+ if (!base.includes('--json')) base.push('--json')
const model = args.model ? ['--model', args.model] : []
+ const resume = args.resumeSessionId ? ['resume', args.resumeSessionId] : []
const { command, shell, argsPrefix } = resolveCodexSpawn()
- return spawnEngine(command, [...argsPrefix, ...base, ...model, '-'], args, { shell, stdinText: args.prompt })
+ let sessionId = args.resumeSessionId ?? null
+ let usage: EngineUsage | undefined
+ let turnError: string | undefined
+ const started = Date.now()
+ return spawnEngine(command, [...argsPrefix, ...base, ...model, ...CODEX_RUNTIME_CONFIG_ARGS, ...resume, '-'], args, {
+ shell, stdinText: args.prompt,
+ onStdoutLine(line) {
+ let event
+ try { event = JSON.parse(line) } catch { return }
+ if (event?.type === 'thread.started' && typeof event.thread_id === 'string' && event.thread_id) sessionId = event.thread_id
+ if (event?.type === 'turn.failed') turnError = String(event.error?.message || 'codex turn failed')
+ if (event?.type !== 'turn.completed' || !event.usage) return
+ const { input_tokens: input, cached_input_tokens: cached = 0, output_tokens: output } = event.usage
+ if (![input, cached, output].every(value => typeof value === 'number' && Number.isFinite(value) && value >= 0)) return
+ usage = { input_tokens: Math.max(0, input - cached), cache_read_input_tokens: cached, output_tokens: output }
+ },
+ })
.then((res) => {
// 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)
- // `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)
+ if (usage && args.model && !turnError && res.exitCode === 0) {
+ try { args.onHopUsage?.({ model: args.model, usage, latencyMs: Date.now() - started, hopIndex: 1 }) }
+ catch { /* never break the run on a ledger error */ }
+ }
+ return classifyEngineResult({
+ ...res, sessionId, usage, model: args.model ?? res.model,
+ exitCode: turnError && res.exitCode === 0 ? 1 : res.exitCode,
+ error: res.error ?? turnError,
+ }, !!args.resumeSessionId)
})
}
startSession(args: EngineSessionArgs): EngineSession | null {
- // Escape hatches → fall back to one-shot `codex exec` (run()): a custom-args
- // override, an explicit opt-out, or Windows (JSON-RPC over a .cmd shell is
- // fragile; exec is the safe path there).
- //
- // This used to `return null` unless BYOA was explicitly unsandboxed, because
- // app-server has no equivalent to `exec --ignore-user-config`. The cost of
- // that was invisible in the code: with no persistent process every codex
- // turn is a fresh session, so agents answered each message with no memory of
- // the one before — what users reported as the agent not remembering the
- // previous exchange.
- //
- // `-c` are global flags and DO apply to app-server, so the filesystem,
- // network, environment and feature profile below is identical on both paths.
- // What app-server cannot exclude is a user's own ~/.codex adding EXTRA
- // mcp_servers — a narrower gap than losing every agent's continuity, on the
- // operator's own machine, with their own config. CUMORA_CODEX_NO_APP_SERVER=1
- // still opts out, and a failing session degrades to one-shot (see daemon.ts).
- if (unsafeEngineArgs('CUMORA_CODEX_ARGS').length) return null
- if (process.env.CUMORA_CODEX_NO_APP_SERVER === '1') return null
- if (IS_WIN) return null
+ // Windows .cmd transport, custom args and explicit opt-outs use exec resume.
+ if (unsafeEngineArgs('CUMORA_CODEX_ARGS').length
+ || process.env.CUMORA_CODEX_NO_APP_SERVER === '1'
+ || IS_WIN) return null
+ args = { ...args, env: codexRuntimeEnv(args.env) }
try { ensureGitRepoForCodex(args.home) }
catch (err) { args.onLog(`[codex] could not init git repo for app-server (${err instanceof Error ? err.message : String(err)}) — falling back to one-shot exec`); return null }
- // Standing prompt rides the thread's developerInstructions (see CodexSession),
- // approval/sandbox are set per-thread, so no global bypass flags are needed.
const { command, argsPrefix } = resolveCodexSpawn()
- // Confine the persistent process with the same profile the one-shot path
- // uses. `-c` are global flags and apply to app-server too, so filesystem,
- // network, environment and features are identical on both paths.
const secure = allowUnsandboxedByoa()
? []
: codexSecureConfigOverrides({ home: args.home, env: args.env })
- return new CodexSession(command, [...argsPrefix, ...secure, 'app-server', '--listen', 'stdio://'], args.home, args.env, args)
+ return new CodexSession(command, [...argsPrefix, ...secure, ...CODEX_RUNTIME_CONFIG_ARGS, 'app-server', '--listen', 'stdio://'], args.home, args.env, args)
}
}
diff --git a/server/src/agents/computer/model-catalog.ts b/server/src/agents/computer/model-catalog.ts
index d2827f4..7297a30 100644
--- a/server/src/agents/computer/model-catalog.ts
+++ b/server/src/agents/computer/model-catalog.ts
@@ -2,6 +2,7 @@ import { spawn } from 'node:child_process'
import type { EngineId } from './engine.js'
import { isCustomAnthropicEndpoint, readClaudeUserSettings, withClaudeUserSettingsEnv } from './claude-user-settings.js'
import { versionCommandInvocation } from './cli-version.js'
+import { CODEX_RUNTIME_CONFIG_ARGS, codexRuntimeEnv } from './codex-runtime.js'
export type ModelCatalogSource = 'protocol' | 'cli' | 'presets'
export type FastModelScope = 'agent' | 'computer' | 'unsupported'
@@ -320,12 +321,13 @@ interface CodexListItem {
isDefault?: unknown
}
-function discoverCodex(command: string): Promise<{ models: EngineModelOption[]; defaultModel: string | null } | null> {
+function discoverCodex(command: string, env: NodeJS.ProcessEnv): Promise<{ models: EngineModelOption[]; defaultModel: string | null } | null> {
return new Promise((resolve) => {
- const invocation = versionCommandInvocation(command, ['app-server', '--listen', 'stdio://'])
+ const invocation = versionCommandInvocation(command, [...CODEX_RUNTIME_CONFIG_ARGS, 'app-server', '--listen', 'stdio://'])
let child: ReturnType<typeof spawn>
try {
child = spawn(invocation.command, invocation.args, {
+ env: codexRuntimeEnv(env),
stdio: ['pipe', 'pipe', 'ignore'],
windowsHide: true,
windowsVerbatimArguments: invocation.windowsVerbatimArguments === true,
@@ -428,7 +430,7 @@ export async function discoverEngineModelCatalog(
}
}
} else if (id === 'codex') {
- const result = await discoverCodex(binPath)
+ const result = await discoverCodex(binPath, env)
if (result?.models.length) catalog = withPreset(id, result.models, 'protocol', result.defaultModel)
} else if (id === 'cursor') {
const models = parseListedModels(await runText(binPath, ['models']), 'cursor')
diff --git a/server/src/cli-bin.ts b/server/src/cli-bin.ts
index 0e0bddb..9c6b341 100644
--- a/server/src/cli-bin.ts
+++ b/server/src/cli-bin.ts
@@ -13,8 +13,13 @@ async function main() {
// BEFORE importing runCli / the DB + Redis clients so it never loads them
// (the daemon host has no DB/Redis access).
if (argv[0] === 'agent' && argv[1] === 'computer') {
- const { runComputerDaemon } = await import('./agents/computer/daemon.js')
- await runComputerDaemon(argv.slice(2))
+ try {
+ const { runComputerDaemon } = await import('./agents/computer/daemon.js')
+ await runComputerDaemon(argv.slice(2))
+ } catch (err) {
+ process.stderr.write(`error: ${err instanceof Error ? err.message : String(err)}\n`)
+ process.exitCode = 2
+ }
return
}