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
feat(byoa): discover models from configured providers (#347)
Strelizia2d1ec299b819
diff --git a/docs/BYOA.md b/docs/BYOA.mdindex b45a66c..add492b 100644--- a/docs/BYOA.md+++ b/docs/BYOA.md@@ -65,9 +65,10 @@ errors and `--doctor` also point to it. While authentication is linked, loggingin updates the shared personal credentials too. Use personal Codex to log outof the shared account. Account quota is shared. Codex still owns token refreshand 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.+An independent runtime `config.toml` takes precedence. Otherwise Cumora projects+the personal configuration's selected provider and model fields into the runtime.+App-server, discovery and secure `exec` use the same projection; secure `exec`+continues to ignore all other user configuration.Main threads resume after daemon restarts: macOS/Linux use app-server, whileWindows and app-server fallbacks use `exec --json` / `exec resume <thread-id>`.@@ -115,6 +116,80 @@ 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.+## Provider model catalogs++The model pickers follow each local engine's active provider connection. Claude+imports explicit `modelPicker.options` and Opus/Sonnet/Haiku/auxiliary model+mappings. Codex resolves its effective configuration through `config/read` and+projects only the selected connection, model and catalog fields into the+isolated runtime. An independent `~/.cumora/codex-runtime/config.toml` takes+precedence over personal Codex configuration. Personal hooks, MCP servers,+permissions, project configuration and conversation state are not imported.++An explicit engine picker or a successful native listing takes precedence over+a generic HTTP catalog. HTTP discovery fills in when that engine has no picker+or native result; it does not inflate an existing engine namespace. Claude+still includes its explicit default-model mappings, and Codex its explicit+model/catalog configuration. Explicit labels take precedence for display.+Choices are deduplicated by exact executable ID within the same engine and+provider connection. Display names do not affect model identity or the ID+submitted to the engine. Engine-specific aliases and context suffixes are+preserved; Cumora does not add or remove suffixes or resolve routing groups to+underlying models.++Discovery covers backend vendors through the engine that uses them:++| Engine | Catalog source |+| --- | --- |+| Claude Code | User picker and model mappings; HTTP fallback when no picker is declared |+| Codex | Native `model/list`, selected provider/model/catalog configuration; HTTP fallback without a native result |+| Grok, Cursor, OpenCode, Antigravity | Native `models` command |+| pi | Native `--list-models` command |+| Gemini | User `.gemini/settings.json` model definitions, aliases and default; `GEMINI_CLI_HOME` replaces the user home |+| Qwen | User `settings.json` declarations for the active auth protocol; `QWEN_HOME` is honored |+| ZCode | Enabled providers in `v2/config.json` and desktop `v2/provider_config.json`; `ZCODE_HOME` and `ZCODE_PROVIDER` are honored |+| Maka | The current ACP adapter does not expose model selection |++Native CLI commands resolve their own provider configuration and are re-read on+each rescan, with the daemon environment and a neutral working directory.+Gemini/Qwen configuration discovery reads user settings, not project settings or+enterprise policy layers. Qwen does not offer image-only/realtime-only routes+or models belonging to another auth protocol. Ambiguous Qwen IDs registered+against different endpoints/credentials are withheld because `--model` alone+cannot identify the intended route. ZCode uses its native ACP+`provider\model` selector, so equal model IDs from different providers remain+distinct. Custom provider model additions and deletions from the ZCode desktop+configuration take precedence over its legacy provider snapshot.+Explicitly disabled ZCode model rules also remove legacy builtin entries.++HTTP discovery uses only the configured API's standard models resource or an+explicit same-origin catalog URL, with the connection's own credentials. It+does not scan other endpoints or test models through inference. Requests have+a short timeout, a 2 MiB total response bound, at most eight pages and at most+1,024 choices. Credentials and connection details remain local.++Connection changes affect subsequent turns. Persistent sessions finish their+active turn and reload while idle; explicit agent/computer model pins still+win. Unreadable provider configuration pauses new secure turns instead of+falling back to a different account. Secure execution, auxiliary tasks and diagnostics receive the same+provider projection. For a known Claude/Codex connection, if a refresh fails,+the picker retains the previous+directory for that connection and reports it as stale. A successful empty+listing clears that listing's previous entries; explicit local declarations+remain. If configuration cannot establish the active connection, old choices+are withheld until it becomes readable. Native-only listings are not cached+under an unknown provider identity; a failed rescan therefore withholds their+old entries. Custom ID entry stays available where the engine supports it.++On Windows, structured provider settings bypass batch wrappers through a native+Codex executable or the resolved npm/pnpm JavaScript entry point. An arbitrary+wrapper without a direct entry point fails explicitly rather than expanding+percent sequences or modifying credential values through `cmd.exe`.++A catalog entry records configuration or a provider listing, not a successful+execution. Generic HTTP entries do not establish tool, context, reasoning or+native Fast Mode support. Native CLI capability metadata takes precedence.+## The Computer — the unifying host conceptRather than bolt BYOA on as a special case, **Computer** is a first-class@@ -301,7 +376,7 @@ interface EngineSession {| Concern | Claude Code | Codex CLI | Grok Build | Cursor Agent | OpenCode | pi | Gemini CLI | Qwen Code | Antigravity | ZCode || --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |-| Secure default | Claude Code ≥ 2.1.248 with `--restricted`; no Bash/PowerShell/web tools; host-home reads, command network, unsandboxed retry, and subprocess credentials are denied | Codex ≥ 0.138.0 with a custom permission profile: only minimal runtime reads plus the agent home; command network disabled; tool env allowlisted; user/project config, rules, hooks, apps, remote plugins, and multi-agent tools ignored or disabled | disabled | disabled | disabled | disabled | disabled | disabled | disabled | disabled |+| Secure default | Claude Code ≥ 2.1.248 with `--restricted` and sandboxed Bash; PowerShell/web tools, host-home reads, command network, unsandboxed retry, and subprocess credentials are denied | Codex ≥ 0.138.0 with a custom permission profile: only minimal runtime reads plus the agent home; command network disabled; tool env allowlisted; user/project config, rules, hooks, apps, remote plugins, and multi-agent tools ignored or disabled | disabled | disabled | disabled | disabled | disabled | disabled | disabled | disabled || Platform | macOS, Linux, WSL2; native Windows disabled because Claude's sandbox is unsupported there | macOS, Linux, WSL2, native Windows | compatibility opt-in only | compatibility opt-in only | compatibility opt-in only | compatibility opt-in only | compatibility opt-in only | compatibility opt-in only | compatibility opt-in only | compatibility opt-in only || Persistent session | secure default; `claude -p --input-format stream-json --output-format stream-json --verbose` | compatibility opt-in only; secure default uses one-shot `exec` | compatibility opt-in ACP | none | none | compatibility opt-in RPC | none | none — 0.22.3 has no stream-json INPUT mode | compatibility bidirectional stream-json | compatibility ACP via the `zcode-acp-server` bridge || Standing prompt | `--append-system-prompt-file <home>/.cumora-standing-prompt.md` | inlined into each secure one-shot wake | compatibility ACP `_meta.rules` | inlined | inlined | compatibility `--append-system-prompt` | inlined | inlined | inlined | inlined |@@ -366,9 +441,13 @@ crossing a vendor-specific deployment pin into the wrong namespace.The daemon advertises and schedules only engines for which it can impose afail-closed host boundary:-- Claude Code on macOS, Linux, and WSL2 runs in restricted mode with filesystem- isolation, an empty strict network allowlist, no Bash/PowerShell/web tools,- no unsandboxed retry, and an explicit deny list for every inherited+- Claude Code on macOS, Linux, and WSL2 runs in restricted mode with sandboxed+ Bash for local scripts, tests, and builds. Keep projects and build caches under+ the agent's `workspace/`; dependencies must already be available because command+ network access is denied. Cumora actions use the fixed MCP bridge, not a shell+ CLI. The policy retains filesystem isolation, an empty strict network allowlist,+ no PowerShell/web tools, no commands excluded from sandboxing, no unsandboxed+ retry, and an explicit deny list for every inheritedenvironment variable not needed by the fixed Cumora MCP bridge. Becauserestricted mode ignores user settings, the daemon imports a fixedseven-key allowlist from Claude's user settings into the trusted Claude@@ -384,7 +463,9 @@ fail-closed host boundary:`api.anthropic.com` is *not* treated as a custom provider, while a`ANTHROPIC_BASE_URL` that won't parse is (it fails toward "custom"). ClaudeCode 2.1.248 or newer is required. Linux/WSL2 also requires `bubblewrap` and- `socat`; a missing dependency fails the turn.+ `socat`; a missing dependency fails the turn. Sandbox availability also depends+ on the host environment; if initialization fails, the turn stops without+ disabling sandboxing.- Codex uses an isolated runtime home. Its one-shot fallback ignores userconfig and exec-policy rules. A custompermission profile permits minimal runtime reads and writes only under thediff --git a/server/src/__tests__/agents-computer-codex-runtime.test.ts b/server/src/__tests__/agents-computer-codex-runtime.test.tsindex 1fa9f8e..a6c8b2b 100644--- a/server/src/__tests__/agents-computer-codex-runtime.test.ts+++ b/server/src/__tests__/agents-computer-codex-runtime.test.ts@@ -13,6 +13,7 @@ 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'+import { codexProviderFingerprint, prepareCodexProvider } from '../agents/computer/codex-provider.js'const execFileAsync = promisify(execFile)const IS_WIN = process.platform === 'win32'@@ -48,6 +49,7 @@ if (process.argv.includes('--version')) {const m = JSON.parse(line)record(m)if (m.method === 'initialize') send({ id: m.id, result: {} })+ if (m.method === 'config/read') send({ id: m.id, result: { config: JSON.parse(process.env.CODEX_TEST_PROVIDER_CONFIG || '{}') } })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') {@@ -307,6 +309,100 @@ test('custom Codex arguments cannot re-enable native memory', async () => {}})+test('provider bootstrap reaches secure exec, triage, doctor and catalog without importing personal execution settings', async () => {+ await mkdir(source, { recursive: true })+ await writeFile(join(source, 'config.toml'), 'model_provider="fixture"\nmodel="auto/main"\n')+ const config = {+ model_provider: 'fixture', model: 'auto/main',+ model_providers: { fixture: { name: 'Fixture', base_url: 'http://127.0.0.1:1/v1', wire_api: 'responses',+ experimental_bearer_token: 'fixture-provider-secret', requires_openai_auth: false } },+ hooks: { command: 'do-not-import' }, mcp_servers: { unsafe: { command: 'do-not-import' } },+ permissions: { unsafe: true },+ }+ const env = { ...process.env, CODEX_TEST_PROVIDER_CONFIG: JSON.stringify(config),+ CUMORA_AGENT_IPC_DIR: join(root, 'ipc'), CUMORA_AGENT_MCP_SHIM: join(root, 'shim') }+ const adapter = getAdapter('codex')+ const signal = AbortSignal.timeout(10_000)+ assert.equal((await adapter.run({ home: root, env, prompt: 'hello', onLog() {}, signal })).exitCode, 0)+ 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, 'auto/main')+ assert.equal(catalog.defaultFastModel, null)+ assert.doesNotMatch(JSON.stringify(catalog), /fixture-provider-secret|127\.0\.0\.1/)+ const records = (await calls()).filter(call => call.argv?.includes('exec'))+ assert.equal(records.length, 3)+ for (const call of records) {+ assert.ok(call.argv.includes('model_provider="fixture"'))+ assert.ok(call.argv.includes('model="auto/main"'))+ assert.ok(call.argv.includes('--ignore-user-config'))+ assert.equal(call.argv.includes('gpt-5.4-mini'), false)+ assert.doesNotMatch(call.argv.join('\n'), /do-not-import|permissions\.unsafe/)+ assert.equal(call.home, codexRuntimeHome())+ }+ assert.ok((await calls()).filter(call => call.argv?.includes('app-server'))+ .some(call => call.argv.includes('model_provider="fixture"')))+})++test('independent runtime provider configuration wins and later configuration changes invalidate the projection', async () => {+ await mkdir(source, { recursive: true })+ await writeFile(join(source, 'config.toml'), 'model="personal/model"\n')+ await mkdir(destination, { recursive: true })+ await writeFile(join(destination, 'config.toml'), 'model="runtime/model"\n')+ const adapter = getAdapter('codex')+ const run = async (model: string) => adapter.run({+ home: root, env: { ...process.env, CODEX_TEST_PROVIDER_CONFIG: JSON.stringify({ model }),+ CUMORA_AGENT_IPC_DIR: join(root, 'ipc'), CUMORA_AGENT_MCP_SHIM: join(root, 'shim') },+ prompt: 'hello', onLog() {}, signal: AbortSignal.timeout(10_000),+ })+ assert.equal((await run('runtime/model')).exitCode, 0)+ const previousFingerprint = codexProviderFingerprint(process.env)+ await writeFile(join(destination, 'config.toml'), 'model="runtime/changed"\n')+ assert.notEqual(codexProviderFingerprint(process.env), previousFingerprint)+ assert.equal((await run('runtime/changed')).exitCode, 0)+ const records = await calls()+ assert.ok(records.filter(call => call.argv?.includes('app-server')).every(call => call.home === destination))+ assert.deepEqual(records.filter(call => call.argv?.includes('exec')).map(call =>+ call.argv.find((arg: string) => arg.startsWith('model='))), ['model="runtime/model"', 'model="runtime/changed"'])+})++test('agent-specific runtime plumbing does not duplicate Codex provider bootstrap', async () => {+ await mkdir(source, { recursive: true })+ await writeFile(join(source, 'config.toml'), 'model_provider="gateway"\n')+ const config = JSON.stringify({ model_provider: 'gateway', model: 'gateway/model', model_providers: { gateway: {+ name: 'Local gateway', base_url: 'https://gateway.invalid/v1', requires_openai_auth: false,+ env_http_headers: { 'x-agent-id': 'CUMORA_AGENT_ID' },+ } } })+ const env = (agent: string) => ({ ...process.env, CODEX_TEST_PROVIDER_CONFIG: config,+ CUMORA_AGENT_ID: agent, CUMORA_AGENT_IPC_DIR: join(root, agent, 'ipc'),+ CUMORA_AGENT_MCP_SHIM: join(root, agent, 'shim') })+ const first = env('first-agent')+ const second = env('second-agent')+ assert.notEqual(codexProviderFingerprint(first), codexProviderFingerprint(second))+ const providers = await Promise.all([prepareCodexProvider('codex', first), prepareCodexProvider('codex', second)])+ assert.deepEqual(providers.map(provider => provider.connection?.headers['x-agent-id']), ['first-agent', 'second-agent'])+ assert.equal((await calls()).filter(call => call.method === 'config/read').length, 1)+})++test('a provider change finishes the active Codex turn before reloading an idle session', { skip: IS_WIN }, async () => {+ await mkdir(source, { recursive: true })+ const file = join(source, 'config.toml')+ await writeFile(file, 'model="auto/main"\n')+ const env = { ...process.env, CODEX_TEST_PROVIDER_CONFIG: '{"model":"auto/main"}',+ CUMORA_AGENT_IPC_DIR: join(root, 'ipc'), CUMORA_AGENT_MCP_SHIM: join(root, 'shim') }+ await prepareCodexProvider('codex', env)+ const session = getAdapter('codex').startSession!({ home: root, env, onLog() {} })!+ assert.ok(session)+ try {+ const turn = session.send('complete the active turn')+ writeFileSync(file, 'model="auto/changed"\n')+ 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() }+})+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') }diff --git a/server/src/__tests__/agents-computer-engine-detect.test.ts b/server/src/__tests__/agents-computer-engine-detect.test.tsindex 30f17d2..dee4379 100644--- a/server/src/__tests__/agents-computer-engine-detect.test.ts+++ b/server/src/__tests__/agents-computer-engine-detect.test.ts@@ -102,7 +102,7 @@ test('listAgentsForComputer keeps an explicit model and pins CUMORA_DEFAULT_* whassert.equal(agents[4]?.engine, 'qwen')})-test('listAgentsForComputer prefers a reported local default without overriding an explicit pin', async () => {+test('listAgentsForComputer leaves local defaults dynamic without overriding an explicit pin', async () => {const catalog = {models: [{ id: 'provider/opus', label: 'Provider Opus' }],defaultModel: 'provider/opus',@@ -136,14 +136,33 @@ test('listAgentsForComputer prefers a reported local default without overridingconst agents = await registry.listAgentsForComputer('comp-1')assert.equal(agents[0]?.model, 'agent/pin')- assert.equal(agents[0]?.fastModel, 'provider/haiku')- assert.equal(agents[1]?.model, 'provider/opus')- assert.equal(agents[1]?.fastModel, 'provider/haiku')+ assert.equal(agents[0]?.fastModel, null)+ assert.equal(agents[1]?.model, null, 'the daemon resolves the current provider default at execution time')+ assert.equal(agents[1]?.fastModel, null)assert.equal(agents[2]?.model, null, 'custom provider with unnamed default must not inherit the deploy pin')- assert.equal(agents[2]?.fastModel, 'provider/haiku')+ assert.equal(agents[2]?.fastModel, null)assert.equal('detectedEngines' in (agents[1] ?? {}), false)})+test('provider defaults stay local for every engine while explicit computer pins win', async () => {+ const catalog = { models: [], defaultModel: 'auto/current', defaultFastModel: null,+ prefersLocalDefault: true, supportsCustom: true, fastModelScope: 'agent', source: 'protocol', trustedModels: true }+ for (const engine of ['codex', 'gemini', 'qwen', 'zcode']) {+ const computer = { availableEngines: [engine],+ detectedEngines: [{ id: engine, bin: engine, path: `/bin/${engine}`, modelCatalog: catalog }] }+ installPoolMock(({ sql }) => /FROM participants/.test(sql) ? { rows: [+ { id: 'dynamic', name: 'Dynamic', engine, model: null, fastModel: null, ...computer },+ { id: 'pinned', name: 'Pinned', engine, model: null, fastModel: null,+ engineDefaults: { [engine]: { model: 'auto/pin', fastModel: 'auto/small' } }, ...computer },+ ] } : { rows: [] })+ const agents = await registry.listAgentsForComputer('comp-1')+ assert.equal(agents[0]?.model, null, engine)+ assert.equal(agents[0]?.fastModel, null, engine)+ assert.equal(agents[1]?.model, 'auto/pin', engine)+ assert.equal(agents[1]?.fastModel, 'auto/small', engine)+ }+})+test('reportDetectedEngines keeps the previous default first when it is still installed', async () => {const calls = installPoolMock(({ sql }) => {if (/SELECT available_engines/.test(sql)) {diff --git a/server/src/__tests__/agents-computer-engine.test.ts b/server/src/__tests__/agents-computer-engine.test.tsindex e01152d..fa1d666 100644--- a/server/src/__tests__/agents-computer-engine.test.ts+++ b/server/src/__tests__/agents-computer-engine.test.ts@@ -4,6 +4,7 @@* Run: node --import tsx --test server/src/__tests__/agents-computer-engine.test.ts*/import assert from 'node:assert/strict'+import { writeFileSync } from 'node:fs'import { chmod, lstat, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import { delimiter, dirname, join } from 'node:path'@@ -20,6 +21,59 @@ const tempDirs: string[] = []// the child down — otherwise it outlives the test and the runner never exits.const liveSessions: Array<{ stop(): void | Promise<void> }> = []+test('Claude preserves an explicit model override and reloads changed providers after the active turn', async () => {+ const root = await mkdtemp(join(tmpdir(), 'cumora-claude-provider-refresh-'))+ tempDirs.push(root)+ const binDir = join(root, 'bin')+ const home = join(root, 'home')+ const configDir = join(root, 'config')+ await Promise.all([mkdir(binDir), mkdir(home), mkdir(configDir)])+ const file = join(configDir, 'settings.json')+ const saved = (endpoint: string) => JSON.stringify({+ model: 'auto/local[1m]', env: { ANTHROPIC_BASE_URL: endpoint },+ })+ await writeFile(file, saved('https://first.example.test'))+ await writeFakeCli(binDir, 'claude', `+if (process.argv.includes('--input-format')) {+ process.stdin.on('data', () => process.stdout.write(JSON.stringify({+ type: 'result', subtype: 'success', session_id: 'retained-thread', result: 'OK'+ }) + '\\n'))+} else {+ process.stdout.write(JSON.stringify({ argv: process.argv.slice(2) }) + '\\n')+}+`)+ setFakeCliPath(binDir)+ const env = secureClaudeEnv(root, { CLAUDE_CONFIG_DIR: configDir, ANTHROPIC_MODEL: 'explicit/main' })+ const adapter = getAdapter('claude')+ const probe = await adapter.probe({ cwd: home, env, tier: 'big', signal: AbortSignal.timeout(10_000) })+ const argv = JSON.parse(probe.text).argv as string[]+ assert.equal(argv[argv.indexOf('--model') + 1], 'explicit/main')+ const session = adapter.startSession!({ home, env, onLog() {} })!+ assert.ok(session)+ liveSessions.push(session)+ const turn = session.send('finish this turn')+ writeFileSync(file, saved('https://second.example.test'))+ assert.equal(session.alive, true)+ assert.equal((await turn).exitCode, 0)+ assert.equal(session.alive, false)+ assert.equal(session.sessionId, 'retained-thread')+})++test('temporarily unreadable Claude provider settings cannot fall through to a different account', async () => {+ const root = await mkdtemp(join(tmpdir(), 'cumora-claude-partial-settings-'))+ tempDirs.push(root)+ const configDir = join(root, 'config')+ const binDir = join(root, 'bin')+ await Promise.all([mkdir(configDir), mkdir(binDir)])+ await writeFile(join(configDir, 'settings.json'), '{partial gateway update')+ await writeFakeCli(binDir, 'claude', "process.stderr.write('fixture must not be invoked')")+ setFakeCliPath(binDir)+ await assert.rejects(getAdapter('claude').classify({+ cwd: root, env: secureClaudeEnv(root, { CLAUDE_CONFIG_DIR: configDir }),+ prompt: 'triage', signal: AbortSignal.timeout(10_000),+ }), /Cannot read Claude provider settings/)+})+function secureClaudeEnv(root: string, overrides: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv {const base: NodeJS.ProcessEnv = { ...process.env }// withClaudeUserSettingsEnv only imports a key from settings.json when thediff --git a/server/src/__tests__/agents-computer-model-catalog.test.ts b/server/src/__tests__/agents-computer-model-catalog.test.tsindex 1258bc1..2887e2e 100644--- a/server/src/__tests__/agents-computer-model-catalog.test.ts+++ b/server/src/__tests__/agents-computer-model-catalog.test.ts@@ -3,7 +3,7 @@** Run: node --import tsx --test server/src/__tests__/agents-computer-model-catalog.test.ts*/-import { test } from 'node:test'+import { after, test } from 'node:test'import assert from 'node:assert/strict'import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'@@ -11,6 +11,19 @@ import { join } from 'node:path'import { readClaudeUserSettings, withClaudeUserSettingsEnv } from '../agents/computer/claude-user-settings.js'import { clearModelCatalogCache, discoverEngineModelCatalog, parseListedModels } from '../agents/computer/model-catalog.js'+// Metadata probes must never share the developer's real Codex home/login.+const isolatedHome = await mkdtemp(join(tmpdir(), 'cumora-catalog-home-'))+const originalEnv = { ...process.env }+process.env.HOME = isolatedHome+process.env.USERPROFILE = isolatedHome+process.env.CODEX_HOME = join(isolatedHome, '.codex')+delete process.env.OPENAI_BASE_URL+after(async () => {+ for (const key of Object.keys(process.env)) if (!(key in originalEnv)) delete process.env[key]+ Object.assign(process.env, originalEnv)+ await rm(isolatedHome, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })+})+test('Codex discovers Fast Mode support from advertised service tiers', async () => {const root = await mkdtemp(join(tmpdir(), 'cumora-codex-tiers-'))const script = join(root, 'catalog.cjs')@@ -250,6 +263,45 @@ test('a listing keeps the preset fast default only when the account listed it',}})+test('native Codex pagination retains a failed refresh and clears a successful empty listing', async () => {+ const root = await mkdtemp(join(tmpdir(), 'cumora-codex-paged-'))+ const state = join(root, 'state.json')+ const script = join(root, 'catalog.cjs')+ const bin = join(root, process.platform === 'win32' ? 'codex.cmd' : 'codex')+ await writeFile(script, `+const fs = require('node:fs')+require('node:readline').createInterface({ input: process.stdin }).on('line', line => {+ const msg = JSON.parse(line)+ if (!msg.id) return+ let response = { result: {} }+ if (msg.method === 'model/list') {+ const state = JSON.parse(fs.readFileSync(${JSON.stringify(state)}, 'utf8'))+ response = state.fail ? { error: { message: 'offline' } } : { result: state.empty ? { data: [] } :+ msg.params.cursor ? { data: [{ model: 'auto/second', displayName: 'Second' }] } :+ { data: [{ model: 'auto/first', isDefault: true }], nextCursor: 'second-page' } }+ }+ process.stdout.write(JSON.stringify({ id: msg.id, ...response }) + '\\n')+})+`)+ await writeFile(bin, process.platform === 'win32'+ ? `@echo off\r\n"${process.execPath}" "%~dp0catalog.cjs" %*\r\n`+ : `#!/bin/sh\nexec node "${script}" "$@"\n`, { mode: 0o755 })+ try {+ await writeFile(state, '{}')+ const listed = await discoverEngineModelCatalog('codex', bin, true)+ assert.deepEqual(listed.models.map(model => model.id), ['auto/first', 'auto/second'])+ await writeFile(state, '{"fail":true}')+ const failed = await discoverEngineModelCatalog('codex', bin, true)+ assert.equal(failed.stale, true)+ assert.deepEqual(failed.models, listed.models)+ await writeFile(state, '{"empty":true}')+ const empty = await discoverEngineModelCatalog('codex', bin, true)+ assert.equal(empty.stale, undefined)+ assert.equal(empty.trustedModels, true)+ assert.deepEqual(empty.models, [])+ } finally { await rm(root, { recursive: true, force: true }) }+})+test('a CLI that listed nothing offers nothing, not a model named after its excuse', async () => {// End to end through the real dispatch. Cursor has no preset — cumora takes// its whole catalog from the CLI — so before the fix the picker's only entrydiff --git a/server/src/__tests__/codex-rpc.test.ts b/server/src/__tests__/codex-rpc.test.tsnew file mode 100644index 0000000..ff957f2--- /dev/null+++ b/server/src/__tests__/codex-rpc.test.ts@@ -0,0 +1,79 @@+import assert from 'node:assert/strict'+import childProcess from 'node:child_process'+import { EventEmitter } from 'node:events'+import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'+import { syncBuiltinESMExports } from 'node:module'+import { tmpdir } from 'node:os'+import { basename, join } from 'node:path'+import { PassThrough } from 'node:stream'+import { test } from 'node:test'+import { assertCodexProviderTransport, codexCommandInvocation, readCodexRpc } from '../agents/computer/codex-rpc.js'++test('an RPC timeout remains bounded when process cleanup never produces close', async () => {+ const originalSpawn = childProcess.spawn+ const child = Object.assign(new EventEmitter(), {+ stdin: new PassThrough(), stdout: new PassThrough(), pid: undefined, unref() {},+ })+ const guard = setTimeout(() => {}, 4000)+ try {+ childProcess.spawn = (() => child) as unknown as typeof childProcess.spawn+ syncBuiltinESMExports()+ const started = Date.now()+ assert.equal(await readCodexRpc('unavailable-codex', [], { PATH: '', CODEX_HOME: tmpdir() },+ 'config/read', {}, { timeoutMs: 5 }), null)+ assert.ok(Date.now() - started < 3000)+ } finally {+ clearTimeout(guard)+ childProcess.spawn = originalSpawn+ syncBuiltinESMExports()+ }+})++test('a successful RPC response survives cleanup without a close event', async () => {+ const originalSpawn = childProcess.spawn+ const child = Object.assign(new EventEmitter(), {+ stdin: new PassThrough(), stdout: new PassThrough(), pid: undefined, unref() {},+ })+ const guard = setTimeout(() => {}, 4000)+ try {+ childProcess.spawn = (() => child) as unknown as typeof childProcess.spawn+ syncBuiltinESMExports()+ const response = { config: { model: 'gateway/model' } }+ const started = Date.now()+ const pending = readCodexRpc('fixture-codex', [], { PATH: '', CODEX_HOME: tmpdir() }, 'config/read', {})+ child.stdout.write(`${JSON.stringify({ id: 1, result: {} })}\n${JSON.stringify({ id: 2, result: response })}\n`)+ assert.deepEqual(await pending, response)+ assert.ok(Date.now() - started < 3000)+ assert.equal(child.stdin.destroyed, true)+ assert.equal(child.stdout.destroyed, true)+ } finally {+ clearTimeout(guard)+ childProcess.spawn = originalSpawn+ syncBuiltinESMExports()+ }+})++test('Windows resolves pnpm-style entry points and preserves literal percent values', { skip: process.platform !== 'win32' }, async () => {+ const root = await mkdtemp(join(tmpdir(), 'cumora-codex-pnpm-'))+ const bin = join(root, 'node_modules', '.bin')+ const packageDir = join(root, 'node_modules', '@openai', 'codex')+ await Promise.all([mkdir(bin, { recursive: true }), mkdir(join(packageDir, 'bin'), { recursive: true })])+ const shim = join(bin, 'codex.cmd')+ const script = join(packageDir, 'bin', 'codex.js')+ await writeFile(shim, '@echo off\r\nexit /b 1\r\n')+ await writeFile(join(packageDir, 'package.json'), JSON.stringify({ name: '@openai/codex', version: '1.0.0' }))+ await writeFile(script, "process.stdout.write(JSON.stringify(process.argv.slice(2)))")+ const value = 'model_providers={gateway={http_headers={token="literal-%COMSPEC%"}}}'+ try {+ const invocation = codexCommandInvocation(shim, ['-c', value], process.env)+ assert.equal(basename(invocation.command).toLowerCase(), 'node.exe')+ assert.equal(invocation.windowsVerbatimArguments, undefined)+ const output = childProcess.execFileSync(invocation.command, invocation.args, { encoding: 'utf8', windowsHide: true })+ assert.deepEqual(JSON.parse(output), ['-c', value])+ assert.throws(() => assertCodexProviderTransport([value], true), /cannot preserve/)+ await rm(join(root, 'node_modules', '@openai'), { recursive: true })+ const fallback = codexCommandInvocation(shim, ['-c', value], { PATH: '' })+ assert.equal(fallback.windowsVerbatimArguments, true)+ assert.equal(await readCodexRpc(shim, ['-c', value], { PATH: '', CODEX_HOME: root }, 'model/list', {}), null)+ } finally { await rm(root, { recursive: true, force: true }) }+})diff --git a/server/src/__tests__/configured-models.test.ts b/server/src/__tests__/configured-models.test.tsnew file mode 100644index 0000000..bbed2ce--- /dev/null+++ b/server/src/__tests__/configured-models.test.ts@@ -0,0 +1,143 @@+import assert from 'node:assert/strict'+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { test } from 'node:test'+import { discoverEngineModelCatalog, parseListedModels } from '../agents/computer/model-catalog.js'++test('Gemini reads JSONC model definitions, custom aliases and defaults without exporting settings', async () => {+ const root = await mkdtemp(join(tmpdir(), 'cumora-gemini-models-'))+ const file = join(root, '.gemini', 'settings.json')+ const env = { GEMINI_CLI_HOME: root }+ try {+ await mkdir(join(root, '.gemini'))+ await writeFile(file, `{+ // An engine-owned catalog, with a quoted URL and trailing commas.+ "model": {"name": "gateway/main"},+ "modelConfigs": {+ "modelDefinitions": {+ "gateway/main": {"displayName": "Main"},+ "hidden/model": {"isVisible": false},+ },+ "customAliases": {"custom/long": {"extends": "gateway/main"}},+ },+ "env": {"SECRET": "https://private.test/a//b"},+ }`)+ const catalog = await discoverEngineModelCatalog('gemini', 'fixture', true, env)+ assert.deepEqual(catalog.models.map(row => row.id), ['gateway/main', 'custom/long'])+ assert.equal(catalog.models[0].label, 'Main')+ assert.equal(catalog.prefersLocalDefault, true)+ assert.equal(catalog.defaultModel, 'gateway/main')+ assert.equal(catalog.defaultFastModel, null)+ assert.doesNotMatch(JSON.stringify(catalog), /SECRET|private\.test/)+ assert.equal((await discoverEngineModelCatalog('gemini', 'fixture', true,+ { ...env, GEMINI_MODEL: 'env/model' })).defaultModel, 'env/model')+ await writeFile(file, '{"modelConfigs":{"modelDefinitions":{}}}')+ assert.deepEqual((await discoverEngineModelCatalog('gemini', 'fixture', false, env)).models, [])+ await writeFile(file, '{partial')+ const broken = await discoverEngineModelCatalog('gemini', 'fixture', true, env)+ assert.equal(broken.stale, true)+ assert.deepEqual(broken.models, [])+ } finally { await rm(root, { recursive: true, force: true }) }+})++test('Qwen includes unambiguous routes across endpoints within the active protocol', async () => {+ const root = await mkdtemp(join(tmpdir(), 'cumora-qwen-models-'))+ const file = join(root, 'settings.json')+ const env = { QWEN_HOME: root }+ try {+ const settings = {+ security: { auth: { selectedType: 'openai' } },+ model: { name: 'gateway/main' },+ providerProtocol: { company: 'openai' },+ modelProviders: {+ company: [+ { id: 'gateway/main', name: 'Main', baseUrl: 'https://gateway.test/v1', envKey: 'KEY' },+ { id: 'gateway/small[1m]', name: 'Small', baseUrl: 'https://gateway.test/v1', envKey: 'KEY' },+ { id: 'other-account', baseUrl: 'https://gateway.test/v1', envKey: 'OTHER_KEY' },+ { id: 'image', baseUrl: 'https://gateway.test/v1', envKey: 'KEY', imageOnly: true },+ ],+ anthropic: [{ id: 'other-protocol' }],+ },+ }+ await writeFile(file, JSON.stringify(settings))+ const catalog = await discoverEngineModelCatalog('qwen', 'fixture', true, env)+ assert.deepEqual(catalog.models.map(row => row.id), ['gateway/main', 'gateway/small[1m]', 'other-account'])+ assert.equal(catalog.models[0].label, 'Main')+ assert.equal(catalog.defaultModel, 'gateway/main')+ assert.equal(catalog.prefersLocalDefault, true)+ settings.modelProviders.company.push(+ { id: 'gateway/main', name: 'Ambiguous', baseUrl: 'https://other.test/v1', envKey: 'OTHER_KEY' },+ )+ await writeFile(file, JSON.stringify(settings))+ const ambiguous = await discoverEngineModelCatalog('qwen', 'fixture', false, env)+ assert.equal(ambiguous.models.some(row => row.id === 'gateway/main'), false)+ settings.model.name = 'image'+ await writeFile(file, JSON.stringify(settings))+ assert.equal((await discoverEngineModelCatalog('qwen', 'fixture', false, env)).models.some(row => row.id === 'image'), false)+ settings.model.name = 'gateway/main'+ settings.modelProviders.company = []+ await writeFile(file, JSON.stringify(settings))+ const changed = await discoverEngineModelCatalog('qwen', 'fixture', false, env)+ assert.deepEqual(changed.models.map(row => row.id), ['gateway/main'])+ } finally { await rm(root, { recursive: true, force: true }) }+})++test('ZCode preserves provider-qualified ACP selectors and desktop model deletions', async () => {+ const root = await mkdtemp(join(tmpdir(), 'cumora-zcode-models-'))+ const env = { ZCODE_HOME: root }+ try {+ await mkdir(join(root, 'v2'))+ await writeFile(join(root, 'v2', 'config.json'), JSON.stringify({ provider: {+ company: { enabled: true, options: { apiKey: 'private-token' }, models: { deleted: {} } },+ local: { options: { baseURL: 'http://localhost:1234/v1' }, models: { 'auto/route': { name: 'Local' } } },+ unusable: { enabled: true, models: { hidden: {} } },+ 'builtin:glm-coding-plan': { enabled: true, options: { apiKey: 'private-plan-key' }, models: { allowed: {}, disabled: {} } },+ } }))+ await writeFile(join(root, 'v2', 'provider_config.json'), JSON.stringify({ config: {+ modelConfigRules: { manualProviderModelRules: [+ { providerId: 'company', modelId: 'auto/route', config: { enabled: true } },+ { providerId: 'company', modelId: 'off', config: { enabled: false } },+ { providerId: 'account:glm-individual-coding-plan', modelId: 'disabled', config: { enabled: false } },+ ] },+ } }))+ const catalog = await discoverEngineModelCatalog('zcode', 'fixture', true, env)+ assert.deepEqual(catalog.models.map(row => row.id), ['company\\auto/route', 'local\\auto/route', 'builtin:glm-coding-plan\\allowed'])+ assert.doesNotMatch(JSON.stringify(catalog), /private-token|private-plan-key|localhost|deleted|unusable|disabled/)+ const pinned = await discoverEngineModelCatalog('zcode', 'fixture', false, { ...env, ZCODE_PROVIDER: 'local' })+ assert.deepEqual(pinned.models.map(row => row.id), ['local\\auto/route'])+ const defaulted = await discoverEngineModelCatalog('zcode', 'fixture', false,+ { ...env, ZCODE_PROVIDER: 'local', ZCODE_MODEL: 'auto/route' })+ assert.equal(defaulted.defaultModel, 'local\\auto/route')+ assert.deepEqual(defaulted.models.map(row => row.id), ['local\\auto/route'])+ } finally { await rm(root, { recursive: true, force: true }) }+})++test('native catalogs preserve context suffixes and do not parse prose into provider IDs', () => {+ for (const style of ['cursor', 'provider', 'pi', 'antigravity'] as const) {+ assert.deepEqual(parseListedModels('gateway/model[1m]', style).map(row => row.id), ['gateway/model[1m]'])+ assert.deepEqual(parseListedModels('Failed to load gateway/model', style), [])+ }+ assert.deepEqual(parseListedModels('ID Name', 'cursor'), [])+})++test('all native listing adapters use the supplied environment, reject failed output and re-read the catalog', async () => {+ const root = await mkdtemp(join(tmpdir(), 'cumora-native-models-'))+ const script = join(root, 'list.cjs')+ const bin = join(root, process.platform === 'win32' ? 'models.cmd' : 'models')+ try {+ await writeFile(script, `process.stdout.write(process.env.MODEL_LIST || ''); process.exit(Number(process.env.LIST_EXIT || 0))`)+ await writeFile(bin, process.platform === 'win32'+ ? `@echo off\r\n"${process.execPath}" "%~dp0list.cjs" %*\r\n`+ : `#!/bin/sh\nexec "${process.execPath}" "${script}" "$@"\n`, { mode: 0o755 })+ for (const engine of ['grok', 'cursor', 'opencode', 'pi', 'antigravity'] as const) {+ const env = { ...process.env, MODEL_LIST: 'gateway/model[1m]' }+ const listed = await discoverEngineModelCatalog(engine, bin, false, env)+ assert.deepEqual(listed.models.map(row => row.id), ['gateway/model[1m]'], engine)+ const changed = await discoverEngineModelCatalog(engine, bin, false, { ...env, MODEL_LIST: 'gateway/changed' })+ assert.deepEqual(changed.models.map(row => row.id), ['gateway/changed'], engine)+ const failed = await discoverEngineModelCatalog(engine, bin, true, { ...env, LIST_EXIT: '1' })+ assert.equal(failed.trustedModels, undefined, engine)+ }+ } finally { await rm(root, { recursive: true, force: true }) }+})diff --git a/server/src/__tests__/model-id.test.ts b/server/src/__tests__/model-id.test.tsindex 6b7af72..1d8c4c0 100644--- a/server/src/__tests__/model-id.test.ts+++ b/server/src/__tests__/model-id.test.ts@@ -8,6 +8,9 @@ test('a model id is one token vendors actually use', () => {assert.equal(parseModelId('claude-sonnet-4-5'), 'claude-sonnet-4-5')assert.equal(parseModelId(' my-provider/some-model '), 'my-provider/some-model')assert.equal(parseModelId('gpt-5.4-mini'), 'gpt-5.4-mini')+ assert.equal(parseModelId('auto/dfmodel[1m]'), 'auto/dfmodel[1m]')+ assert.equal(parseModelId('provider/model+thinking'), 'provider/model+thinking')+ assert.equal(parseModelId('builtin:zai-coding-plan\\glm-model'), 'builtin:zai-coding-plan\\glm-model')assert.equal(parseModelId(''), null)assert.equal(parseModelId(' '), null)assert.equal(parseModelId(null), null)@@ -16,7 +19,8 @@ test('a model id is one token vendors actually use', () => {})test('a model id cannot carry a shell metacharacter', () => {- for (const value of ['sonnet & calc.exe', 'sonnet|calc', 'sonnet;calc', 'a"b', 'a%PATH%', 'a b', '../x']) {+ for (const value of ['sonnet & calc.exe', 'sonnet|calc', 'sonnet;calc', 'a"b', 'a%PATH%', 'a b', '../x',+ 'a/../x', 'a/./x', 'a[1m', 'a[1m][2m]', 'a\nb', 'a@host', 'provider\\..\\secret', 'provider\\../secret', 'p\\a\\b']) {assert.throws(() => parseModelId(value), InvalidModelIdError)assert.equal(modelIdOrNull(value), null)}diff --git a/server/src/__tests__/provider-model-catalog.test.ts b/server/src/__tests__/provider-model-catalog.test.tsnew file mode 100644index 0000000..03fb06e--- /dev/null+++ b/server/src/__tests__/provider-model-catalog.test.ts@@ -0,0 +1,217 @@+import assert from 'node:assert/strict'+import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'+import { homedir, tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, test } from 'node:test'+import { projectCodexProvider } from '../agents/computer/codex-provider.js'+import { clearModelCatalogCache, discoverEngineModelCatalog } from '../agents/computer/model-catalog.js'+import { fetchProviderModels, parseProviderModels } from '../agents/computer/provider-models.js'++afterEach(clearModelCatalogCache)++async function serve(handler: (req: IncomingMessage, res: ServerResponse) => void) {+ const server = createServer(handler)+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))+ const address = server.address() as { port: number }+ return {+ url: `http://127.0.0.1:${address.port}`,+ async close() {+ server.closeAllConnections()+ await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()))+ },+ }+}++test('provider projection imports only the selected connection and model fields', () => {+ const result = projectCodexProvider({+ model_provider: 'gateway', model: 'auto/dfmodel',+ model_providers: {+ gateway: {+ name: 'Gateway', base_url: 'https://gateway.test/v1', wire_api: 'responses',+ env_key: 'GATEWAY_TOKEN', env_http_headers: { 'x-account': 'ACCOUNT' },+ query_params: { api_version: 'v1' }, command: 'must-not-run', auth: { command: 'must-not-run' },+ },+ inactive: { base_url: 'https://inactive.test', experimental_bearer_token: 'inactive-secret' },+ },+ hooks: { command: 'must-not-run' }, mcp_servers: { unsafe: {} }, permissions: { unsafe: true },+ }, { GATEWAY_TOKEN: 'local-secret', ACCOUNT: 'account' }, homedir())+ assert.equal(result.defaultModel, 'auto/dfmodel')+ assert.equal(result.connection?.url, 'https://gateway.test/v1/models')+ assert.equal(result.connection?.headers.Authorization, 'Bearer local-secret')+ assert.equal(result.connection?.headers['x-account'], 'account')+ assert.equal(result.prefersLocalDefault, true)+ assert.doesNotMatch(result.args.join('\n'), /must-not-run|inactive|hooks|mcp_servers|permissions/)+ assert.match(result.args.join('\n'), /model_provider="gateway"/)+ assert.match(result.args.join('\n'), /model_providers=\{/)+ assert.equal(projectCodexProvider({+ model_providers: { openai: { base_url: 'https://gateway.test', model_catalog_url: 'https://other.test/models' } },+ }, {}, homedir()).connection, null, 'never forward credentials to another catalog origin')+})++test('a Codex native backend override is projected but probed through its own protocol', () => {+ const result = projectCodexProvider({ openai_base_url: 'https://gateway.test/native', model: 'auto/main' }, {}, homedir())+ assert.equal(result.connection, null)+ assert.match(result.args.join('\n'), /openai_base_url="https:\/\/gateway.test\/native"/)+ assert.equal(result.prefersLocalDefault, true)+})++test('an explicit provider address wins over inherited OpenAI overrides without moving credentials', () => {+ const result = projectCodexProvider({+ model_provider: 'gateway',+ model_providers: { gateway: { name: 'Gateway', base_url: 'https://selected.test/v1',+ experimental_bearer_token: 'selected-token', wire_api: 'responses' } },+ }, { OPENAI_BASE_URL: 'https://other.test/v1' }, homedir())+ assert.equal(result.connection?.url, 'https://selected.test/v1/models')+ assert.equal(result.connection?.headers.Authorization, 'Bearer selected-token')+ assert.doesNotMatch(result.args.join('\n'), /other\.test/)+ assert.equal(result.ignoresOpenAIBaseEnv, true)+ const native = projectCodexProvider({ openai_base_url: 'https://runtime.test/native' },+ { OPENAI_BASE_URL: 'https://other.test' }, homedir())+ assert.match(native.args.join('\n'), /runtime\.test/)+ assert.doesNotMatch(native.args.join('\n'), /other\.test/)+})++test('protocol-only provider identities include resolved tenant and authentication environment', () => {+ const config = { model_provider: 'oauth', model_providers: { oauth: {+ name: 'OAuth', base_url: 'https://provider.test', requires_openai_auth: true,+ env_http_headers: { 'x-tenant': 'TENANT_ID' },+ } } }+ const first = projectCodexProvider(config, { TENANT_ID: 'a' }, homedir())+ const second = projectCodexProvider(config, { TENANT_ID: 'b' }, homedir())+ assert.equal(first.connection, null)+ assert.equal(second.connection, null)+ assert.notEqual(first.identity, second.identity)+})++test('HTTP catalog parsing preserves exact routes and ignores capability claims', () => {+ const result = parseProviderModels([+ { id: 'auto/dfmodel', display_name: 'Flash', supportsFastMode: true, serviceTiers: [{ id: 'fast' }] },+ { model: 'auto/dfmodel[1m]', label: 'Flash' },+ { id: 'provider/model+thinking' },+ { id: 'a/../secret' }, { id: 'model & calc' }, { id: 'model\ncontrol' }, { id: 'model@host' },+ ])+ assert.deepEqual(result.map(model => model.id), ['auto/dfmodel', 'auto/dfmodel[1m]', 'provider/model+thinking'])+ assert.ok(result.every(model => model.supportsFastMode === undefined))+})++test('HTTP discovery bounds pagination and keeps authentication on one endpoint', async () => {+ const calls: string[] = []+ const server = await serve((req, res) => {+ calls.push(req.url!)+ assert.equal(req.headers.authorization, 'Bearer fixture-token')+ res.setHeader('Content-Type', 'application/json')+ res.end(JSON.stringify(req.url!.includes('cursor=')+ ? { data: [{ id: 'auto/second' }] }+ : { data: [{ id: 'auto/first' }], next_cursor: 'page-two' }))+ })+ try {+ const models = await fetchProviderModels({ url: `${server.url}/v1/models`, headers: { Authorization: 'Bearer fixture-token' } })+ assert.deepEqual(models?.map(model => model.id), ['auto/first', 'auto/second'])+ assert.deepEqual(calls, ['/v1/models', '/v1/models?cursor=page-two'])+ } finally { await server.close() }+})++test('HTTP discovery rejects redirects, oversized responses, malformed data and repeating cursors', async () => {+ const server = await serve((req, res) => {+ if (req.url?.startsWith('/redirect')) {+ res.writeHead(302, { Location: '/redirect-target' })+ res.end()+ } else if (req.url?.startsWith('/large')) res.end(' '.repeat(2 * 1024 * 1024 + 1))+ else if (req.url?.startsWith('/loop')) res.end(JSON.stringify({ data: [], next_cursor: 'repeat' }))+ else res.end(JSON.stringify({ message: 'not a model catalog' }))+ })+ try {+ for (const path of ['redirect', 'large', 'loop', 'invalid']) {+ assert.equal(await fetchProviderModels({ url: `${server.url}/${path}`, headers: {} }), null)+ }+ } finally { await server.close() }+})++test('Claude without a picker supplements mappings from HTTP, retains failures and clears successful empties', async () => {+ const root = await mkdtemp(join(tmpdir(), 'cumora-provider-models-'))+ let mode: 'models' | 'failure' | 'empty' = 'models'+ const server = await serve((_req, res) => {+ if (mode === 'failure') { res.writeHead(503).end(); return }+ res.setHeader('Content-Type', 'application/json')+ res.end(JSON.stringify({ data: mode === 'empty' ? [] : [+ { id: 'auto/dfmodel[1m]', display_name: 'Generic remote label' },+ { id: 'auto/dfmodel', display_name: 'Flash' },+ { id: 'remote-only', supportsFastMode: true },+ ] }))+ })+ const file = join(root, 'settings.json')+ const env = { CLAUDE_CONFIG_DIR: root }+ const write = (model = 'auto/dfmodel[1m]') => writeFile(file, JSON.stringify({+ model,+ env: { ANTHROPIC_BASE_URL: server.url, ANTHROPIC_AUTH_TOKEN: 'private-token',+ ANTHROPIC_DEFAULT_OPUS_MODEL: 'auto/big', ANTHROPIC_DEFAULT_SONNET_MODEL: 'auto/middle',+ ANTHROPIC_DEFAULT_HAIKU_MODEL: 'auto/small' },+ hooks: { command: 'must-not-run' },+ }))+ try {+ await write()+ const catalog = await discoverEngineModelCatalog('claude', 'fixture-claude', true, env)+ assert.equal(catalog.defaultModel, 'auto/dfmodel[1m]')+ assert.equal(catalog.defaultFastModel, 'auto/small')+ assert.ok(catalog.models.some(model => model.id === 'auto/middle'))+ assert.ok(catalog.models.some(model => model.id === 'auto/big'))+ assert.ok(catalog.models.some(model => model.id === 'auto/dfmodel'))+ assert.ok(catalog.models.every(model => model.supportsFastMode === false))+ assert.doesNotMatch(JSON.stringify(catalog), /private-token|127\.0\.0\.1|must-not-run/)+ mode = 'failure'+ const failed = await discoverEngineModelCatalog('claude', 'fixture-claude', true, env)+ assert.equal(failed.stale, true)+ assert.ok(failed.models.some(model => model.id === 'remote-only'))+ mode = 'empty'+ const empty = await discoverEngineModelCatalog('claude', 'fixture-claude', true, env)+ assert.equal(empty.stale, undefined)+ assert.equal(empty.models.some(model => model.id === 'remote-only'), false)+ await write('auto/changed')+ assert.equal((await discoverEngineModelCatalog('claude', 'fixture-claude', false, env)).defaultModel, 'auto/changed')+ await writeFile(file, '{partial configuration')+ const partial = await discoverEngineModelCatalog('claude', 'fixture-claude', true, env)+ assert.equal(partial.stale, true)+ assert.deepEqual(partial.models, [], 'unknown connection identity cannot borrow an earlier directory')+ const switchedPartial = await discoverEngineModelCatalog('claude', 'fixture-claude', true,+ { ...env, ANTHROPIC_BASE_URL: 'https://other.example.test' })+ assert.deepEqual(switchedPartial.models, [])+ // A different connection never inherits the previous connection's cached choices.+ const other = join(root, 'other')+ await mkdir(other)+ await writeFile(join(other, 'settings.json'), JSON.stringify({ model: 'other/only' }))+ const switched = await discoverEngineModelCatalog('claude', 'fixture-claude', false, { CLAUDE_CONFIG_DIR: other })+ assert.equal(switched.models.some(model => model.id.startsWith('auto/')), false)+ } finally {+ await server.close()+ await rm(root, { recursive: true, force: true })+ }+})++test('an explicit Claude picker is authoritative, including variants and a successful empty picker', async () => {+ const root = await mkdtemp(join(tmpdir(), 'cumora-picker-'))+ let calls = 0+ const server = await serve((_req, res) => {+ calls+++ res.end(JSON.stringify({ data: [{ id: 'auto/route' }] }))+ })+ const file = join(root, 'settings.json')+ const env = { CLAUDE_CONFIG_DIR: root }+ const write = (options: unknown[]) => writeFile(file, JSON.stringify({+ env: { ANTHROPIC_BASE_URL: server.url }, modelPicker: { options },+ }))+ try {+ await write([{ model: 'auto/route[1m]', label: 'Native route' }])+ const catalog = await discoverEngineModelCatalog('claude', 'fixture', true, env)+ assert.deepEqual(catalog.models.map(row => row.id), ['auto/route[1m]'])+ assert.equal(catalog.stale, undefined)+ await write([{ model: 'auto/route', label: 'Plain' }, { model: 'auto/route[1m]', label: 'Long' }])+ assert.equal((await discoverEngineModelCatalog('claude', 'fixture', false, env)).models.length, 2)+ await write([])+ assert.deepEqual((await discoverEngineModelCatalog('claude', 'fixture', false, env)).models, [])+ assert.equal(calls, 0, 'an engine picker must not be inflated by a generic namespace')+ } finally {+ await server.close()+ await rm(root, { recursive: true, force: true })+ }+})diff --git a/server/src/agents/computer/claude-user-settings.ts b/server/src/agents/computer/claude-user-settings.tsindex 8ca75a7..d67a475 100644--- a/server/src/agents/computer/claude-user-settings.ts+++ b/server/src/agents/computer/claude-user-settings.ts@@ -5,9 +5,13 @@* Import only validated, non-executable fields. Environment values enter the* trusted core; the adapter denies those names to model-spawned subprocesses.*/+import { createHash } from 'node:crypto'import { readFileSync, statSync } from 'node:fs'import { homedir } from 'node:os'import { isAbsolute, join } from 'node:path'+import type { EngineModelOption } from './model-catalog.js'+import { modelIdOrNull } from './model-id.js'+import { parseProviderModels } from './provider-models.js'const MAX_SETTINGS_BYTES = 1024 * 1024@@ -18,6 +22,7 @@ export const CLAUDE_CORE_ENV_KEYS = ['ANTHROPIC_API_KEY','ANTHROPIC_AUTH_TOKEN','ANTHROPIC_BASE_URL',+ 'ANTHROPIC_MODEL','ANTHROPIC_SMALL_FAST_MODEL','ANTHROPIC_DEFAULT_OPUS_MODEL','ANTHROPIC_DEFAULT_SONNET_MODEL',@@ -111,6 +116,8 @@ export interface ClaudeUserSettings {defaultModel: string | nulldefaultFastModel: string | nullprefersLocalDefault: boolean+ models?: EngineModelOption[]+ readFailure?: true}const EMPTY_SETTINGS: ClaudeUserSettings = {@@ -145,32 +152,37 @@ export function readClaudeUserSettings(env: NodeJS.ProcessEnv = process.env): Cltry {const file = settingsPath(env)if (!file) return EMPTY_SETTINGS- if (statSync(file).size > MAX_SETTINGS_BYTES) return EMPTY_SETTINGS+ if (statSync(file).size > MAX_SETTINGS_BYTES) return { ...EMPTY_SETTINGS, readFailure: true }const parsed = JSON.parse(readFileSync(file, 'utf8')) as unknown- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return EMPTY_SETTINGS+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return { ...EMPTY_SETTINGS, readFailure: true }const record = parsed as Record<string, unknown>const rawEnv = record.env && typeof record.env === 'object' && !Array.isArray(record.env)? record.env as Record<string, unknown>: {}const coreEnv: Partial<Record<ClaudeCoreEnvKey, string>> = {}for (const key of CLAUDE_CORE_ENV_KEYS) {- const value = cleanString(rawEnv[key], key === 'ANTHROPIC_SMALL_FAST_MODEL' ? 160 : 4096)+ const raw = rawEnv[key]+ const value = key.endsWith('_MODEL')+ ? modelIdOrNull(typeof raw === 'string' ? raw : null)+ : cleanString(raw, 4096)if (value) coreEnv[key] = value}+ const picker = record.modelPicker+ const options = picker && typeof picker === 'object' && 'options' in picker ? picker.options : undefinedreturn {coreEnv,turnEnv: turnEnv(rawEnv),turnSettings: turnSettings(record),- defaultModel: cleanString(record.model, 160),- defaultFastModel: cleanString(rawEnv.ANTHROPIC_DEFAULT_HAIKU_MODEL, 160)- ?? cleanString(rawEnv.ANTHROPIC_SMALL_FAST_MODEL, 160),+ defaultModel: coreEnv.ANTHROPIC_MODEL ?? modelIdOrNull(typeof record.model === 'string' ? record.model : null),+ defaultFastModel: coreEnv.ANTHROPIC_DEFAULT_HAIKU_MODEL ?? coreEnv.ANTHROPIC_SMALL_FAST_MODEL ?? null,// A custom endpoint owns its model namespace. When no explicit Agent pin// exists, the server must not replace that namespace with its Anthropic// deployment default even if the local config omits a named model.prefersLocalDefault: isCustomAnthropicEndpoint(coreEnv.ANTHROPIC_BASE_URL),+ ...(Array.isArray(options) ? { models: parseProviderModels(options) } : {}),}- } catch {- return EMPTY_SETTINGS+ } catch (error) {+ return (error as NodeJS.ErrnoException).code === 'ENOENT' ? EMPTY_SETTINGS : { ...EMPTY_SETTINGS, readFailure: true }}}@@ -183,3 +195,13 @@ export function withClaudeUserSettingsEnv(env: NodeJS.ProcessEnv): NodeJS.Proces}return merged}++/** Private change detector for idle persistent sessions. */+export function claudeProviderFingerprint(env: NodeJS.ProcessEnv): string {+ const settings = readClaudeUserSettings(env)+ const effective = withClaudeUserSettingsEnv(env)+ return createHash('sha256').update(JSON.stringify([+ effective.ANTHROPIC_MODEL || settings.defaultModel, settings.turnSettings, settings.turnEnv,+ CLAUDE_CORE_ENV_KEYS.map(key => effective[key]),+ ])).digest('hex')+}diff --git a/server/src/agents/computer/codex-provider.ts b/server/src/agents/computer/codex-provider.tsnew file mode 100644index 0000000..0463317--- /dev/null+++ b/server/src/agents/computer/codex-provider.ts@@ -0,0 +1,195 @@+import { createHash } from 'node:crypto'+import { existsSync, readFileSync, statSync } from 'node:fs'+import { homedir } from 'node:os'+import { isAbsolute, join, resolve } from 'node:path'+import { CODEX_RUNTIME_CONFIG_ARGS, codexRuntimeEnv, codexRuntimeHome } from './codex-runtime.js'+import { readCodexRpc } from './codex-rpc.js'+import { modelIdOrNull } from './model-id.js'+import type { ProviderCatalogConnection } from './provider-models.js'++export interface CodexProvider {+ args: string[]+ defaultModel: string | null+ prefersLocalDefault: boolean+ connection: ProviderCatalogConnection | null+ catalogFile: string | null+ fingerprint: string+ identity: string+ ignoresOpenAIBaseEnv: boolean+}++const cache = new Map<string, Promise<CodexProvider>>()+const ready = new Map<string, CodexProvider>()+const agentRuntimeEnv = new Set(['CUMORA_AGENT_ID', 'CUMORA_AGENT_IPC_DIR', 'CUMORA_AGENT_MCP_SHIM'])+const configReads = new Map<string, Promise<Record<string, unknown> | null>>()++function sourceHome(env: NodeJS.ProcessEnv): string {+ if (existsSync(join(codexRuntimeHome(), 'config.toml'))) return codexRuntimeHome()+ const home = env.CODEX_HOME || join(homedir(), '.codex')+ if (!isAbsolute(home)) throw new Error('Codex configuration home must be absolute')+ return home+}++function configText(home: string): string {+ const file = join(home, 'config.toml')+ if (!existsSync(file)) return ''+ if (statSync(file).size > 1024 * 1024) throw new Error('Codex provider configuration is too large')+ return readFileSync(file, 'utf8')+}++/** Local hash only: changing credentials/config invalidates caches without publishing them. */+export function codexProviderFingerprint(env: NodeJS.ProcessEnv): string {+ const home = sourceHome(env)+ return createHash('sha256').update(home).update(configText(home))+ .update(JSON.stringify(Object.entries(env).sort(([a], [b]) => a.localeCompare(b)))).digest('hex')+}++function record(value: unknown): Record<string, unknown> {+ return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}+}++function strings(value: unknown): Record<string, string> {+ return Object.fromEntries(Object.entries(record(value)).filter((entry): entry is [string, string] =>+ typeof entry[1] === 'string' && entry[1].length <= 4096 && !/[\r\n\0]/.test(entry[1])).slice(0, 64))+}++function toml(value: unknown): string {+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return JSON.stringify(value)+ return `{${Object.entries(record(value)).map(([key, v]) => `${JSON.stringify(key)}=${toml(v)}`).join(',')}}`+}++/** Only connection fields, never commands, hooks, MCP, permissions, profiles or tool settings. */+export function projectCodexProvider(config: Record<string, unknown>, env: NodeJS.ProcessEnv, home: string, fingerprint = ''): CodexProvider {+ const args: string[] = []+ const add = (key: string, value: unknown) => { args.push('-c', `${key}=${toml(value)}`) }+ const providerId = typeof config.model_provider === 'string' ? config.model_provider : 'openai'+ const raw = record(record(config.model_providers)[providerId])+ const provider: Record<string, unknown> = {}+ for (const key of ['name', 'base_url', 'model_catalog_url', 'env_key', 'experimental_bearer_token', 'wire_api']) {+ const value = raw[key]+ if (typeof value === 'string' && value.length <= 4096) provider[key] = value+ }+ for (const key of ['requires_openai_auth', 'supports_websockets']) {+ if (typeof raw[key] === 'boolean') provider[key] = raw[key]+ }+ for (const key of ['http_headers', 'env_http_headers', 'query_params']) {+ const entries = strings(raw[key])+ if (Object.keys(entries).length) provider[key] = entries+ }+ const usesOpenAIEnv = providerId === 'openai' && !raw.base_url && typeof config.openai_base_url !== 'string' && !!env.OPENAI_BASE_URL+ const openaiBase = providerId !== 'openai' ? null+ : typeof config.openai_base_url === 'string' ? config.openai_base_url : env.OPENAI_BASE_URL+ const baseUrl = (typeof raw.base_url === 'string' ? raw.base_url : null) || openaiBase+ if (typeof config.model_provider === 'string') {+ add('model_provider', providerId)+ }+ if (Object.keys(provider).length) {+ add('model_providers', { [providerId]: provider })+ }+ if (openaiBase && providerId === 'openai') add('openai_base_url', openaiBase)+ const defaultModel = modelIdOrNull(typeof config.model === 'string' ? config.model : null)+ if (defaultModel) add('model', defaultModel)+ let catalogFile: string | null = null+ if (typeof config.model_catalog_json === 'string') {+ catalogFile = resolve(home, config.model_catalog_json)+ add('model_catalog_json', catalogFile)+ }+ let connection: ProviderCatalogConnection | null = null+ const headers = strings(provider.http_headers)+ for (const [key, name] of Object.entries(strings(provider.env_http_headers))) {+ if (env[name]) headers[key] = env[name]!+ }+ const token = typeof provider.env_key === 'string' ? env[provider.env_key]+ : typeof provider.experimental_bearer_token === 'string' ? provider.experimental_bearer_token : env.OPENAI_API_KEY+ if (token && !Object.keys(headers).some(key => key.toLowerCase() === 'authorization')) headers.Authorization = `Bearer ${token}`+ if (baseUrl) {+ try {+ const base = new URL(baseUrl)+ if (!['http:', 'https:'].includes(base.protocol) || base.username || base.password) throw new Error()+ const explicit = typeof provider.model_catalog_url === 'string' ? new URL(provider.model_catalog_url, base) : null+ // Catalog credentials may never cross to another origin.+ if (explicit && explicit.origin !== base.origin) throw new Error()+ const standard = new URL(base)+ standard.pathname = `${standard.pathname.replace(/\/+$/, '')}/models`+ standard.hash = ''+ const url = explicit ?? standard+ // OAuth-only connections use the engine protocol; do not repurpose login tokens.+ const compatibleApi = !!raw.base_url || usesOpenAIEnv || !!explicit+ if (compatibleApi && (provider.requires_openai_auth !== true || token)) {+ connection = { url: url.href, headers, query: strings(provider.query_params) }+ }+ } catch { /* Invalid/unsupported endpoint: protocol and configured choices remain available. */ }+ }+ const prefersLocalDefault = !!baseUrl || providerId !== 'openai'+ const identity = createHash('sha256').update(JSON.stringify([+ providerId, provider, baseUrl, headers, token,+ ])).digest('hex')+ return { args, defaultModel, prefersLocalDefault, connection, catalogFile, fingerprint, identity,+ ignoresOpenAIBaseEnv: !!raw.base_url || typeof config.openai_base_url === 'string' || providerId !== 'openai' }+}++async function readEffectiveCodexConfig(command: string, env: NodeJS.ProcessEnv, home: string): Promise<Record<string, unknown>> {+ const keyEnv = Object.entries(env).filter(([key]) => !agentRuntimeEnv.has(key)).sort(([a], [b]) => a.localeCompare(b))+ const key = createHash('sha256').update(command).update(home).update(configText(home)).update(JSON.stringify(keyEnv)).digest('hex')+ let pending = configReads.get(key)+ if (!pending) {+ // Share only the effective-config read; provider projection still uses each agent's environment.+ pending = readCodexRpc(command, [+ ...CODEX_RUNTIME_CONFIG_ARGS,+ '-c', 'features.hooks=false', '-c', 'features.apps=false',+ '-c', 'features.remote_plugin=false', '-c', 'mcp_servers={}',+ ], { ...env, CODEX_HOME: home }, 'config/read', { includeLayers: false })+ configReads.set(key, pending)+ void pending.then(() => {+ if (configReads.get(key) === pending) configReads.delete(key)+ }, () => {+ if (configReads.get(key) === pending) configReads.delete(key)+ })+ }+ const result = await pending+ if (!result || !result.config || typeof result.config !== 'object') {+ throw new Error('Cannot read effective Codex provider configuration; refresh the engine after correcting its configuration')+ }+ return record(result.config)+}++export function cachedCodexProvider(env: NodeJS.ProcessEnv): CodexProvider | undefined {+ const fingerprint = codexProviderFingerprint(env)+ const cached = ready.get(fingerprint)+ if (cached) return cached+ const home = sourceHome(env)+ return configText(home) ? undefined : projectCodexProvider({}, env, home, fingerprint)+}++export async function prepareCodexProvider(command: string, env: NodeJS.ProcessEnv): Promise<CodexProvider> {+ const fingerprint = codexProviderFingerprint(env)+ const key = `${command}\0${fingerprint}`+ const existing = cache.get(key)+ if (existing) return existing+ const pending = (async () => {+ const home = sourceHome(env)+ let config: Record<string, unknown> = {}+ if (configText(home)) {+ // Resolve TOML/profiles using the installed engine, with startup integrations disabled.+ config = await readEffectiveCodexConfig(command, env, home)+ }+ const projected = projectCodexProvider(config, env, home, fingerprint)+ ready.set(fingerprint, projected)+ if (ready.size > 64) ready.delete(ready.keys().next().value!)+ return projected+ })()+ cache.set(key, pending)+ if (cache.size > 64) cache.delete(cache.keys().next().value!)+ try { return await pending } catch (error) { cache.delete(key); throw error }+}++export async function codexProviderRuntime(command: string, env: NodeJS.ProcessEnv) {+ const provider = await prepareCodexProvider(command, env)+ return { provider, env: codexProviderEnv(provider, env) }+}++export function codexProviderEnv(provider: CodexProvider, env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {+ const runtime = codexRuntimeEnv(env)+ if (provider.ignoresOpenAIBaseEnv) delete runtime.OPENAI_BASE_URL+ return runtime+}diff --git a/server/src/agents/computer/codex-rpc.ts b/server/src/agents/computer/codex-rpc.tsnew file mode 100644index 0000000..496725e--- /dev/null+++ b/server/src/agents/computer/codex-rpc.ts@@ -0,0 +1,115 @@+import { execFile, spawn } from 'node:child_process'+import { existsSync } from 'node:fs'+import { basename, delimiter, dirname, join } from 'node:path'+import { createRequire } from 'node:module'+import { StringDecoder } from 'node:string_decoder'+import { versionCommandInvocation } from './cli-version.js'++/** Resolve npm/pnpm entry points so structured TOML never passes through cmd.exe. */+export function codexCommandInvocation(command: string, args: string[], env: NodeJS.ProcessEnv): ReturnType<typeof versionCommandInvocation> {+ let invocation = versionCommandInvocation(command, args)+ if (process.platform !== 'win32') return invocation+ const paths = (env.PATH ?? process.env.PATH ?? '').split(delimiter)+ const shim = [command, ...paths.map(dir => join(dir, command))]+ .flatMap(path => [path, `${path}.cmd`]).find(path => existsSync(path) && /\.cmd$/i.test(path))+ if (!shim) return invocation+ invocation = versionCommandInvocation(shim, args)+ let script = join(dirname(shim), 'node_modules', '@openai', 'codex', 'bin', 'codex.js')+ if (!existsSync(script)) {+ try { script = createRequire(join(dirname(shim), 'cumora-resolver.cjs')).resolve('@openai/codex/bin/codex.js') }+ catch { return invocation }+ }+ if (!existsSync(script)) return invocation+ const node = [join(dirname(shim), 'node.exe'), ...paths.map(dir => join(dir, 'node.exe'))]+ .find(path => existsSync(path))+ ?? (/^node(?:\.exe)?$/i.test(basename(process.execPath)) ? process.execPath : null)+ return node ? { command: node, args: [script, ...args] } : invocation+}++export function assertCodexProviderTransport(args: string[], usesShell: boolean): void {+ if (process.platform === 'win32' && usesShell && args.length) {+ throw new Error('Codex provider settings require a native executable or a resolvable npm/pnpm installation on Windows; this batch wrapper cannot preserve them safely')+ }+}++/** Metadata only. Callers must project config/read before storing or reporting it. */+export function readCodexRpc(+ command: string,+ args: string[],+ env: NodeJS.ProcessEnv,+ method: string,+ params: Record<string, unknown>,+ limits: { timeoutMs?: number; maxBytes?: number } = {},+): Promise<Record<string, unknown> | null> {+ return new Promise((resolve) => {+ const invocation = codexCommandInvocation(command, [...args, 'app-server', '--listen', 'stdio://'], env)+ const hasProvider = args.some(arg => /^(?:model(?:_provider|_providers|_catalog_json)?|openai_base_url)=/.test(arg))+ if (hasProvider && invocation.windowsVerbatimArguments) { resolve(null); return }+ let child: ReturnType<typeof spawn>+ try {+ child = spawn(invocation.command, invocation.args, {+ env, cwd: env.CODEX_HOME, stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true,+ detached: process.platform !== 'win32',+ windowsVerbatimArguments: invocation.windowsVerbatimArguments === true,+ })+ } catch { resolve(null); return }+ let done = false+ let closed = false+ let buffer = ''+ let bytes = 0+ const decoder = new StringDecoder('utf8')+ const finish = (value: Record<string, unknown> | null) => {+ if (done) return+ done = true+ clearTimeout(timer)+ if (closed) { resolve(value); return }+ const cleanupDeadline = setTimeout(() => {+ resolve(value)+ child.stdin?.destroy()+ child.stdout?.destroy()+ child.unref()+ }, 1500)+ cleanupDeadline.unref()+ child.once('close', () => { clearTimeout(kill); clearTimeout(cleanupDeadline); resolve(value) })+ child.stdin?.end()+ const kill = setTimeout(() => {+ if (!child.pid) return+ if (process.platform === 'win32') {+ execFile('taskkill', ['/pid', String(child.pid), '/t', '/f'], { windowsHide: true }, () => {})+ } else {+ try { process.kill(-child.pid, 'SIGKILL') } catch { /* already exited */ }+ }+ }, 250)+ kill.unref()+ }+ const send = (message: object) => {+ if (!done) child.stdin?.write(`${JSON.stringify(message)}\n`)+ }+ const timer = setTimeout(() => finish(null), limits.timeoutMs ?? 10_000)+ timer.unref()+ child.stdin?.on('error', () => finish(null))+ child.once('error', () => finish(null))+ child.once('close', () => { closed = true; finish(null) })+ child.stdout?.on('data', (chunk: Buffer) => {+ bytes += chunk.length+ if (bytes > (limits.maxBytes ?? 2 * 1024 * 1024)) { finish(null); return }+ buffer += decoder.write(chunk)+ for (;;) {+ const newline = buffer.indexOf('\n')+ if (newline < 0 || done) break+ const line = buffer.slice(0, newline)+ buffer = buffer.slice(newline + 1)+ let message: { id?: number; result?: Record<string, unknown>; error?: unknown }+ try { message = JSON.parse(line) } catch { continue }+ if (message.id === 1) {+ if (message.error) { finish(null); return }+ send({ method: 'initialized', params: {} })+ send({ id: 2, method, params })+ } else if (message.id === 2) finish(message.result ?? null)+ }+ })+ send({ id: 1, method: 'initialize', params: {+ clientInfo: { name: 'cumora-catalog', version: '1.0.0' }, capabilities: { experimentalApi: true },+ } })+ })+}diff --git a/server/src/agents/computer/configured-models.ts b/server/src/agents/computer/configured-models.tsnew file mode 100644index 0000000..eb3c42c--- /dev/null+++ b/server/src/agents/computer/configured-models.ts@@ -0,0 +1,152 @@+import { readFileSync, statSync } from 'node:fs'+import { homedir } from 'node:os'+import { isAbsolute, join } from 'node:path'+import type { EngineModelOption } from './model-catalog.js'+import { modelIdOrNull } from './model-id.js'+import { parseProviderModels } from './provider-models.js'++function object(value: unknown): Record<string, unknown> {+ return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}+}++function read(file: string): Record<string, unknown> {+ try {+ if (statSync(file).size > 2 * 1024 * 1024) throw new Error('Model settings exceed the size limit')+ // JSONC comments/trailing commas are allowed; quoted URLs and strings stay intact.+ const text = readFileSync(file, 'utf8')+ .replace(/"(?:\\.|[^"\\])*"|\/\*[\s\S]*?\*\/|\/\/[^\r\n]*/g, token => token.startsWith('"') ? token : '')+ .replace(/"(?:\\.|[^"\\])*"|,\s*(?=[}\]])/g, token => token.startsWith('"') ? token : '')+ const parsed: unknown = JSON.parse(text)+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('Invalid model settings')+ return parsed as Record<string, unknown>+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {}+ throw error+ }+}++function home(override: string | undefined, directory: string): string {+ if (override && !isAbsolute(override)) throw new Error('Engine configuration home must be absolute')+ return override || join(homedir(), directory)+}++/** Read model declarations only. The engine still owns credentials and execution. */+export function configuredEngineModels(id: 'gemini' | 'qwen' | 'zcode', env: NodeJS.ProcessEnv): {+ models: EngineModelOption[]; defaultModel: string | null+} | null {+ let rows: unknown[] = []+ let defaultId: unknown+ let declared = false+ let includeDefault = true+ if (id === 'gemini' || id === 'qwen') {+ const dir = id === 'gemini' ? join(home(env.GEMINI_CLI_HOME, ''), '.gemini') : home(env.QWEN_HOME, '.qwen')+ const settings = read(join(dir, 'settings.json'))+ defaultId = object(settings.model).name+ if (id === 'gemini') {+ defaultId = env.GEMINI_MODEL || defaultId+ const configs = object(settings.modelConfigs)+ const definitions = object(configs.modelDefinitions)+ const aliases = { ...object(configs.aliases), ...object(configs.customAliases) }+ includeDefault = typeof defaultId !== 'string' || object(definitions[defaultId]).isVisible !== false+ declared = ['modelDefinitions', 'aliases', 'customAliases'].some(key => key in configs)+ rows = [+ ...Object.entries(definitions).filter(([, value]) => object(value).isVisible !== false)+ .map(([id, value]) => ({ id, displayName: object(value).displayName })),+ ...Object.keys(aliases).filter(id => !(id in definitions)).map(id => ({ id })),+ ]+ } else {+ // --model selects within the active auth protocol. Advertising a model+ // from another protocol would require changing execution credentials.+ const auth = object(object(settings.security).auth)+ const inferred = env.QWEN_OAUTH ? 'qwen-oauth'+ : env.OPENAI_API_KEY && env.OPENAI_BASE_URL && (env.OPENAI_MODEL || env.QWEN_MODEL) ? 'openai'+ : env.GEMINI_API_KEY && env.GEMINI_MODEL ? 'gemini'+ : (env.GOOGLE_API_KEY || env.GOOGLE_CLOUD_PROJECT) && env.GOOGLE_MODEL ? 'vertex-ai'+ : env.ANTHROPIC_API_KEY && env.ANTHROPIC_MODEL && env.ANTHROPIC_BASE_URL ? 'anthropic' : 'qwen-oauth'+ const protocol = typeof auth.selectedType === 'string' ? auth.selectedType : inferred+ const protocols = object(settings.providerProtocol)+ const vars: Record<string, string | undefined> = {+ openai: env.OPENAI_MODEL || env.QWEN_MODEL, anthropic: env.ANTHROPIC_MODEL,+ gemini: env.GEMINI_MODEL, 'vertex-ai': env.GOOGLE_MODEL,+ }+ defaultId ||= vars[protocol]+ const providers = object(settings.modelProviders)+ declared = 'modelProviders' in settings+ const declarations = Object.entries(providers).filter(([key]) => (protocols[key] ?? key) === protocol)+ .flatMap(([, value]) => Array.isArray(value) ? value : [])+ const chat = (value: unknown) => object(value).imageOnly !== true && object(value).realtimeOnly !== true+ rows = declarations.filter(chat)+ const connection = (value: unknown) => {+ const row = object(value)+ return JSON.stringify([row.baseUrl, row.envKey, row.wireApi, row.api, object(row.generationConfig).customHeaders])+ }+ const routes = new Map<unknown, Set<string>>()+ for (const row of rows) {+ const key = object(row).id+ if (!routes.has(key)) routes.set(key, new Set())+ routes.get(key)!.add(connection(row))+ }+ // --model carries no route discriminator. Hide ambiguous IDs instead of+ // silently selecting the first credential/endpoint registered for them.+ includeDefault = (routes.get(defaultId)?.size ?? 0) <= 1+ && !declarations.some(value => object(value).id === defaultId && !chat(value))+ rows = rows.filter(value => routes.get(object(value).id)!.size === 1)+ }+ } else {+ const root = home(env.ZCODE_HOME, '.zcode')+ const providers = object(read(join(root, 'v2', 'config.json')).provider)+ const personal = object(read(join(root, 'v2', 'provider_config.json')).config)+ const modelRules = object(personal.modelConfigRules)+ const normalize = (id: string) => id.replace(/^account:([a-z0-9]+)-(?:individual-|team-)?coding-plan$/, 'builtin:$1-coding-plan')+ .replace(/^account:([a-z0-9]+)-start-plan$/, 'builtin:$1-start-plan')+ const personalModels = new Map<string, string[]>()+ const disabled = new Set<string>()+ for (const value of [modelRules.providerModelRules, modelRules.manualProviderModelRules]) {+ for (const rule of Array.isArray(value) ? value : []) {+ const row = object(rule)+ if (typeof row.providerId !== 'string' || typeof row.modelId !== 'string') continue+ const key = normalize(row.providerId)+ if (!personalModels.has(key)) personalModels.set(key, [])+ if (object(row.config).enabled === false) disabled.add(`${key}\\${row.modelId}`)+ else personalModels.get(key)!.push(row.modelId)+ }+ }+ const rules = object(personal.providerConfigRules).providerRules+ for (const rule of Array.isArray(rules) ? rules : []) {+ const row = object(rule)+ if (typeof row.providerId !== 'string') continue+ const key = normalize(row.providerId)+ if (key in providers) continue+ const config = object(row.config)+ providers[key] = { name: row.providerName, enabled: row.enabled,+ options: { apiKey: object(config.access).apiKey, baseURL: object(config.api).baseUrl } }+ }+ declared = Object.keys(providers).length > 0+ let firstProvider: string | undefined+ for (const [providerId, value] of Object.entries(providers)) {+ if (env.ZCODE_PROVIDER && normalize(env.ZCODE_PROVIDER) !== providerId) continue+ const provider = object(value)+ const options = object(provider.options)+ let local = false+ try { local = ['localhost', '127.0.0.1', '[::1]'].includes(new URL(String(options.baseURL)).hostname) } catch { /* no local endpoint */ }+ const usable = providerId.startsWith('builtin:')+ ? provider.enabled === true && !!options.apiKey+ : provider.enabled !== false && (!!options.apiKey || options.apiKeyRequired === false || local)+ if (!usable) continue+ firstProvider ??= providerId+ const configured = object(provider.models)+ const personalIds = personalModels.get(providerId)+ const ids = personalIds && !providerId.startsWith('builtin:') ? personalIds : [...Object.keys(configured), ...(personalIds ?? [])]+ rows.push(...ids.filter(id => !disabled.has(`${providerId}\\${id}`))+ .map(id => ({ id: `${providerId}\\${id}`, label: object(configured[id]).name ?? id })))+ }+ if (env.ZCODE_MODEL && firstProvider) {+ defaultId = env.ZCODE_MODEL.includes('\\') ? env.ZCODE_MODEL : `${firstProvider}\\${env.ZCODE_MODEL}`+ }+ includeDefault = typeof defaultId !== 'string' || !disabled.has(defaultId)+ }+ const defaultModel = typeof defaultId === 'string' ? modelIdOrNull(defaultId) : null+ if (defaultModel && includeDefault) rows.push({ id: defaultModel })+ if (!declared && !defaultModel) return null+ return { models: parseProviderModels(rows).map(model => ({ ...model, supportsFastMode: false })), defaultModel }+}diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.tsindex e5bc3c6..61c2bee 100644--- a/server/src/agents/computer/daemon.ts+++ b/server/src/agents/computer/daemon.ts@@ -54,6 +54,7 @@ import { type ActionSurface, actionSurfaceFor, actionSurfaceText, calendarExamplimport { 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 { cachedCodexProvider } from './codex-provider.js'import { migrateCodexSession, migrateCodexSessions } from './codex-session-migration.js'import { runWithSessionRecovery } from './session-recovery.js'@@ -2516,7 +2517,10 @@ export class AgentRunner {if (pinned) return pinnedif (this.adapter.id === 'claude') return 'haiku'if (this.adapter.id === 'grok') return 'grok-4.5'- if (this.adapter.id === 'codex') return 'gpt-5.4-mini'+ if (this.adapter.id === 'codex') {+ const provider = cachedCodexProvider(this.engineEnv())+ return provider?.prefersLocalDefault ? provider.defaultModel ?? '<codex-default>' : 'gpt-5.4-mini'+ }if (this.adapter.id === 'gemini') return 'gemini-2.5-flash-lite'if (this.adapter.id === 'qwen') return 'qwen3-coder-flash'if (this.adapter.id === 'opencode') return this.agent.model ?? '<opencode-default>'diff --git a/server/src/agents/computer/engine.ts b/server/src/agents/computer/engine.tsindex 413496e..241f921 100644--- a/server/src/agents/computer/engine.ts+++ b/server/src/agents/computer/engine.ts@@ -27,13 +27,16 @@ import { randomUUID } from 'node:crypto'import { existsSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'import { access, lstat, mkdir, mkdtemp, rename, rm, writeFile } from 'node:fs/promises'import { homedir, tmpdir } from 'node:os'-import { basename, dirname, join, delimiter as PATH_DELIMITER } from 'node:path'+import { dirname, join, delimiter as PATH_DELIMITER } from 'node:path'import { StringDecoder } from 'node:string_decoder'import { stripLoneSurrogates } from '../text-safety.js'-import { isCustomAnthropicEndpoint, readClaudeUserSettings, withClaudeUserSettingsEnv } from './claude-user-settings.js'+import { CLAUDE_CORE_ENV_KEYS, claudeProviderFingerprint, 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'+import { cachedCodexProvider, codexProviderEnv, codexProviderFingerprint, codexProviderRuntime, prepareCodexProvider } from './codex-provider.js'+import { assertCodexProviderTransport, codexCommandInvocation } from './codex-rpc.js'+import { modelIdOrNull } from './model-id.js'import { supportsNativeFastMode } from '../../../../shared/native-fast-mode.js'const IS_WIN = process.platform === 'win32'@@ -368,19 +371,9 @@ function resolveCodexSpawn(): CodexSpawn {: fallback.commandif (!/\.cmd$/i.test(shim)) return { ...fallback, argsPrefix: [] }- const shimDir = dirname(shim)- const script = join(shimDir, 'node_modules', '@openai', 'codex', 'bin', 'codex.js')- if (!existsSync(script)) return { ...fallback, argsPrefix: [] }-- const nodeCandidates = [- join(shimDir, 'node.exe'),- ...(process.env.PATH ?? '').split(PATH_DELIMITER).filter(Boolean).map((dir) => join(dir, 'node.exe')),- ]- const node = nodeCandidates.find((candidate) => existsSync(candidate))- ?? (/^node(?:\.exe)?$/i.test(basename(process.execPath)) ? process.execPath : null)- if (!node) return { ...fallback, argsPrefix: [] }-- return { command: node, argsPrefix: [script], shell: false, wantsStdinPrompt: false }+ const invocation = codexCommandInvocation(shim, [], process.env)+ if (invocation.windowsVerbatimArguments) return { ...fallback, argsPrefix: [] }+ return { command: invocation.command, argsPrefix: invocation.args, shell: false, wantsStdinPrompt: false }}/** Interactive setup uses exactly the same home as every background call. */@@ -1340,7 +1333,7 @@ class ClaudeSession implements EngineSession {private steerQueue: string[] = []readonly carriesStandingPrompt: boolean- constructor(bin: string, args: string[], opts: EngineSessionArgs, carriesStandingPrompt: boolean) {+ constructor(bin: string, args: string[], opts: EngineSessionArgs, carriesStandingPrompt: boolean, private readonly providerChanged: () => boolean) {this.onLog = opts.onLogthis.onHopUsage = opts.onHopUsagethis.resumePending = !!opts.resumeSessionId@@ -1358,7 +1351,13 @@ class ClaudeSession implements EngineSession {this.die(code ?? (signalName ? 128 : 1), signalName ? `terminated by ${signalName}` : `exited with code ${code}`))}- get alive(): boolean { return !this.exited && this.child.stdin?.writable === true }+ get alive(): boolean {+ if (!this.pending && this.providerChanged()) {+ void this.stop({ force: true })+ return false+ }+ return !this.exited && this.child.stdin?.writable === true+ }get sessionId(): string | null { return this.sid }send(prompt: string): Promise<EngineRunResult> {@@ -1625,7 +1624,11 @@ export function claudeSecureFlags(agentHome: string, env: NodeJS.ProcessEnv, nat* denies those names to every model-spawned subprocess. Compatibility mode* keeps Claude's native settings loading and its already-explicit host risk. */function claudeCoreEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {- return allowUnsandboxedByoa(env) ? { ...env } : withClaudeUserSettingsEnv(env)+ if (allowUnsandboxedByoa(env)) return { ...env }+ if (readClaudeUserSettings(env).readFailure && !CLAUDE_CORE_ENV_KEYS.every(key => env[key] !== undefined)) {+ throw new Error('Cannot read Claude provider settings; retry after its configuration has finished updating')+ }+ return withClaudeUserSettingsEnv(env)}/** Pick the small brain inside the local provider namespace. An explicit@@ -1635,11 +1638,16 @@ function claudeCoreEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {* URL is not a custom endpoint — Claude Code exports it into every child* process, so keying on "the variable is set" dropped Haiku for first-party* accounts. */+function claudeMainModel(env: NodeJS.ProcessEnv, requested?: string | null): string | null {+ return modelIdOrNull(requested || env.ANTHROPIC_MODEL || readClaudeUserSettings(env).defaultModel)+}+function claudeFastModelArgs(env: NodeJS.ProcessEnv, requested?: string | null): string[] {const model = requested?.trim()|| env.CUMORA_TRIAGE_MODEL?.trim()|| env.ANTHROPIC_DEFAULT_HAIKU_MODEL?.trim()|| env.ANTHROPIC_SMALL_FAST_MODEL?.trim()+ || (isCustomAnthropicEndpoint(env.ANTHROPIC_BASE_URL) ? claudeMainModel(env) : null)if (model) return ['--model', model]return isCustomAnthropicEndpoint(env.ANTHROPIC_BASE_URL) ? [] : ['--model', 'haiku']}@@ -1666,7 +1674,7 @@ function claudeTurnEnv(env: NodeJS.ProcessEnv, fastModel?: string | null): NodeJfunction claudeFastModeError(model: string | null | undefined, env: NodeJS.ProcessEnv, enabled: boolean): string | null {if (!enabled) return null- let resolved = model || readClaudeUserSettings(env).defaultModel+ let resolved = claudeMainModel(env, model)if (/^opus(?:\[1m\])?$/i.test(resolved ?? '')) resolved = env.ANTHROPIC_DEFAULT_OPUS_MODEL || resolvedif (!supportsNativeFastMode('claude', resolved)) {return 'Fast mode requires a supported Opus model; select one explicitly to avoid changing the selected model.'@@ -1730,7 +1738,8 @@ class ClaudeAdapter implements EngineAdapter {// uses its default main reasoning brain. One token in, "OK" out — proves the binary runs// and that tier is authed/has quota, with NO tools/MCP/persona.const env = claudeCoreEnv(args.env)- const model = args.tier === 'small' ? claudeFastModelArgs(env) : []+ const main = claudeMainModel(env)+ const model = args.tier === 'small' ? claudeFastModelArgs(env) : main ? ['--model', main] : []const { command, shell, wantsStdinPrompt } = resolveSpawn(this.bin)const base = allowUnsandboxedByoa(env)? ['-p', ...model, '--output-format', 'text', '--dangerously-skip-permissions', '--strict-mcp-config']@@ -1764,10 +1773,12 @@ class ClaudeAdapter implements EngineAdapter {catch (err) { return { ok: false, detail: `could not write standing-prompt probe file: ${err instanceof Error ? err.message : String(err)}` } }const env = claudeCoreEnv(args.env)const { command, shell, wantsStdinPrompt } = resolveSpawn(this.bin)+ const main = claudeMainModel(env)+ const model = main ? ['--model', main] : []const base = allowUnsandboxedByoa(env)- ? ['-p', '--output-format', 'text', '--append-system-prompt-file', promptFile, '--dangerously-skip-permissions']+ ? ['-p', ...model, '--output-format', 'text', '--append-system-prompt-file', promptFile, '--dangerously-skip-permissions']: [- '-p', '--output-format', 'text', '--append-system-prompt-file', promptFile,+ '-p', ...model, '--output-format', 'text', '--append-system-prompt-file', promptFile,'--restricted', '--tools', '', '--strict-mcp-config',]const argv = wantsStdinPrompt ? base : ['-p', DOCTOR_PROMPT, ...base.slice(1)]@@ -1809,7 +1820,8 @@ class ClaudeAdapter implements EngineAdapter {// the dangerous bypass remains only for explicit compatibility mode.// Big-brain model → --model; small-brain → ANTHROPIC_SMALL_FAST_MODEL env.const flags = unsafeEngineArgs('CUMORA_CLAUDE_ARGS')- const model = args.model ? ['--model', args.model] : []+ const selectedModel = claudeMainModel(args.env, args.model)+ const model = selectedModel ? ['--model', selectedModel] : []const env = claudeTurnEnv(args.env, args.fastModel)const fastMode = args.nativeFastMode ?? falseif (fastMode && flags.length) return Promise.resolve({ exitCode: 1, error: 'Fast mode requires removing the CUMORA_CLAUDE_ARGS override so Cumora can preserve the selected model and settings.' })@@ -1840,7 +1852,8 @@ class ClaudeAdapter implements EngineAdapter {// Respect a user's custom flag override (CUMORA_CLAUDE_ARGS) by NOT using the// persistent path — those flags are tuned for the one-shot run; fall back to run().if (unsafeEngineArgs('CUMORA_CLAUDE_ARGS').length) return null- const model = args.model ? ['--model', args.model] : []+ const selectedModel = claudeMainModel(args.env, args.model)+ const model = selectedModel ? ['--model', selectedModel] : []const env = claudeTurnEnv(args.env, args.fastModel)const fastMode = args.nativeFastMode ?? falseif (claudeFastModeError(args.model, env, fastMode)) return null@@ -1866,7 +1879,9 @@ class ClaudeAdapter implements EngineAdapter {'-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose',...resume, ...sys, ...model, ...claudeSecureFlags(args.home, env, fastMode),]- return new ClaudeSession(this.bin, argv, { ...args, env }, carriesStanding)+ const fingerprint = claudeProviderFingerprint(args.env)+ return new ClaudeSession(this.bin, argv, { ...args, env }, carriesStanding,+ () => claudeProviderFingerprint(args.env) !== fingerprint)}}@@ -2035,6 +2050,7 @@ class CodexSession implements EngineSession {private readonly child: ChildProcessprivate readonly authHome: stringprivate readonly authFingerprint: string | null | undefined+ private readonly providerChanged: () => booleanprivate readonly onLog: (line: string) => voidprivate readonly onHopUsage?: (r: EngineHopReport) => void/** Wall-clock when the CURRENT turn started (turn/start request sent), used to@@ -2065,7 +2081,8 @@ class CodexSession implements EngineSession {private cum = { input: 0, cached: 0, output: 0 }private turnStart = { input: 0, cached: 0, output: 0 }- constructor(bin: string, spawnArgs: string[], home: string, env: NodeJS.ProcessEnv, opts: EngineSessionArgs) {+ constructor(bin: string, spawnArgs: string[], home: string, env: NodeJS.ProcessEnv, opts: EngineSessionArgs, providerChanged: () => boolean) {+ this.providerChanged = providerChangedthis.authHome = env.CODEX_HOME!this.authFingerprint = codexAuthFingerprint(this.authHome)this.onLog = opts.onLog@@ -2100,6 +2117,11 @@ class CodexSession implements EngineSession {get alive(): boolean {if (this.exited || this.child.stdin?.writable !== true) return falseif (!this.pending) {+ if (this.providerChanged()) {+ this.onLog('[codex] provider configuration changed; restarting the idle session')+ void this.stop({ force: true })+ return false+ }const auth = codexAuthFingerprint(this.authHome)if (auth !== undefined && auth !== this.authFingerprint) {this.onLog('[codex] login changed; restarting the session with its saved thread')@@ -2326,28 +2348,33 @@ class CodexAdapter implements EngineAdapter {readonly id = 'codex' as constreadonly bin = 'codex'- classify(args: EngineClassifyArgs): Promise<EngineClassifyResult> {+ async classify(args: EngineClassifyArgs): Promise<EngineClassifyResult> {// gpt-5.4-mini works with ChatGPT auth; arbitrary small API models do not.const flags = allowUnsandboxedByoa() ? extraArgs('CUMORA_TRIAGE_ARGS') : []- return this.capture(args, flags.length ? flags : ['--model', args.model || 'gpt-5.4-mini', '--skip-git-repo-check'])+ const provider = await prepareCodexProvider(this.bin, args.env)+ const model = args.model || (provider.prefersLocalDefault ? provider.defaultModel : 'gpt-5.4-mini')+ return this.capture(args, flags.length ? flags : [...(model ? ['--model', model] : []), '--skip-git-repo-check'])}- probe(args: EngineProbeArgs): Promise<EngineClassifyResult> {+ async probe(args: EngineProbeArgs): Promise<EngineClassifyResult> {// Omit --model for the big tier so Codex uses its configured default.- const model = args.tier === 'small' ? ['--model', triageModel('gpt-5.4-mini')] : []+ const provider = await prepareCodexProvider(this.bin, args.env)+ const selected = args.tier === 'small' ? triageModel(provider.prefersLocalDefault ? provider.defaultModel ?? '' : 'gpt-5.4-mini') : null+ const model = selected ? ['--model', selected] : []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)+ private async capture(args: EngineClassifyArgs, flags: string[]): Promise<EngineClassifyResult> {+ const { env, provider } = await codexProviderRuntime(this.bin, args.env)const { command, shell, argsPrefix } = resolveCodexSpawn()+ assertCodexProviderTransport(provider.args, shell)const exec = allowUnsandboxedByoa() ? ['exec'] : codexSecureExecArgs({ home: args.cwd, env }, true)- return spawnCapture(command, [...argsPrefix, ...exec, '--ephemeral', ...flags, ...CODEX_RUNTIME_CONFIG_ARGS, ...codexServiceTierArgs(false), '-'], {+ return spawnCapture(command, [...argsPrefix, ...provider.args, ...exec, '--ephemeral', ...flags, ...CODEX_RUNTIME_CONFIG_ARGS, ...codexServiceTierArgs(false), '-'], {cwd: args.cwd, env, signal: args.signal, onLog: args.onLog, shell, stdinText: args.prompt,})}- probeWake(args: EngineWakeProbeArgs): Promise<EngineWakeProbeResult> {+ async probeWake(args: EngineWakeProbeArgs): Promise<EngineWakeProbeResult> {// Same gates as startSession()'s "fall back to one-shot exec" decision: when// 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@@ -2357,7 +2384,8 @@ class CodexAdapter implements EngineAdapter {|| IS_WIN) {return Promise.resolve({ ok: true, detail: '', skipped: true })}- args = { ...args, env: codexRuntimeEnv(args.env) }+ const { env, provider } = await codexProviderRuntime(this.bin, args.env)+ args = { ...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@@ -2378,7 +2406,7 @@ class CodexAdapter implements EngineAdapter {void terminateEngineTree(child).then(() => resolve(r))}const secure = allowUnsandboxedByoa() ? [] : codexSecureConfigOverrides({ home: args.cwd, env: args.env }, true)- const appServerArgs = [...argsPrefix, ...secure, ...CODEX_RUNTIME_CONFIG_ARGS, 'app-server', '--listen', 'stdio://']+ const appServerArgs = [...argsPrefix, ...provider.args, ...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,})@@ -2451,12 +2479,13 @@ class CodexAdapter implements EngineAdapter {await atomicAgentWrite(join(home, 'AGENTS.md'), PERSONA_HEADER(persona))}- run(args: EngineRunArgs): Promise<EngineRunResult> {+ async run(args: EngineRunArgs): Promise<EngineRunResult> {// `codex exec` is the non-interactive mode. Secure mode applies a custom// 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 { env, provider } = await codexProviderRuntime(this.bin, args.env)+ args = { ...args, env }const flags = unsafeEngineArgs('CUMORA_CODEX_ARGS')const base = flags.length? ['exec', ...flags]@@ -2468,10 +2497,11 @@ class CodexAdapter implements EngineAdapter {const resume = args.resumeSessionId ? ['resume', args.resumeSessionId] : []const { command, shell, argsPrefix } = resolveCodexSpawn()let sessionId = args.resumeSessionId ?? null+ assertCodexProviderTransport(provider.args, shell)let usage: EngineUsage | undefinedlet turnError: string | undefinedconst started = Date.now()- return spawnEngine(command, [...argsPrefix, ...base, ...model, ...CODEX_RUNTIME_CONFIG_ARGS, ...codexServiceTierArgs(args.nativeFastMode ?? false), ...resume, '-'], args, {+ return spawnEngine(command, [...argsPrefix, ...provider.args, ...base, ...model, ...CODEX_RUNTIME_CONFIG_ARGS, ...codexServiceTierArgs(args.nativeFastMode ?? false), ...resume, '-'], args, {shell, stdinText: args.prompt,onStdoutLine(line) {let event@@ -2505,14 +2535,23 @@ class CodexAdapter implements EngineAdapter {if (unsafeEngineArgs('CUMORA_CODEX_ARGS').length|| process.env.CUMORA_CODEX_NO_APP_SERVER === '1'|| IS_WIN) return null- args = { ...args, env: codexRuntimeEnv(args.env) }+ const originalEnv = args.env+ const provider = cachedCodexProvider(originalEnv)+ // First turn can prepare asynchronously through run(); never start on an+ // unprepared connection just because this legacy interface is synchronous.+ if (!provider) return null+ args = { ...args, env: codexProviderEnv(provider, 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 }const { command, argsPrefix } = resolveCodexSpawn()const secure = allowUnsandboxedByoa()? []: codexSecureConfigOverrides({ home: args.home, env: args.env })- return new CodexSession(command, [...argsPrefix, ...secure, ...CODEX_RUNTIME_CONFIG_ARGS, ...codexServiceTierArgs(args.nativeFastMode ?? false), 'app-server', '--listen', 'stdio://'], args.home, args.env, args)+ return new CodexSession(command, [...argsPrefix, ...provider.args, ...secure, ...CODEX_RUNTIME_CONFIG_ARGS, ...codexServiceTierArgs(args.nativeFastMode ?? false), 'app-server', '--listen', 'stdio://'], args.home, args.env, args,+ () => {+ try { return codexProviderFingerprint(originalEnv) !== provider.fingerprint }+ catch { return true }+ })}}diff --git a/server/src/agents/computer/model-catalog.ts b/server/src/agents/computer/model-catalog.tsindex 10d2062..2d00040 100644--- a/server/src/agents/computer/model-catalog.ts+++ b/server/src/agents/computer/model-catalog.ts@@ -1,8 +1,15 @@import { spawn } from 'node:child_process'-import type { EngineId } from './engine.js'+import { createHash } from 'node:crypto'+import { homedir } from 'node:os'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'+import { codexProviderFingerprint, codexProviderRuntime } from './codex-provider.js'+import { readCodexRpc } from './codex-rpc.js'+import { CODEX_RUNTIME_CONFIG_ARGS, codexAuthFingerprint } from './codex-runtime.js'+import { configuredEngineModels } from './configured-models.js'+import type { EngineId } from './engine.js'+import { modelIdOrNull } from './model-id.js'+import { fetchProviderModels, MAX_CATALOG_MODELS, readProviderCatalogFile } from './provider-models.js'export type ModelCatalogSource = 'protocol' | 'cli' | 'presets'export type FastModelScope = 'agent' | 'computer' | 'unsupported'@@ -28,12 +35,11 @@ export interface EngineModelCatalog {supportsCustom: booleanfastModelScope: FastModelScopesource: ModelCatalogSource- /** Every id in `models` is runnable by this computer's account: the provider- * listed it, or the engine's own aliases are first-party by definition.- * Absent means "this build cannot promise that" — builds before this flag- * merged their presets into the reported list, and the app must not present- * such a catalog as the provider's. */+ /** Choices explicitly configured or listed for this connection, without preset+ * contamination. This does not guarantee execution or model capabilities.+ * Absent on older daemons that appended unverified vendor presets. */trustedModels?: boolean+ stale?: boolean}const PRESETS: Record<EngineId, EngineModelCatalog> = {@@ -156,7 +162,10 @@ const PRESETS: Record<EngineId, EngineModelCatalog> = {const MODEL_PROBE_TIMEOUT_MS = 10_000const MODEL_OUTPUT_LIMIT = 2 * 1024 * 1024const MODEL_CACHE_TTL_MS = 15 * 60 * 1000-const catalogCache = new Map<string, { at: number; catalog: EngineModelCatalog }>()+const catalogCache = new Map<string, {+ at: number; fingerprint: string; catalog: EngineModelCatalog+ remote?: EngineModelOption[]; protocol?: EngineModelOption[]+}>()export function clearModelCatalogCache(): void {catalogCache.clear()@@ -177,7 +186,7 @@ function mergeModels(discovered: EngineModelOption[], fallback: EngineModelOptioconst out: EngineModelOption[] = []const seen = new Set<string>()for (const model of [...discovered, ...fallback]) {- const id = clean(model.id, 160)+ const id = modelIdOrNull(model.id)if (!id || seen.has(id)) continueseen.add(id)out.push({@@ -187,7 +196,7 @@ function mergeModels(discovered: EngineModelOption[], fallback: EngineModelOptiorecommendedFor: model.recommendedFor?.filter((tier): tier is 'big' | 'small' => tier === 'big' || tier === 'small'),...(typeof model.supportsFastMode === 'boolean' ? { supportsFastMode: model.supportsFastMode } : {}),})- if (out.length >= 128) break+ if (out.length >= MAX_CATALOG_MODELS) break}return out}@@ -209,7 +218,6 @@ function fromDiscovered(id: EngineId, discovered: EngineModelOption[], source: '// preset id the account did not list is the same lie as an unlisted model.defaultFastModel: discovered.some((model) => model.id === preset.defaultFastModel) ? preset.defaultFastModel : null,source,- // The provider answered, so every id above is one this account can reach.trustedModels: true,}}@@ -223,7 +231,7 @@ function stopChild(child: ReturnType<typeof spawn>): void {child.once('close', () => clearTimeout(timer))}-function runText(command: string, args: string[]): Promise<string> {+function runText(command: string, args: string[], env: NodeJS.ProcessEnv): Promise<string | null> {return new Promise((resolve) => {const invocation = versionCommandInvocation(command, args)let child: ReturnType<typeof spawn>@@ -231,29 +239,32 @@ function runText(command: string, args: string[]): Promise<string> {child = spawn(invocation.command, invocation.args, {stdio: ['ignore', 'pipe', 'pipe'],windowsHide: true,+ env, cwd: homedir(),windowsVerbatimArguments: invocation.windowsVerbatimArguments === true,})} catch {- resolve('')+ resolve(null)return}let output = ''+ let exceeded = falseconst append = (chunk: Buffer) => {+ if (Buffer.byteLength(output) + chunk.length > MODEL_OUTPUT_LIMIT) exceeded = trueif (output.length < MODEL_OUTPUT_LIMIT) output += chunk.toString('utf8').slice(0, MODEL_OUTPUT_LIMIT - output.length)}child.stdout?.on('data', append)- child.stderr?.on('data', append)+ child.stderr?.resume()let settled = false- const finish = () => {+ const finish = (ok = false) => {if (settled) returnsettled = trueclearTimeout(timer)- resolve(output.trim())+ resolve(ok && !exceeded ? output.trim() : null)}const timer = setTimeout(() => { stopChild(child); finish() }, MODEL_PROBE_TIMEOUT_MS)timer.unref?.()- child.once('error', finish)- child.once('close', finish)+ child.once('error', () => finish())+ child.once('close', code => finish(code === 0))})}@@ -268,27 +279,14 @@ function splitIdColumn(line: string): [string, string] {return [stripped.slice(0, sep).trim(), stripped.slice(sep).trim()]}-/** The model id in a listing line's id column, or null when that column is not- * an id at all.- *- * `runText` folds stderr into stdout and ignores the exit status, so whatever- * a CLI printed when it could not list models arrives here as if it were a- * catalog — and the exit status would not have saved us. Measured against a- * real cursor-agent: an account with nothing provisioned prints- * "No models available for this account." and exits 0. That line used to- * become a selectable model with the id "No", merged AHEAD of the built-in- * preset, so the picker offered "No" and the real defaults vanished.- *- * An id occupies its whole column — `auto`, `gpt-5.5`, `gemini-3.8-flash-high`- * — and prose does not. That test needs no vendor's error wording, which is- * the point: the next CLI's phrasing, in a locale we have never seen, still- * fails it. */+/** Even a successful CLI may print prose such as "No models available".+ * Only a complete ID column is a selectable model. */function modelIdToken(column: string): string | null {if (!column || /\s/.test(column)) return null// "Error:", "Warning:" — a bare word wearing sentence punctuation, which can// survive the column rule when a CLI aligns its message.if (/^[a-z]+[.:,;!?]+$/i.test(column)) return null- return column.match(/^[a-z0-9][\w./:@+-]*$/i)?.[0] ?? null+ return modelIdOrNull(column)}/** Parse model-list output shared by OpenCode, pi, Cursor and Antigravity. Exported so new@@ -301,11 +299,10 @@ export function parseListedModels(text: string, style: 'provider' | 'pi' | 'curslet id: string | null = nulllet label: string | null = nulllet recommendedFor: Array<'big' | 'small'> | undefined- if (style === 'provider') {- id = line.match(/(?:^|\s)([a-z0-9][\w.-]*\/[\w./:@+-]+)/i)?.[1] ?? null- } else if (style === 'pi') {- id = line.match(/(?:^|\s)([a-z0-9][\w.-]*\/[\w./:@+-]+)/i)?.[1] ?? null- if (!id) {+ if (style === 'provider' || style === 'pi') {+ const candidate = modelIdToken(splitIdColumn(line)[0])+ if (candidate?.includes('/')) id = candidate+ if (!id && style === 'pi') {const pair = line.replace(/^[*✓>•-]+\s*/, '').split(/\s+/)if (pair.length >= 2 && /^[a-z0-9][\w.-]*$/i.test(pair[0]) && /^[a-z0-9][\w.:@/+-]*[-.:/][\w.:@/+-]*$/i.test(pair[1])) {id = `${pair[0]}/${pair[1]}`@@ -326,8 +323,12 @@ export function parseListedModels(text: string, style: 'provider' | 'pi' | 'cursif (recs.length) recommendedFor = recs}} else {- const candidate = modelIdToken(splitIdColumn(line)[0])- if (candidate && !/^(available|current|default|name|model)$/i.test(candidate)) id = candidate+ const [column, labelPart] = splitIdColumn(line)+ const candidate = modelIdToken(column)+ if (candidate && !/^(available|current|default|id|name|model)$/i.test(candidate)) {+ id = candidate+ label = labelPart || candidate+ }}const normalized = clean(id, 160)if (normalized) {@@ -351,77 +352,37 @@ interface CodexListItem {serviceTiers?: unknown}-function discoverCodex(command: string, env: NodeJS.ProcessEnv): Promise<{ models: EngineModelOption[]; defaultModel: string | null } | null> {- return new Promise((resolve) => {- 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,+async function discoverCodex(command: string, env: NodeJS.ProcessEnv, providerArgs: string[]): Promise<{ models: EngineModelOption[]; defaultModel: string | null } | null> {+ const models: EngineModelOption[] = []+ let defaultModel: string | null = null+ let cursor: string | null = null+ const cursors = new Set<string>()+ const deadline = Date.now() + MODEL_PROBE_TIMEOUT_MS+ let remainingBytes = MODEL_OUTPUT_LIMIT+ for (let page = 0; page < 8; page++) {+ if (Date.now() >= deadline || remainingBytes <= 0) return null+ const result = await readCodexRpc(command, [...CODEX_RUNTIME_CONFIG_ARGS, ...providerArgs], env,+ 'model/list', { includeHidden: false, limit: 128, ...(cursor ? { cursor } : {}) },+ { timeoutMs: deadline - Date.now(), maxBytes: remainingBytes })+ if (!Array.isArray(result?.data)) return null+ remainingBytes -= Buffer.byteLength(JSON.stringify(result))+ for (const row of result.data as CodexListItem[]) {+ const id = modelIdOrNull(typeof row.model === 'string' ? row.model : typeof row.id === 'string' ? row.id : null)+ if (!id) continue+ models.push({ id, label: clean(row.displayName, 160) ?? id, description: clean(row.description, 320),+ recommendedFor: row.isDefault === true ? ['big'] : undefined,+ ...(Array.isArray(row.serviceTiers) ? {+ supportsFastMode: row.serviceTiers.some((tier) => tier?.id === 'fast' || tier?.id === 'priority'),+ } : {}),})- } catch {- resolve(null)- return+ if (row.isDefault === true) defaultModel = id}- child.stdin?.on('error', () => { /* close/error below owns the result */ })- let settled = false- let buffer = ''- const finish = (value: { models: EngineModelOption[]; defaultModel: string | null } | null) => {- if (settled) return- settled = true- clearTimeout(timer)- stopChild(child)- resolve(value)- }- const send = (message: object) => {- try { child.stdin?.write(`${JSON.stringify(message)}\n`) } catch { finish(null) }- }- const timer = setTimeout(() => finish(null), MODEL_PROBE_TIMEOUT_MS)- timer.unref?.()- child.once('error', () => finish(null))- child.once('close', () => finish(null))- child.stdout?.on('data', (chunk: Buffer) => {- buffer += chunk.toString('utf8')- for (;;) {- const newline = buffer.indexOf('\n')- if (newline < 0) break- const line = buffer.slice(0, newline).trim()- buffer = buffer.slice(newline + 1)- if (!line.startsWith('{')) continue- let message: { id?: unknown; result?: { data?: unknown } }- try { message = JSON.parse(line) as typeof message } catch { continue }- if (message.id === 1) {- send({ jsonrpc: '2.0', method: 'initialized', params: {} })- send({ jsonrpc: '2.0', id: 2, method: 'model/list', params: { includeHidden: false, limit: 128 } })- continue- }- if (message.id !== 2 || !Array.isArray(message.result?.data)) continue- const rows = message.result.data as CodexListItem[]- const models = rows.map((row): EngineModelOption | null => {- const id = clean(row.model, 160) ?? clean(row.id, 160)- if (!id) return null- return {- id,- label: clean(row.displayName, 160) ?? id,- description: clean(row.description, 320),- recommendedFor: row.isDefault === true ? ['big'] : undefined,- ...(Array.isArray(row.serviceTiers) ? {- supportsFastMode: row.serviceTiers.some((tier) => tier?.id === 'fast' || tier?.id === 'priority'),- } : {}),- }- }).filter((row): row is EngineModelOption => row !== null)- const defaultModel = rows.find((row) => row.isDefault === true)- finish({ models, defaultModel: clean(defaultModel?.model, 160) ?? clean(defaultModel?.id, 160) })- }- })- send({- jsonrpc: '2.0', id: 1, method: 'initialize',- params: { clientInfo: { name: 'cumora-daemon', version: '1.0.0' }, capabilities: { experimentalApi: true } },- })- })+ cursor = typeof result.nextCursor === 'string' ? result.nextCursor : null+ if (!cursor || models.length >= MAX_CATALOG_MODELS) return { models: models.slice(0, MAX_CATALOG_MODELS), defaultModel }+ if (cursors.has(cursor)) return null+ cursors.add(cursor)+ }+ return null}/** Discover the account/config-specific catalog without making a model call.@@ -437,53 +398,122 @@ export async function discoverEngineModelCatalog(): Promise<EngineModelCatalog> {const preset = clonePreset(id)if (!binPath) return preset- const cacheKey = `${id}\u0000${binPath}`+ // Unreadable configuration cannot establish which connection owns old rows.+ const failed = (): EngineModelCatalog => ({+ ...preset, models: [], defaultModel: null, defaultFastModel: null, stale: true,+ })+ // Native listings already resolve all configured backend providers. Re-read+ // them on a rescan rather than caching under an unknown connection identity.+ const listing = {+ cursor: ['models', 'cursor'], opencode: ['models', 'provider'],+ pi: ['--list-models', 'pi'], antigravity: ['models', 'antigravity'],+ grok: ['models', 'cursor'],+ } as const+ if (id in listing) {+ const [arg, style] = listing[id as keyof typeof listing]+ const output = await runText(binPath, [arg], env)+ const models = output === null ? [] : parseListedModels(output, style)+ return models.length || output === '' ? fromDiscovered(id, models, 'cli', null) : preset+ }+ if (id === 'gemini' || id === 'qwen' || id === 'zcode') {+ try {+ const configured = configuredEngineModels(id, env)+ return configured ? { ...fromDiscovered(id, configured.models, 'cli', configured.defaultModel),+ defaultFastModel: null, prefersLocalDefault: true } : preset+ } catch { return failed() }+ }+ if (id !== 'claude' && id !== 'codex') return preset+ const settings = id === 'claude' ? readClaudeUserSettings(env) : null+ if (settings?.readFailure) return failed()+ const coreEnv = id === 'claude' ? withClaudeUserSettingsEnv(env) : env+ let codex+ try {+ if (id === 'codex') codex = await codexProviderRuntime(binPath, env)+ } catch { return failed() }+ const identity = id === 'claude'+ ? [coreEnv.ANTHROPIC_BASE_URL, coreEnv.ANTHROPIC_API_KEY, coreEnv.ANTHROPIC_AUTH_TOKEN]+ : [codex?.provider.identity, codexAuthFingerprint()]+ const hash = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex')+ const cacheKey = `${id}\0${binPath}\0${hash(identity)}`+ const fingerprint = id === 'claude' ? hash([settings, coreEnv.ANTHROPIC_MODEL, coreEnv.ANTHROPIC_DEFAULT_OPUS_MODEL,+ coreEnv.ANTHROPIC_DEFAULT_SONNET_MODEL, coreEnv.ANTHROPIC_DEFAULT_HAIKU_MODEL, coreEnv.ANTHROPIC_SMALL_FAST_MODEL])+ : hash([codexProviderFingerprint(env), readProviderCatalogFile(codex?.provider.catalogFile ?? null)])const cached = catalogCache.get(cacheKey)- if (!refresh && cached && Date.now() - cached.at < MODEL_CACHE_TTL_MS) return cached.catalog+ if (!refresh && cached && cached.fingerprint === fingerprint && Date.now() - cached.at < MODEL_CACHE_TTL_MS) return cached.cataloglet catalog: EngineModelCatalog | null = null- if (id === 'claude') {- const settings = readClaudeUserSettings(env)- const coreEnv = withClaudeUserSettingsEnv(env)- const defaultFastModel = clean(coreEnv.ANTHROPIC_DEFAULT_HAIKU_MODEL, 160)- ?? clean(coreEnv.ANTHROPIC_SMALL_FAST_MODEL, 160)- const prefersLocalDefault = isCustomAnthropicEndpoint(clean(coreEnv.ANTHROPIC_BASE_URL, 4096))- const configured = [settings.defaultModel, defaultFastModel]- .filter((model): model is string => !!model)- .map((model) => ({ id: model, label: model }))- if (configured.length || prefersLocalDefault) {- catalog = {- ...preset,- // Anthropic aliases are useful first-party presets, but claiming they- // exist on an arbitrary custom endpoint is misleading. Operators can- // still type any provider-specific id via supportsCustom.- models: mergeModels(configured, prefersLocalDefault ? [] : preset.models),- defaultModel: settings.defaultModel,+ let remoteModels = cached?.remote+ let protocolModels = cached?.protocol+ if (id === 'claude' && settings) {+ const defaultFastModel = modelIdOrNull(coreEnv.ANTHROPIC_DEFAULT_HAIKU_MODEL)+ ?? modelIdOrNull(coreEnv.ANTHROPIC_SMALL_FAST_MODEL)+ const prefersLocalDefault = isCustomAnthropicEndpoint(coreEnv.ANTHROPIC_BASE_URL)+ const defaultModel = modelIdOrNull(coreEnv.ANTHROPIC_MODEL) ?? settings.defaultModel+ const mapped = [defaultModel, coreEnv.ANTHROPIC_DEFAULT_OPUS_MODEL, coreEnv.ANTHROPIC_DEFAULT_SONNET_MODEL,+ coreEnv.ANTHROPIC_DEFAULT_HAIKU_MODEL, coreEnv.ANTHROPIC_SMALL_FAST_MODEL]+ .filter((model): model is string => !!model).map(id => ({ id, label: id }))+ let remote: EngineModelOption[] | null = null+ const hasPicker = settings.models !== undefined+ if (!hasPicker && prefersLocalDefault && coreEnv.ANTHROPIC_BASE_URL) {+ try {+ const base = new URL(coreEnv.ANTHROPIC_BASE_URL)+ if (['http:', 'https:'].includes(base.protocol) && !base.username && !base.password) {+ const path = base.pathname.replace(/\/+$/, '')+ base.pathname = `${path}${/\/v1$/.test(path) ? '' : '/v1'}/models`+ base.hash = ''+ const token = coreEnv.ANTHROPIC_AUTH_TOKEN+ const key = coreEnv.ANTHROPIC_API_KEY+ remote = await fetchProviderModels({ url: base.href, headers: {+ 'anthropic-version': '2023-06-01', ...(token ? { Authorization: `Bearer ${token}` } : {}),+ ...(key ? { 'x-api-key': key } : {}),+ } })+ }+ } catch { /* Only local declarations remain available. */ }+ }+ const configured = mergeModels(settings.models ?? [], mapped)+ remoteModels = hasPicker ? undefined : remote ?? cached?.remote+ if (hasPicker || configured.length || prefersLocalDefault || remote !== null) {+ catalog = { ...preset,+ models: mergeModels(configured, remoteModels ?? (hasPicker || prefersLocalDefault ? [] : preset.models))+ .map(model => prefersLocalDefault ? { ...model, supportsFastMode: false } : model),+ defaultModel,defaultFastModel: defaultFastModel ?? (prefersLocalDefault ? null : preset.defaultFastModel),- prefersLocalDefault,- source: 'cli',- // First-party aliases are runnable by any Anthropic account; on a custom- // endpoint they were not merged at all.- trustedModels: true,+ prefersLocalDefault, source: 'cli', trustedModels: true,+ ...(!hasPicker && prefersLocalDefault && coreEnv.ANTHROPIC_BASE_URL && remote === null ? { stale: true } : {}),+ }+ }+ } else if (codex) {+ const { provider, env: runtimeEnv } = codex+ const result = await discoverCodex(binPath, runtimeEnv, provider.args)+ const remote = !result && !cached?.protocol && provider.connection ? await fetchProviderModels(provider.connection) : null+ const local = readProviderCatalogFile(provider.catalogFile)+ if (provider.defaultModel && !local.some(model => model.id === provider.defaultModel)) {+ local.push({ id: provider.defaultModel, label: provider.defaultModel })+ }+ remoteModels = result || cached?.protocol ? undefined : remote ?? cached?.remote+ protocolModels = result?.models ?? cached?.protocol+ if (result || remote !== null || local.length || cached) {+ const protocol = protocolModels ?? []+ const native = new Map(protocol.map(model => [model.id, model]))+ const explicit = local.map(model => ({ ...native.get(model.id), ...model,+ label: model.label !== model.id ? model.label : native.get(model.id)?.label ?? model.label,+ description: model.description ?? native.get(model.id)?.description,+ ...(!native.has(model.id) ? { supportsFastMode: false } : {}),+ }))+ const rows = mergeModels(explicit, mergeModels(protocol, (remoteModels ?? [])+ .map(model => ({ ...model, supportsFastMode: false }))))+ catalog = { ...fromDiscovered(id, rows, 'protocol', provider.defaultModel ?? result?.defaultModel ?? null),+ prefersLocalDefault: provider.prefersLocalDefault,+ ...(provider.prefersLocalDefault ? { defaultFastModel: null } : {}),+ ...(!result ? { stale: true } : {}),}}- } else if (id === 'codex') {- const result = await discoverCodex(binPath, env)- if (result?.models.length) catalog = fromDiscovered(id, result.models, 'protocol', result.defaultModel)- } else if (id === 'cursor') {- const models = parseListedModels(await runText(binPath, ['models']), 'cursor')- if (models.length) catalog = fromDiscovered(id, models, 'cli', null)- } else if (id === 'opencode') {- const models = parseListedModels(await runText(binPath, ['models']), 'provider')- if (models.length) catalog = fromDiscovered(id, models, 'cli', null)- } else if (id === 'pi') {- const models = parseListedModels(await runText(binPath, ['--list-models']), 'pi')- if (models.length) catalog = fromDiscovered(id, models, 'cli', null)- } else if (id === 'antigravity') {- const models = parseListedModels(await runText(binPath, ['models']), 'antigravity')- if (models.length) catalog = fromDiscovered(id, models, 'cli', null)}- if (catalog) catalogCache.set(cacheKey, { at: Date.now(), catalog })+ if (!catalog && cached) return { ...cached.catalog, stale: true }+ if (catalog) {+ if (catalogCache.size >= 64 && !catalogCache.has(cacheKey)) catalogCache.delete(catalogCache.keys().next().value!)+ catalogCache.set(cacheKey, { at: Date.now(), fingerprint, catalog, remote: remoteModels, protocol: protocolModels })+ }return catalog ?? preset}diff --git a/server/src/agents/computer/model-id.ts b/server/src/agents/computer/model-id.tsindex b255edd..e2e22f6 100644--- a/server/src/agents/computer/model-id.ts+++ b/server/src/agents/computer/model-id.ts@@ -1,7 +1,8 @@/** Model ids are interpolated into engine argv. On Windows that argv is joined* into a cmd.exe command line, so the id has to be a single token. Vendor ids- * use letters, digits, and `.` `_` `:` `/` `-`. Anything else is rejected. */-export const MODEL_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/+ * include provider routes, `auto/model[1m]`, and ZCode's ACP `provider\model`+ * selector. Backslashes are allowed only as that single provider delimiter. */+export const MODEL_ID_RE = /^(?!.*(?:^|[\\/])\.\.?(?:[\\/]|$))(?:[A-Za-z0-9][A-Za-z0-9._:-]*\\)?[A-Za-z0-9][A-Za-z0-9._:/+-]{0,127}(?:\[[A-Za-z0-9._+-]{1,16}\])?$/export class InvalidModelIdError extends Error {constructor() {@@ -16,9 +17,10 @@ export function parseModelId(value: unknown): string | null | undefined {if (value === undefined) return undefinedif (value === null) return nullif (typeof value !== 'string') return undefined+ if (/[\u0000-\u001f\u007f]/.test(value)) throw new InvalidModelIdError()const trimmed = value.trim()if (!trimmed) return null- if (!MODEL_ID_RE.test(trimmed)) throw new InvalidModelIdError()+ if (trimmed.length > 128 || !MODEL_ID_RE.test(trimmed)) throw new InvalidModelIdError()return trimmed}diff --git a/server/src/agents/computer/provider-models.ts b/server/src/agents/computer/provider-models.tsnew file mode 100644index 0000000..097675c--- /dev/null+++ b/server/src/agents/computer/provider-models.ts@@ -0,0 +1,88 @@+import { readFileSync, statSync } from 'node:fs'+import type { EngineModelOption } from './model-catalog.js'+import { modelIdOrNull } from './model-id.js'++export const MAX_CATALOG_MODELS = 1024+const MAX_BYTES = 2 * 1024 * 1024++export interface ProviderCatalogConnection {+ url: string+ headers: Record<string, string>+ query?: Record<string, string>+}++function text(value: unknown, max: number): string | undefined {+ if (typeof value !== 'string') return undefined+ return value.replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, max) || undefined+}++/** Deliberately ignore generic capability claims (especially native Fast Mode). */+export function parseProviderModels(rows: unknown): EngineModelOption[] {+ if (!Array.isArray(rows)) return []+ return rows.slice(0, MAX_CATALOG_MODELS).flatMap((row) => {+ if (!row || typeof row !== 'object') return []+ const id = modelIdOrNull(typeof row.model === 'string' ? row.model : typeof row.id === 'string' ? row.id : typeof row.slug === 'string' ? row.slug : null)+ if (!id) return []+ return [{+ id,+ label: text(row.label ?? row.display_name ?? row.displayName ?? row.name, 160) ?? id,+ description: text(row.description, 320),+ }]+ })+}++export function readProviderCatalogFile(file: string | null): EngineModelOption[] {+ if (!file) return []+ try {+ if (statSync(file).size > MAX_BYTES) return []+ const parsed = JSON.parse(readFileSync(file, 'utf8'))+ return parseProviderModels(parsed.models ?? parsed.data ?? parsed)+ } catch { return [] }+}++/** A null result is a failed refresh; [] is a successful, explicitly empty catalog. */+export async function fetchProviderModels(connection: ProviderCatalogConnection): Promise<EngineModelOption[] | null> {+ const models: EngineModelOption[] = []+ const url = new URL(connection.url)+ for (const [key, value] of Object.entries(connection.query ?? {})) url.searchParams.set(key, value)+ const cursors = new Set<string>()+ const controller = new AbortController()+ const timeout = setTimeout(() => controller.abort(), 3500)+ timeout.unref()+ let total = 0+ try {+ for (let page = 0; page < 8; page++) {+ const response = await fetch(url, {+ headers: connection.headers, redirect: 'error', signal: controller.signal,+ })+ if (!response.ok || !response.body) {+ await response.body?.cancel()+ return null+ }+ const reader = response.body.getReader()+ const chunks: Uint8Array[] = []+ try {+ for (;;) {+ const next = await reader.read()+ if (next.done) break+ total += next.value.length+ if (total > MAX_BYTES) { await reader.cancel(); return null }+ chunks.push(next.value)+ }+ } finally { reader.releaseLock() }+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8'))+ const rows = body.data ?? body.models+ if (!Array.isArray(rows)) return null+ models.push(...parseProviderModels(rows))+ if (models.length >= MAX_CATALOG_MODELS) return models.slice(0, MAX_CATALOG_MODELS)+ const cursor = body.next_cursor ?? body.nextCursor ?? (body.has_more === true ? body.last_id : null)+ if (typeof cursor !== 'string' || !cursor) return body.has_more === true ? null : models+ if (cursors.has(cursor)) return null+ cursors.add(cursor)+ // Only a cursor may be returned by the server, never a URL to fetch.+ url.searchParams.set(body.has_more === true ? 'after_id' : 'cursor', cursor)+ }+ return null+ } catch { return null }+ finally { clearTimeout(timeout); controller.abort() }+}diff --git a/server/src/agents/computer/registry.ts b/server/src/agents/computer/registry.tsindex 5f0a30d..6856559 100644--- a/server/src/agents/computer/registry.ts+++ b/server/src/agents/computer/registry.ts@@ -15,7 +15,7 @@* runtime/jwt.ts — the same token a pod gets)*/import { type ProviderProfileMetadata, isProviderProfileId, sanitizeProviderProfiles } from './provider-profiles.js'-import { InvalidModelIdError, parseModelId } from './model-id.js'+import { InvalidModelIdError, modelIdOrNull, parseModelId } from './model-id.js'import { createHash, randomBytes, randomUUID } from 'node:crypto'import { pool } from '../../db/pool.js'import { audit } from '../../auth.js'@@ -188,10 +188,10 @@ function sanitizeModelCatalog(raw: unknown): EngineModelCatalog | undefined {const models: EngineModelOption[] = []const seen = new Set<string>()if (Array.isArray(rec.models)) {- for (const rawModel of rec.models.slice(0, 128)) {+ for (const rawModel of rec.models.slice(0, 1024)) {if (!rawModel || typeof rawModel !== 'object') continueconst model = rawModel as Record<string, unknown>- const id = displayString(model.id, 160)+ const id = typeof model.id === 'string' ? modelIdOrNull(model.id) : nullif (!id || seen.has(id)) continueseen.add(id)const recommendedFor = Array.isArray(model.recommendedFor)@@ -217,6 +217,7 @@ function sanitizeModelCatalog(raw: unknown): EngineModelCatalog | undefined {// Passed through, never defaulted: only a daemon that knows its list is// preset-free may say so, and the app withholds model rows without it....(rec.trustedModels === true ? { trustedModels: true } : {}),+ ...(rec.stale === true ? { stale: true } : {}),}}@@ -804,15 +805,13 @@ export async function listAgentsForComputer(computerId: string, supportsProvider? engineDefaults as EngineDefaultsMap: {}) as EngineDefaultsMapconst engineDefaultsForAgent = agent.engine ? defaults[agent.engine] : undefined- // A custom Claude endpoint owns its model namespace. Its reported defaults- // fill only unpinned fields; explicit per-Agent choices still win. When it- // cannot name a main/fast default, leave that field null so the CLI chooses- // instead of crossing an Anthropic deployment pin into the provider.- if (r.engine === 'claude' && localCatalog?.prefersLocalDefault) {+ // Resolve unpinned defaults locally each turn so a provider change cannot+ // turn an old catalog default into a permanent Agent pin.+ if (localCatalog?.prefersLocalDefault) {return {...agent,- model: agent.model ?? engineDefaultsForAgent?.model ?? localCatalog.defaultModel,- fastModel: agent.fastModel ?? engineDefaultsForAgent?.fastModel ?? localCatalog.defaultFastModel,+ model: agent.model ?? engineDefaultsForAgent?.model ?? null,+ fastModel: agent.fastModel ?? engineDefaultsForAgent?.fastModel ?? null,}}// Apply engine_defaults before deploy-level defaultsdiff --git a/src/components/AgentEditor.tsx b/src/components/AgentEditor.tsxindex 51568e3..352bce8 100644--- a/src/components/AgentEditor.tsx+++ b/src/components/AgentEditor.tsx@@ -105,7 +105,7 @@ export function AgentEditor({ agent, onClose, onSaved }: Props) {const selectedProfile = profiles.find((p) => p.id === providerProfile)const modelCatalog = providerProfile ? {models: [], defaultModel: selectedProfile?.model, defaultFastModel: selectedProfile?.fastModel,- supportsCustom: true, fastModelScope: 'agent',+ supportsCustom: true, fastModelScope: 'agent', stale: false,} : detectedEngine?.modelCatalog// Per-computer engine model defaults (configured on the Computer card).// When the local CLI catalog can't name a default (e.g. custom endpoints),@@ -170,7 +170,8 @@ export function AgentEditor({ agent, onClose, onSaved }: Props) {})),]const catalogNotice = !isByoa ? ''- : modelCatalogTrust === 'guessed' ? t('agent.modelCatalogGuessed')+ : modelCatalog?.stale ? t('agent.modelCatalogStale')+ : modelCatalogTrust === 'guessed' ? t('agent.modelCatalogGuessed'): modelCatalogTrust === 'unverified' ? t('agent.modelCatalogUnverified'): ''const origin = getPairingServerOrigin()diff --git a/src/desktop/MeView.tsx b/src/desktop/MeView.tsxindex 0856c59..bf96a67 100644--- a/src/desktop/MeView.tsx+++ b/src/desktop/MeView.tsx@@ -1319,6 +1319,9 @@ function ComputersTab() {)}</fieldset><p className="text-[11px] text-ink-500">{t('me.engineModelHelp')}</p>+ {row.modelCatalog?.stale && (+ <p className="text-[11px] text-ink-500">{t('agent.modelCatalogStale')}</p>+ )}{catalogTrust(row.modelCatalog) === 'guessed' && (<p className="text-[11px] text-ink-500">{t('agent.modelCatalogGuessed')}</p>)}diff --git a/src/lib/engine-model-choices.ts b/src/lib/engine-model-choices.tsindex 34a0a79..43a3d82 100644--- a/src/lib/engine-model-choices.ts+++ b/src/lib/engine-model-choices.ts@@ -10,9 +10,9 @@* Only a catalog the daemon vouches for produces model rows. Two states do not:** - `presets`: the engine never listed anything, so the ids are Cumora's- * compiled-in guesses about the account (gemini, qwen, zcode and maka are- * never probed at all). Offering them means offering models the account may- * not run, each inheritable by every Agent — so they are not offered at all.+ * compiled-in guesses about the account. Offering them means offering models+ * the account may not run, each inheritable by every Agent — so they are not+ * offered at all.* - `unverified`: a daemon that predates `trustedModels` reported a catalog* after merging its presets into the provider's answer, while still labelling* it `protocol`/`cli`. The tail is unvouched-for and indistinguishable from a@@ -44,10 +44,11 @@ export interface ModelChoiceCatalog {* itself (a provider profile), which is why `catalogTrust` treats absent as* reported rather than as a failure. */source?: 'protocol' | 'cli' | 'presets'- /** Set by a daemon that promises every id above is runnable by this account.+ /** Set by a daemon whose choices were explicitly configured or listed.* Absent on daemons old enough to have merged their presets into a reported* listing, which is the case `catalogTrust` calls `unverified`. */trustedModels?: boolean+ stale?: boolean}export type CatalogTrust = 'reported' | 'guessed' | 'unverified' | 'missing'diff --git a/src/locales/en.ts b/src/locales/en.tsindex 7cf01a4..99fae0b 100644--- a/src/locales/en.ts+++ b/src/locales/en.ts@@ -473,6 +473,7 @@ export const en = {'agent.providerMissing': 'Unavailable: {id}','agent.modelLabelByoa': 'Big-brain model (大脑)','agent.modelHintByoaCatalog': 'Choose a model available to this computer\'s engine, or search and enter a custom model id.',+ 'agent.modelCatalogStale': 'Model discovery could not fully refresh. Current choices may be stale; check the engine configuration and refresh. Availability is checked when a model runs.','agent.modelCatalogGuessed': 'This engine reported no model list, so there is nothing to pick from. Cumora only has built-in guesses for it, and those may not be available to this account — type the model id instead.','agent.modelCatalogUnverified': 'This computer\'s daemon is too old to say which models its engine can actually run, so the list is hidden. Type the model id, or update the daemon on that computer and refresh.','agent.fastHintByoaCatalog': 'Per-agent model for lightweight decisions such as inbox triage. Blank uses the engine\'s small-brain default.',diff --git a/src/locales/zh-CN.ts b/src/locales/zh-CN.tsindex 39f392a..de3e900 100644--- a/src/locales/zh-CN.ts+++ b/src/locales/zh-CN.ts@@ -475,6 +475,7 @@ export const zhCN: Partial<Record<keyof typeof en, string>> = {'agent.providerMissing': '不可用:{id}','agent.modelLabelByoa': '主力模型(大脑)','agent.modelHintByoaCatalog': '从这台计算机上的引擎实际可用模型中选择;也可以搜索并输入自定义模型 ID。',+ 'agent.modelCatalogStale': '模型目录未能完整刷新,当前选项可能已过期;请检查引擎配置后刷新。实际可用性以执行结果为准。','agent.modelCatalogGuessed': '该引擎没有报告模型列表,因此这里没有可选项。Cumora 只有内置猜测值,未必对你的账号可用——请直接输入模型 ID。','agent.modelCatalogUnverified': '这台计算机的守护进程版本过旧,无法确认引擎实际可用的模型,因此列表已隐藏。请直接输入模型 ID,或在该计算机上升级守护进程后刷新。','agent.fastHintByoaCatalog': '用于收件箱分流等轻量判断的成员级模型。留空时使用该引擎的小脑默认值。',diff --git a/src/types.ts b/src/types.tsindex 060c984..f193990 100644--- a/src/types.ts+++ b/src/types.ts@@ -25,10 +25,11 @@ export interface EngineModelCatalog {supportsCustom: booleanfastModelScope: 'agent' | 'computer' | 'unsupported'source: 'protocol' | 'cli' | 'presets'- /** Set by a daemon that promises every id in `models` is runnable by this- * account. Absent on older daemons, whose catalogs merged built-in presets+ /** Explicitly configured/listed choices, without a guarantee of execution.+ * Absent on older daemons, whose catalogs merged built-in presets* into the reported list — the picker withholds those rows. */trustedModels?: boolean+ stale?: boolean}export interface DetectedEngine {