Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
fix(byoa): support custom Claude providers in secure mode (#189)
OKNOTOK2a56b1162a99
diff --git a/docs/BYOA.md b/docs/BYOA.mdindex cb06cdf..d95874b 100644--- a/docs/BYOA.md+++ b/docs/BYOA.md@@ -256,8 +256,12 @@ provider hops; uncached input, output+reasoning, and cache read/write tokens mapto Cumora's common usage ledger without double-counting. OpenCode may race itsfinal `step_finish` against the terminal idle event, so a clean process exit isthe completion signal and accounting is best-effort when that event is absent.-Model selection: the per-agent `participants.model` / `fast_model`-columns, else the matching deploy-level `CUMORA_DEFAULT_*_MODEL` pin.+Model selection normally remains an explicit per-agent `participants.model` /+`fast_model`, then the matching deploy-level `CUMORA_DEFAULT_*_MODEL` pin. When+a Computer reports a custom Claude endpoint, its configured main/fast defaults+fill unpinned fields first. It may also own an unnamed local default; in that+case the daemon passes no model flag rather than crossing a vendor-specific+deployment pin into the wrong namespace.### Secure default and compatibility opt-in@@ -267,9 +271,16 @@ fail-closed host boundary:- Claude Code on macOS, Linux, and WSL2 runs in restricted mode with filesystemisolation, an empty strict network allowlist, no Bash/PowerShell/web tools,no unsandboxed retry, and an explicit deny list for every inherited- environment variable not needed by the fixed Cumora MCP bridge. Claude Code+ environment variable not needed by the fixed Cumora MCP bridge. Because+ restricted mode ignores user settings, the daemon imports only+ `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_BASE_URL`, and+ `ANTHROPIC_SMALL_FAST_MODEL` from Claude's user settings into the trusted+ Claude core; those names remain denied to model-spawned subprocesses and the+ Cumora never serializes the values into argv, its logs, Agent files, or server+ reports. Claude Code2.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. See+ [ADR 0005](decisions/0005-secure-claude-provider-bootstrap.md).- Codex runs one-shot with user config and exec-policy rules ignored. A custompermission profile permits minimal runtime reads and writes only under theagent home, disables command network, and gives model-spawned commands only@@ -297,23 +308,27 @@ because the daemon cannot prove that they preserve the sandbox.### Running against a custom provider-Those pins are resolved server-side and name Anthropic / OpenAI models. If your-local engine CLI is pointed at a **custom provider** (CC Switch and-friends), it has never heard of `claude-opus-4-7`, so every turn fails with-*"There's an issue with the selected model"* even though the CLI works fine in-your terminal.+Custom providers (CC Switch and friends) often store their endpoint,+authentication value, and default model in `~/.claude/settings.json`. Secure+Claude imports only that provider bootstrap subset, reports the configured+default model without reporting credentials or endpoint details, and gives it+precedence over Cumora's deploy-level Anthropic pin for Agents left on **Follow+engine default**. Explicit per-Agent model choices still win.-Set `CUMORA_ENGINE_MODEL` on the daemon to fix it:+`CUMORA_ENGINE_MODEL` remains the operator override when the provider needs a+different policy or an older daemon has not reported its local default:| value | effect || --- | --- |-| unset | use the model Cumora pinned (default) |+| unset | explicit Agent pin → reported local default → deploy pin → CLI default || `local` | pass **no** model at all — the CLI runs on whatever it is already configured for, and the small/fast pin is dropped too || any model id | use that model instead of the pinned one |-Pair it with `CUMORA_TRIAGE_MODEL` if your provider also lacks the small brain-(`haiku` / `gpt-5.4-mini`); `cumora agent computer doctor` probes the same model-that triage will use, so a green doctor means real wakes will work.+The configured `ANTHROPIC_SMALL_FAST_MODEL` is also used for local triage. When+a custom endpoint does not name a fast model, Cumora passes no triage model and+lets the provider choose instead of injecting the first-party `haiku` alias.+`CUMORA_TRIAGE_MODEL` remains an explicit override, and `cumora agent computer+doctor` probes that same resolution path.```bashCUMORA_ENGINE_MODEL=local CUMORA_TRIAGE_MODEL=local-small cumora agent computer@@ -377,8 +392,9 @@ inner state stays local.the operator's existing login, but model-spawned commands cannot read thatlogin or inherit provider credentials in secure mode. Each agent gets its ownwritable home; its credential-free IPC namespace and executable bridge stay-outside that home. Claude restricted mode ignores user/project settings while-retaining core authentication; Codex `exec --ignore-user-config --ignore-rules`+outside that home. Claude restricted mode ignores user/project settings;+Cumora restores only its allowlisted provider bootstrap to the trusted core.+Codex `exec --ignore-user-config --ignore-rules`does the same and marks the project untrusted. Secure engine startup also dropsempty, relative, and agent-home entries from `PATH`, so a model-planted`claude`/`codex` executable cannot run before the next sandbox is established.diff --git a/docs/COORDINATION.md b/docs/COORDINATION.mdindex 90a0812..731310a 100644--- a/docs/COORDINATION.md+++ b/docs/COORDINATION.md@@ -54,19 +54,23 @@ making a clear decision in front of correct state.**In order from "always on, no brain attention" to "soft, brain-mediated":-### 1. Per-agent model pin (deploy env)+### 1. Per-agent model pin and custom-Claude resolution`CUMORA_DEFAULT_CLAUDE_MODEL=claude-opus-4-7` on the prod server.-`listAgentsForComputer` (`server/src/agents/computer/registry.ts`) substitutes-this when `participants.model` is null. The daemon then spawns claude with-explicit `--model claude-opus-4-7` instead of inheriting whatever the local-claude CLI defaults to.+An explicit `participants.model` wins. Otherwise `listAgentsForComputer`+(`server/src/agents/computer/registry.ts`) normally substitutes the deploy pin.+For a Computer that reports a custom Claude endpoint, its provider-local+main/fast defaults fill unpinned fields first. The provider may mark an unnamed+local default authoritative; the daemon then omits `--model` rather than sending+an Anthropic model into another namespace.**Why this exists:** the local claude CLI silently flipped its default from`opus-4-7` to `opus-4-8` partway through a session in 2026-05-31. Opus-4-8 ismore cautious about prompt-injection-like patterns and behaves differently inmulti-agent flows. Withoutthe pin, every user's behavior drifts whenever Anthropic ships a model.-Override per-agent by setting `participants.model` for a specific id.+Override per-agent by setting `participants.model` for a specific id. Secure+Claude provider bootstrap and the reason credentials stay outside model tools+are recorded in [ADR 0005](decisions/0005-secure-claude-provider-bootstrap.md).### 2. Per-computer big-brain concurrency cap (daemon)`CUMORA_BYOA_MAX_CONCURRENT_BIG_BRAIN` (default **6**; drop to 2-4 on very@@ -668,7 +672,7 @@ one and re-test. Don't pile on.| Var | Default | Notes ||---|---|---|-| `CUMORA_DEFAULT_CLAUDE_MODEL` | unset | Deploy-level model pin (e.g. `claude-opus-4-7`). Per-agent `participants.model` overrides this. |+| `CUMORA_DEFAULT_CLAUDE_MODEL` | unset | Deploy-level fallback (e.g. `claude-opus-4-7`). Explicit per-agent and reported custom-provider defaults override it. || `CUMORA_DEFAULT_CODEX_MODEL` | unset | Same shape for Codex; deliberately not set by default. || `CUMORA_DEFAULT_GROK_MODEL` | unset | Same shape for Grok Build. || `CUMORA_DEFAULT_CURSOR_MODEL` | unset | Same shape for Cursor Agent; blank lets Cursor use Auto. |diff --git a/docs/decisions/0005-secure-claude-provider-bootstrap.md b/docs/decisions/0005-secure-claude-provider-bootstrap.mdnew file mode 100644index 0000000..1c7798c--- /dev/null+++ b/docs/decisions/0005-secure-claude-provider-bootstrap.md@@ -0,0 +1,67 @@+# ADR 0005: Bootstrap custom Claude providers without widening Agent tools++- Status: Accepted+- Date: 2026-09-05++## Context++Secure Claude BYOA turns use Claude Code's `--restricted` mode. It correctly+ignores user/project settings so an Agent cannot acquire the operator's hooks,+MCP servers, permissions, or tool configuration. It also ignores the `env`+section of `~/.claude/settings.json`, where tools such as CC Switch commonly+store `ANTHROPIC_BASE_URL` and an authentication value.++That produced a split-brain result: `claude auth status` and an ordinary+terminal turn worked, while the same account under Cumora reported `Not logged+in`. If authentication was bypassed, an unpinned Agent could still receive the+server's Anthropic deployment model even though the custom endpoint owned a+different model namespace.++## Decision++- In secure mode, the daemon reads only a fixed allowlist from Claude's user+ settings: `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`,+ `ANTHROPIC_BASE_URL`, and `ANTHROPIC_SMALL_FAST_MODEL`.+- Those values enter only the trusted Claude core process environment. The+ inline restricted policy denies every imported name to model-spawned+ subprocesses. Cumora never serializes the values into argv, its logs, the+ Agent home, model-catalog reports, or its server.+- Explicit daemon environment values take precedence over the settings file.+ Missing, malformed, relative-config-root, or oversized settings fail soft and+ preserve Claude's native first-party OAuth/keychain behavior.+- Claude model discovery reports the configured defaults and whether a custom+ endpoint owns an unnamed default. For an Agent without an explicit model pin,+ that custom-provider default wins over a deployment-level vendor pin. The+ same applies to its fast model; if either default is unnamed, no model flag is+ injected. Explicit `participants.model` / `fast_model` values remain highest+ priority, and older daemons without this signal retain the deployment+ fallback.++## Consequences++- A custom Claude endpoint configured through the ordinary Claude settings file+ works without enabling `CUMORA_BYOA_ALLOW_UNSANDBOXED`.+- The operator's complete Claude settings remain outside the Agent boundary;+ executable configuration such as hooks, MCP servers, permissions, and+ arbitrary environment entries is still ignored.+- The daemon is now trusted to read four provider bootstrap values from a+ user-owned file. It already owns the Claude process and inherited equivalent+ values when exported by the operator; this changes their source, not the+ process trust boundary.+- A custom provider that needs additional environment variables remains+ unsupported in secure mode until each variable receives an explicit security+ review and is added to the allowlist.++## Alternatives considered++- **Enable unsandboxed compatibility mode:** rejected because authentication+ availability must not grant model-generated tools host file, credential, and+ network authority.+- **Pass the complete user settings file to restricted Claude:** rejected+ because it restores the hooks, permissions, MCP, and tool configuration that+ restricted mode intentionally excludes.+- **Embed provider values in `--settings` JSON:** rejected because secrets would+ become visible in the process command line and diagnostic captures.+- **Always remove deployment model pins:** rejected because first-party BYOA+ fleets use them to keep behavior stable across CLI upgrades. Only observed+ custom-provider ownership takes precedence.diff --git a/server/src/__tests__/agents-computer-engine-detect.test.ts b/server/src/__tests__/agents-computer-engine-detect.test.tsindex 86dfaad..3535cf1 100644--- a/server/src/__tests__/agents-computer-engine-detect.test.ts+++ b/server/src/__tests__/agents-computer-engine-detect.test.ts@@ -89,6 +89,48 @@ 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 () => {+ const catalog = {+ models: [{ id: 'provider/opus', label: 'Provider Opus' }],+ defaultModel: 'provider/opus',+ defaultFastModel: 'provider/haiku',+ prefersLocalDefault: true,+ supportsCustom: true,+ fastModelScope: 'agent',+ source: 'cli',+ }+ const localComputer = {+ availableEngines: ['claude'],+ detectedEngines: [{ id: 'claude', bin: 'claude', path: '/bin/claude', modelCatalog: catalog }],+ }+ installPoolMock(({ sql }) => {+ if (/FROM participants/.test(sql)) {+ return { rows: [+ { id: 'explicit', name: 'Explicit', role: null, systemPrompt: null, engine: 'claude', model: 'agent/pin', fastModel: null, ...localComputer },+ { id: 'local', name: 'Local', role: null, systemPrompt: null, engine: 'claude', model: null, fastModel: null, ...localComputer },+ {+ id: 'unnamed', name: 'Unnamed', role: null, systemPrompt: null, engine: 'claude', model: null, fastModel: null,+ availableEngines: ['claude'],+ detectedEngines: [{+ id: 'claude', bin: 'claude', path: '/bin/claude',+ modelCatalog: { ...catalog, models: [], defaultModel: null },+ }],+ },+ ] }+ }+ return { rows: [] }+ })++ const 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[2]?.model, null, 'custom provider with unnamed default must not inherit the deploy pin')+ assert.equal(agents[2]?.fastModel, 'provider/haiku')+ assert.equal('detectedEngines' in (agents[1] ?? {}), false)+})+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 71bc02b..a270cad 100644--- a/server/src/__tests__/agents-computer-engine.test.ts+++ b/server/src/__tests__/agents-computer-engine.test.ts@@ -172,13 +172,24 @@ test('Claude secure mode is fail-closed and strips tool credentials', { skip: ISconst root = await mkdtemp(join(tmpdir(), 'cumora-claude-secure-'))tempDirs.push(root)const binDir = join(root, 'bin')+ const configDir = join(root, 'claude-config')const home = join(root, 'home')await mkdir(binDir)+ await mkdir(configDir)await mkdir(home)+ await writeFile(join(configDir, 'settings.json'), JSON.stringify({+ model: 'provider/default-model',+ env: {+ ANTHROPIC_API_KEY: 'settings-api-key-must-lose',+ ANTHROPIC_AUTH_TOKEN: 'settings-auth-token',+ ANTHROPIC_BASE_URL: 'https://provider.example.test',+ UNRELATED_SECRET: 'must-not-be-imported',+ },+ }), 'utf8')await writeFakeCli(binDir,'claude',- "process.stderr.write(JSON.stringify({ argv: process.argv.slice(2), scrub: process.env.CLAUDE_CODE_SUBPROCESS_ENV_SCRUB }))\nprocess.exit(1)\n",+ "process.stderr.write(JSON.stringify({ argv: process.argv.slice(2), scrub: process.env.CLAUDE_CODE_SUBPROCESS_ENV_SCRUB, coreEnv: { apiKey: process.env.ANTHROPIC_API_KEY, authToken: process.env.ANTHROPIC_AUTH_TOKEN, baseUrl: process.env.ANTHROPIC_BASE_URL, unrelated: process.env.UNRELATED_SECRET } }))\nprocess.exit(1)\n",)useFakeCliPath(binDir)@@ -188,14 +199,25 @@ test('Claude secure mode is fail-closed and strips tool credentials', { skip: IShome,prompt: 'wake',env: secureClaudeEnv(root, {+ CLAUDE_CONFIG_DIR: configDir,+ ANTHROPIC_API_KEY: 'explicit-daemon-api-key',OPENAI_API_KEY: 'must-not-appear-in-settings',}),onLog: (line) => logs.push(line),signal: new AbortController().signal,})- const captured = JSON.parse(logs[0] ?? '{}') as { argv?: string[]; scrub?: string }+ const captured = JSON.parse(logs[0] ?? '{}') as {+ argv?: string[]+ scrub?: string+ coreEnv?: { apiKey?: string; authToken?: string; baseUrl?: string; unrelated?: string }+ }assert.equal(captured.scrub, '1')+ assert.deepEqual(captured.coreEnv, {+ apiKey: 'explicit-daemon-api-key',+ authToken: 'settings-auth-token',+ baseUrl: 'https://provider.example.test',+ })assert.ok(captured.argv?.includes('--restricted'))assert.ok(captured.argv?.includes('dontAsk'))assert.ok(captured.argv?.includes('Read,Write,Edit,Glob,Grep,mcp__cumora__cli'))@@ -229,7 +251,62 @@ test('Claude secure mode is fail-closed and strips tool credentials', { skip: ISassert.ok(settings.sandbox?.filesystem?.denyRead?.includes(process.platform === 'darwin' ? '/Users' : '/home'))assert.ok(settings.sandbox?.filesystem?.allowRead?.includes(home))assert.ok(settings.sandbox?.credentials?.envVars?.some((entry) => entry.name === 'OPENAI_API_KEY' && entry.mode === 'deny'))+ for (const name of ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL']) {+ assert.ok(settings.sandbox?.credentials?.envVars?.some((entry) => entry.name === name && entry.mode === 'deny'))+ }assert.doesNotMatch(settingsText, /must-not-appear-in-settings/)+ assert.doesNotMatch(settingsText, /settings-auth-token|explicit-daemon-api-key|provider\.example\.test/)+})++test('Claude secure triage stays inside the custom provider model namespace', { skip: IS_WIN }, async () => {+ const root = await mkdtemp(join(tmpdir(), 'cumora-claude-provider-model-'))+ tempDirs.push(root)+ const binDir = join(root, 'bin')+ const configDir = join(root, 'claude-config')+ const cwd = join(root, 'triage')+ await mkdir(binDir)+ await mkdir(configDir)+ await mkdir(cwd)+ await writeFakeCli(+ binDir,+ 'claude',+ "process.stdout.write(JSON.stringify({ result: JSON.stringify({ argv: process.argv.slice(2) }) }))\n",+ )+ useFakeCliPath(binDir)++ const settingsPath = join(configDir, 'settings.json')+ await writeFile(settingsPath, JSON.stringify({+ env: {+ ANTHROPIC_AUTH_TOKEN: 'fixture-token',+ ANTHROPIC_BASE_URL: 'https://provider.example.test',+ ANTHROPIC_SMALL_FAST_MODEL: 'provider/fast-model',+ },+ }), 'utf8')+ const env = secureClaudeEnv(root, {+ CLAUDE_CONFIG_DIR: configDir,+ CUMORA_TRIAGE_MODEL: undefined,+ ANTHROPIC_SMALL_FAST_MODEL: undefined,+ })+ const configured = await getAdapter('claude').classify({+ cwd, prompt: 'classify', env, signal: new AbortController().signal,+ })+ const configuredArgv = JSON.parse(configured.text) as { argv: string[] }+ const configuredModel = configuredArgv.argv.indexOf('--model')+ assert.ok(configuredModel >= 0)+ assert.equal(configuredArgv.argv[configuredModel + 1], 'provider/fast-model')++ await writeFile(settingsPath, JSON.stringify({+ env: {+ ANTHROPIC_AUTH_TOKEN: 'fixture-token',+ ANTHROPIC_BASE_URL: 'https://provider.example.test',+ },+ }), 'utf8')+ const unnamed = await getAdapter('claude').classify({+ cwd, prompt: 'classify', env, signal: new AbortController().signal,+ })+ const unnamedArgv = JSON.parse(unnamed.text) as { argv: string[] }+ assert.equal(unnamedArgv.argv.includes('--model'), false)+ assert.equal(unnamedArgv.argv.includes('haiku'), false)})test('persistent Claude startup failure keeps stderr for first send', async () => {diff --git a/server/src/__tests__/agents-computer-model-catalog.test.ts b/server/src/__tests__/agents-computer-model-catalog.test.tsindex 9ea6559..867e9cb 100644--- a/server/src/__tests__/agents-computer-model-catalog.test.ts+++ b/server/src/__tests__/agents-computer-model-catalog.test.ts@@ -5,7 +5,11 @@*/import { test } from 'node:test'import assert from 'node:assert/strict'-import { parseListedModels } from '../agents/computer/model-catalog.js'+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+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'test('OpenCode catalog keeps provider-qualified model ids and deduplicates them', () => {assert.deepEqual(@@ -32,3 +36,60 @@ test('Cursor catalog accepts bullets and ignores headings', () => {const out = parseListedModels('Available models\n* auto\n- claude-4.6-sonnet\n gpt-5.5\n', 'cursor')assert.deepEqual(out.map((model) => model.id), ['auto', 'claude-4.6-sonnet', 'gpt-5.5'])})++test('Claude custom-provider settings expose only core bootstrap values and model defaults', async () => {+ const root = await mkdtemp(join(tmpdir(), 'cumora-claude-catalog-'))+ const configDir = join(root, 'config')+ await mkdir(configDir)+ await writeFile(join(configDir, 'settings.json'), JSON.stringify({+ model: 'provider/opus-large',+ env: {+ ANTHROPIC_AUTH_TOKEN: 'settings-token',+ ANTHROPIC_BASE_URL: 'https://provider.example.test',+ ANTHROPIC_SMALL_FAST_MODEL: 'provider/haiku-small',+ UNRELATED_SECRET: 'do-not-import',+ },+ }), 'utf8')+ const env = { CLAUDE_CONFIG_DIR: configDir, ANTHROPIC_AUTH_TOKEN: 'explicit-token' }+ try {+ const settings = readClaudeUserSettings(env)+ assert.deepEqual(settings, {+ coreEnv: {+ ANTHROPIC_AUTH_TOKEN: 'settings-token',+ ANTHROPIC_BASE_URL: 'https://provider.example.test',+ ANTHROPIC_SMALL_FAST_MODEL: 'provider/haiku-small',+ },+ defaultModel: 'provider/opus-large',+ defaultFastModel: 'provider/haiku-small',+ prefersLocalDefault: true,+ })+ const merged = withClaudeUserSettingsEnv(env)+ assert.equal(merged.ANTHROPIC_AUTH_TOKEN, 'explicit-token')+ assert.equal(merged.ANTHROPIC_BASE_URL, 'https://provider.example.test')+ assert.equal(merged.UNRELATED_SECRET, undefined)++ clearModelCatalogCache()+ const catalog = await discoverEngineModelCatalog('claude', '/fixture/claude', true, env)+ assert.equal(catalog.defaultModel, 'provider/opus-large')+ assert.equal(catalog.defaultFastModel, 'provider/haiku-small')+ assert.equal(catalog.prefersLocalDefault, true)+ assert.equal(catalog.source, 'cli')+ assert.deepEqual(catalog.models.map((model) => model.id), [+ 'provider/opus-large',+ 'provider/haiku-small',+ ])+ assert.doesNotMatch(JSON.stringify(catalog), /settings-token|provider\.example\.test/)+ } finally {+ clearModelCatalogCache()+ await rm(root, { recursive: true, force: true })+ }+})++test('Claude settings ignore a relative config-root override instead of reading from cwd', () => {+ assert.deepEqual(readClaudeUserSettings({ CLAUDE_CONFIG_DIR: 'relative/config' }), {+ coreEnv: {},+ defaultModel: null,+ defaultFastModel: null,+ prefersLocalDefault: false,+ })+})diff --git a/server/src/agents/computer/claude-user-settings.ts b/server/src/agents/computer/claude-user-settings.tsnew file mode 100644index 0000000..0acfe0c--- /dev/null+++ b/server/src/agents/computer/claude-user-settings.ts@@ -0,0 +1,98 @@+/**+ * Claude Code's `--restricted` mode intentionally ignores user settings. That+ * is the right boundary for tools, hooks and MCP servers, but custom providers+ * commonly keep the small provider/bootstrap surface the Claude core needs in+ * ~/.claude/settings.json. Import only that narrow bootstrap surface into the+ * engine process environment; the adapter's restricted settings separately+ * deny every imported value to model-spawned subprocesses.+ */+import { readFileSync, statSync } from 'node:fs'+import { homedir } from 'node:os'+import { isAbsolute, join } from 'node:path'++const MAX_SETTINGS_BYTES = 1024 * 1024++/** Never broaden this to arbitrary settings.env entries. Values in this list+ * reach the trusted Claude core process, while everything else remains ignored+ * exactly as `--restricted` promises. */+export const CLAUDE_CORE_ENV_KEYS = [+ 'ANTHROPIC_API_KEY',+ 'ANTHROPIC_AUTH_TOKEN',+ 'ANTHROPIC_BASE_URL',+ 'ANTHROPIC_SMALL_FAST_MODEL',+] as const++type ClaudeCoreEnvKey = typeof CLAUDE_CORE_ENV_KEYS[number]++export interface ClaudeUserSettings {+ coreEnv: Partial<Record<ClaudeCoreEnvKey, string>>+ defaultModel: string | null+ defaultFastModel: string | null+ prefersLocalDefault: boolean+}++const EMPTY_SETTINGS: ClaudeUserSettings = {+ coreEnv: {},+ defaultModel: null,+ defaultFastModel: null,+ prefersLocalDefault: false,+}++function cleanString(value: unknown, max: number): string | null {+ if (typeof value !== 'string') return null+ const clean = value.replace(/[\u0000-\u001f\u007f]/g, '').trim()+ return clean ? clean.slice(0, max) : null+}++function settingsPath(env: NodeJS.ProcessEnv): string | null {+ const configured = cleanString(env.CLAUDE_CONFIG_DIR, 4096)+ // Never resolve a relative override against the daemon's changing cwd. An+ // explicit but ambiguous override is ignored as a whole rather than falling+ // back to a different settings file.+ if (configured && !isAbsolute(configured)) return null+ const dir = configured ?? join(homedir(), '.claude')+ return join(dir, 'settings.json')+}++/** Read only the non-executable provider bootstrap subset of Claude's user+ * settings. Malformed, oversized or absent settings fail soft so first-party+ * OAuth/keychain users retain Claude's native behaviour. */+export function readClaudeUserSettings(env: NodeJS.ProcessEnv = process.env): ClaudeUserSettings {+ try {+ const file = settingsPath(env)+ if (!file) return EMPTY_SETTINGS+ if (statSync(file).size > MAX_SETTINGS_BYTES) return EMPTY_SETTINGS+ const parsed = JSON.parse(readFileSync(file, 'utf8')) as unknown+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return EMPTY_SETTINGS+ 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)+ if (value) coreEnv[key] = value+ }+ return {+ coreEnv,+ defaultModel: cleanString(record.model, 160),+ defaultFastModel: cleanString(rawEnv.ANTHROPIC_SMALL_FAST_MODEL, 160),+ // 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: !!coreEnv.ANTHROPIC_BASE_URL,+ }+ } catch {+ return EMPTY_SETTINGS+ }+}++/** Explicit daemon environment always wins over the user settings file. */+export function withClaudeUserSettingsEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {+ const merged = { ...env }+ const { coreEnv } = readClaudeUserSettings(env)+ for (const key of CLAUDE_CORE_ENV_KEYS) {+ if (merged[key] === undefined && coreEnv[key] !== undefined) merged[key] = coreEnv[key]+ }+ return merged+}diff --git a/server/src/agents/computer/engine.ts b/server/src/agents/computer/engine.tsindex 42b3bf4..6e9d984 100644--- a/server/src/agents/computer/engine.ts+++ b/server/src/agents/computer/engine.ts@@ -30,6 +30,7 @@ import { homedir, tmpdir } from 'node:os'import { basename, dirname, join, delimiter as PATH_DELIMITER } from 'node:path'import { StringDecoder } from 'node:string_decoder'import { stripLoneSurrogates } from '../text-safety.js'+import { withClaudeUserSettingsEnv } from './claude-user-settings.js'import { isCliVersionAtLeast, probeEngineVersion, probeLocalEngineVersion } from './cli-version.js'import { discoverEngineModelCatalog, type EngineModelCatalog } from './model-catalog.js'@@ -1407,13 +1408,47 @@ function claudeSecureFlags(agentHome: string, env: NodeJS.ProcessEnv): string[]]}+/** Restricted Claude ignores ~/.claude/settings.json wholesale. Recover only+ * the provider bootstrap variables its trusted core needs; claudeSecureSettings+ * 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)+}++/** Pick the small brain inside the local provider namespace. An explicit+ * per-agent/computer pin wins; next use the provider's configured fast model.+ * If a custom endpoint names no fast model, omit --model and let that endpoint+ * choose instead of injecting Anthropic's `haiku` alias. */+function claudeFastModelArgs(env: NodeJS.ProcessEnv, requested?: string | null): string[] {+ const model = requested?.trim()+ || env.CUMORA_TRIAGE_MODEL?.trim()+ || env.ANTHROPIC_SMALL_FAST_MODEL?.trim()+ if (model) return ['--model', model]+ return env.ANTHROPIC_BASE_URL?.trim() ? [] : ['--model', 'haiku']+}++function claudeTurnEnv(env: NodeJS.ProcessEnv, fastModel?: string | null): NodeJS.ProcessEnv {+ const core = claudeCoreEnv(env)+ const turnEnv: NodeJS.ProcessEnv = {+ ...core,+ MAX_THINKING_TOKENS: core.MAX_THINKING_TOKENS ?? '0',+ CLAUDE_CODE_SUBPROCESS_ENV_SCRUB: allowUnsandboxedByoa(core)+ ? core.CLAUDE_CODE_SUBPROCESS_ENV_SCRUB+ : '1',+ }+ if (fastModel) turnEnv.ANTHROPIC_SMALL_FAST_MODEL = fastModel+ return turnEnv+}+class ClaudeAdapter implements EngineAdapter {readonly id = 'claude' as constreadonly bin = 'claude'async classify(args: EngineClassifyArgs): Promise<EngineClassifyResult> {- // Plain headless completion on Claude Code's own cheap fast model (Haiku) —- // exactly what Claude Code uses for its OWN quick judgments. NO tools, NO+ // Plain headless completion on Claude Code's cheap fast model (Haiku for a+ // first-party account, or the custom provider's configured/default model).+ // NO tools, NO// MCP (--strict-mcp-config, no --mcp-config = zero MCP init, the slowest// part of a cold `claude` spawn), NO session, thinking off, neutral cwd (no// persona CLAUDE.md). Just text in → JSON out, locally. Never the cloud.@@ -1421,7 +1456,8 @@ class ClaudeAdapter implements EngineAdapter {// token usage (incl. cache_read/cache_creation) → we unwrap `.result` as the// text and pass `.usage` up for the triage cost ledger.const flags = unsafeEngineArgs('CUMORA_TRIAGE_ARGS')- const model = ['--model', args.model || 'haiku']+ const env = claudeCoreEnv(args.env)+ const model = claudeFastModelArgs(env, args.model)const { command, shell, wantsStdinPrompt } = resolveSpawn(this.bin)const usingJson = flags.length === 0// On Windows the .cmd shim runs via the shell, which can't carry the big@@ -1430,13 +1466,13 @@ class ClaudeAdapter implements EngineAdapter {// before (unchanged).const base = flags.length? [...flags, '-p']- : allowUnsandboxedByoa()+ : allowUnsandboxedByoa(env)? ['-p', ...model, '--output-format', 'json', '--dangerously-skip-permissions', '--strict-mcp-config']: ['-p', ...model, '--output-format', 'json', '--restricted', '--tools', '', '--strict-mcp-config']const argv = wantsStdinPrompt ? base : (flags.length ? [...base, args.prompt] : ['-p', args.prompt, ...base.slice(1)])const res = await spawnCapture(command, argv, {cwd: args.cwd,- env: { ...args.env, MAX_THINKING_TOKENS: '0' },+ env: { ...env, MAX_THINKING_TOKENS: '0' },signal: args.signal,onLog: args.onLog,shell,@@ -1456,18 +1492,19 @@ class ClaudeAdapter implements EngineAdapter {probe(args: EngineProbeArgs): Promise<EngineClassifyResult> {// Mirror classify's clean one-shot spawn, but pick the tier's model: 'small'- // → haiku (the cerebellum); 'big' → omit --model so Claude uses its DEFAULT- // (the main reasoning brain). One token in, "OK" out — proves the binary runs+ // → the resolved provider-local cerebellum; 'big' → omit --model so Claude+ // 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 model = args.tier === 'small' ? ['--model', triageModel('haiku')] : []+ const env = claudeCoreEnv(args.env)+ const model = args.tier === 'small' ? claudeFastModelArgs(env) : []const { command, shell, wantsStdinPrompt } = resolveSpawn(this.bin)- const base = allowUnsandboxedByoa()+ const base = allowUnsandboxedByoa(env)? ['-p', ...model, '--output-format', 'text', '--dangerously-skip-permissions', '--strict-mcp-config']: ['-p', ...model, '--output-format', 'text', '--restricted', '--tools', '', '--strict-mcp-config']const argv = wantsStdinPrompt ? base : ['-p', DOCTOR_PROMPT, ...base.slice(1)]return spawnCapture(command, argv, {cwd: args.cwd,- env: { ...args.env, MAX_THINKING_TOKENS: '0' },+ env: { ...env, MAX_THINKING_TOKENS: '0' },signal: args.signal,shell,stdinText: wantsStdinPrompt ? DOCTOR_PROMPT : undefined,@@ -1491,8 +1528,9 @@ class ClaudeAdapter implements EngineAdapter {const promptFile = join(args.cwd, '.cumora-doctor-standing.md')try { await writeFile(promptFile, '', 'utf8') }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 base = allowUnsandboxedByoa()+ const base = allowUnsandboxedByoa(env)? ['-p', '--output-format', 'text', '--append-system-prompt-file', promptFile, '--dangerously-skip-permissions']: ['-p', '--output-format', 'text', '--append-system-prompt-file', promptFile,@@ -1501,7 +1539,7 @@ class ClaudeAdapter implements EngineAdapter {const argv = wantsStdinPrompt ? base : ['-p', DOCTOR_PROMPT, ...base.slice(1)]const r = await spawnCapture(command, argv, {cwd: args.cwd,- env: { ...args.env, MAX_THINKING_TOKENS: '0' },+ env: { ...env, MAX_THINKING_TOKENS: '0' },signal: args.signal,shell,stdinText: wantsStdinPrompt ? DOCTOR_PROMPT : undefined,@@ -1538,6 +1576,7 @@ class ClaudeAdapter implements EngineAdapter {// 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 env = claudeTurnEnv(args.env, args.fastModel)// Continuous context across wakes: resume the agent's prior session so it// remembers the running task (its place in a counting relay, what it already// said) instead of re-deriving from a frozen inbox snapshot each time.@@ -1547,23 +1586,15 @@ class ClaudeAdapter implements EngineAdapter {// unchanged (prompt in argv).const base = flags.length? [...flags, ...resume, '-p']- : allowUnsandboxedByoa()+ : allowUnsandboxedByoa(env)? ['-p', ...resume, ...model, '--output-format', 'stream-json', '--verbose', '--dangerously-skip-permissions']- : ['-p', ...resume, ...model, '--output-format', 'stream-json', '--verbose', ...claudeSecureFlags(args.home, args.env)]+ : ['-p', ...resume, ...model, '--output-format', 'stream-json', '--verbose', ...claudeSecureFlags(args.home, env)]const argv = wantsStdinPrompt ? base : (flags.length ? [...base, args.prompt] : ['-p', args.prompt, ...base.slice(1)])// BYOA turns are short reactive cycles (read inbox, maybe reply). Extended// thinking just adds latency + cost here, and in a group @all it makes the// slowest agent finish last and bow out on the "don't duplicate" rule. Disable// it by default (MAX_THINKING_TOKENS=0); a user can re-enable by exporting their// own MAX_THINKING_TOKENS before launching the daemon.- const env: NodeJS.ProcessEnv = {- ...args.env,- MAX_THINKING_TOKENS: args.env.MAX_THINKING_TOKENS ?? '0',- CLAUDE_CODE_SUBPROCESS_ENV_SCRUB: allowUnsandboxedByoa()- ? args.env.CLAUDE_CODE_SUBPROCESS_ENV_SCRUB- : '1',- }- if (args.fastModel) env.ANTHROPIC_SMALL_FAST_MODEL = args.fastModelreturn spawnEngine(command, argv, { ...args, env }, { shell, stdinText: wantsStdinPrompt ? args.prompt : undefined })}@@ -1572,6 +1603,7 @@ class ClaudeAdapter implements EngineAdapter {// persistent path — those flags are tuned for the one-shot run; fall back to run().if (unsafeEngineArgs('CUMORA_CLAUDE_ARGS').length) return nullconst model = args.model ? ['--model', args.model] : []+ const env = claudeTurnEnv(args.env, args.fastModel)// --resume only on the FIRST spawn / after a restart, to continue a prior// session; inside a live process the session continues on its own.const resume = args.resumeSessionId ? ['--resume', args.resumeSessionId] : []@@ -1585,23 +1617,15 @@ class ClaudeAdapter implements EngineAdapter {try { atomicAgentWriteSync(file, args.standingPrompt); sys = ['--append-system-prompt-file', file]; carriesStanding = true }catch { /* couldn't write → leave it; the daemon inlines the standing prompt instead */ }}- const argv = allowUnsandboxedByoa()+ const argv = allowUnsandboxedByoa(env)? ['-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose',...resume, ...sys, ...model, '--dangerously-skip-permissions',]: ['-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose',- ...resume, ...sys, ...model, ...claudeSecureFlags(args.home, args.env),+ ...resume, ...sys, ...model, ...claudeSecureFlags(args.home, env),]- const env: NodeJS.ProcessEnv = {- ...args.env,- MAX_THINKING_TOKENS: args.env.MAX_THINKING_TOKENS ?? '0',- CLAUDE_CODE_SUBPROCESS_ENV_SCRUB: allowUnsandboxedByoa()- ? args.env.CLAUDE_CODE_SUBPROCESS_ENV_SCRUB- : '1',- }- if (args.fastModel) env.ANTHROPIC_SMALL_FAST_MODEL = args.fastModelreturn new ClaudeSession(this.bin, argv, { ...args, env }, carriesStanding)}}diff --git a/server/src/agents/computer/model-catalog.ts b/server/src/agents/computer/model-catalog.tsindex 2cfc4ad..645409d 100644--- a/server/src/agents/computer/model-catalog.ts+++ b/server/src/agents/computer/model-catalog.ts@@ -1,5 +1,6 @@import { spawn } from 'node:child_process'import type { EngineId } from './engine.js'+import { readClaudeUserSettings, withClaudeUserSettingsEnv } from './claude-user-settings.js'import { versionCommandInvocation } from './cli-version.js'export type ModelCatalogSource = 'protocol' | 'cli' | 'presets'@@ -19,6 +20,9 @@ export interface EngineModelCatalog {models: EngineModelOption[]defaultModel: string | nulldefaultFastModel: string | null+ /** The local CLI/provider owns the default model namespace. An unpinned+ * Agent must not inherit a deployment-level vendor model in its place. */+ prefersLocalDefault?: booleansupportsCustom: booleanfastModelScope: FastModelScopesource: ModelCatalogSource@@ -310,7 +314,12 @@ function discoverCodex(command: string): Promise<{ models: EngineModelOption[];/** Discover the account/config-specific catalog without making a model call.* Failure is deliberately soft: a compact preset catalog plus custom entry is* still more useful than hiding the selector or blocking an engine rescan. */-export async function discoverEngineModelCatalog(id: EngineId, binPath: string | null, refresh = false): Promise<EngineModelCatalog> {+export async function discoverEngineModelCatalog(+ id: EngineId,+ binPath: string | null,+ refresh = false,+ env: NodeJS.ProcessEnv = process.env,+): Promise<EngineModelCatalog> {const preset = clonePreset(id)if (!binPath) return presetconst cacheKey = `${id}\u0000${binPath}`@@ -318,7 +327,28 @@ export async function discoverEngineModelCatalog(id: EngineId, binPath: string |if (!refresh && cached && Date.now() - cached.at < MODEL_CACHE_TTL_MS) return cached.cataloglet catalog: EngineModelCatalog | null = null- if (id === 'codex') {+ if (id === 'claude') {+ const settings = readClaudeUserSettings(env)+ const coreEnv = withClaudeUserSettingsEnv(env)+ const defaultFastModel = clean(coreEnv.ANTHROPIC_SMALL_FAST_MODEL, 160)+ const prefersLocalDefault = !!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,+ defaultFastModel: defaultFastModel ?? (prefersLocalDefault ? null : preset.defaultFastModel),+ prefersLocalDefault,+ source: 'cli',+ }+ }+ } else if (id === 'codex') {const result = await discoverCodex(binPath)if (result?.models.length) catalog = withPreset(id, result.models, 'protocol', result.defaultModel)} else if (id === 'cursor') {diff --git a/server/src/agents/computer/registry.ts b/server/src/agents/computer/registry.tsindex 90a408f..0f10195 100644--- a/server/src/agents/computer/registry.ts+++ b/server/src/agents/computer/registry.ts@@ -197,6 +197,7 @@ function sanitizeModelCatalog(raw: unknown): EngineModelCatalog | undefined {models,defaultModel: displayString(rec.defaultModel, 160),defaultFastModel: displayString(rec.defaultFastModel, 160),+ ...(rec.prefersLocalDefault === true ? { prefersLocalDefault: true } : {}),supportsCustom: rec.supportsCustom !== false,fastModelScope,source,@@ -612,23 +613,33 @@ export async function mintAgentRuntimeToken(args: {* Includes the per-agent big-brain (`model`) + small-brain (`fastModel`)* overrides so the daemon can pass them to the engine.*- * When a row has no explicit model, fall back to the deploy-level default+ * When a row has no explicit model, a reported custom-Claude provider default+ * takes precedence; otherwise fall back to the deploy-level default* (CUMORA_DEFAULT_CLAUDE_MODEL / CUMORA_DEFAULT_CODEX_MODEL /* CUMORA_DEFAULT_GROK_MODEL / CUMORA_DEFAULT_CURSOR_MODEL /* CUMORA_DEFAULT_OPENCODE_MODEL / CUMORA_DEFAULT_PI_MODEL /* CUMORA_DEFAULT_GEMINI_MODEL / CUMORA_DEFAULT_QWEN_MODEL /* CUMORA_DEFAULT_ANTIGRAVITY_MODEL) so every BYOA- * daemon gets a consistent pin — independent of whatever model the local- * engine CLI happens to default to today. Critical: a model+ * daemon without a custom provider gets a consistent pin. Critical: a model* upgrade in the underlying CLI (e.g. claude 4.7 → 4.8) silently changes- * agent behavior on every user's machine unless we pin here. */+ * agent behavior on every user's machine unless we pin here. A custom+ * provider can explicitly make its unnamed local default authoritative so a+ * vendor-specific deploy pin never crosses into the wrong namespace. */export async function listAgentsForComputer(computerId: string): Promise<Array<{ id: string; name: string; role: string | null; systemPrompt: string | null; engine: EngineId | null; model: string | null; fastModel: string | null }>> {- const { rows } = await pool.query<{ id: string; name: string; role: string | null; systemPrompt: string | null; engine: EngineId | null; model: string | null; fastModel: string | null }>(- `SELECT id, name, role, system_prompt AS "systemPrompt", engine, model, fast_model AS "fastModel" FROM participants- WHERE computer_id = $1 AND kind = 'agent' AND departed_at IS NULL- ORDER BY name ASC`,+ const { rows } = await pool.query<{+ id: string; name: string; role: string | null; systemPrompt: string | null+ engine: EngineId | null; model: string | null; fastModel: string | null+ availableEngines?: string[]; detectedEngines?: unknown+ }>(+ `SELECT p.id, p.name, p.role, p.system_prompt AS "systemPrompt", p.engine, p.model,+ p.fast_model AS "fastModel", c.available_engines AS "availableEngines",+ COALESCE(c.detected_engines, '[]'::jsonb) AS "detectedEngines"+ FROM participants p+ JOIN computers c ON c.id = p.computer_id+ WHERE p.computer_id = $1 AND p.kind = 'agent' AND p.departed_at IS NULL+ ORDER BY p.name ASC`,[computerId],)const claudeDefault = process.env.CUMORA_DEFAULT_CLAUDE_MODEL?.trim() || null@@ -641,7 +652,21 @@ export async function listAgentsForComputer(computerId: string): Promise<const qwenDefault = process.env.CUMORA_DEFAULT_QWEN_MODEL?.trim() || nullconst antigravityDefault = process.env.CUMORA_DEFAULT_ANTIGRAVITY_MODEL?.trim() || nullreturn rows.map((r) => {- if (r.model) return r+ const { availableEngines, detectedEngines, ...agent } = r+ const localCatalog = sanitizeDetectedEngines(detectedEngines, availableEngines ?? [])+ .find((entry) => entry.id === agent.engine)?.modelCatalog+ // 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) {+ return {+ ...agent,+ model: agent.model ?? localCatalog.defaultModel,+ fastModel: agent.fastModel ?? localCatalog.defaultFastModel,+ }+ }+ if (agent.model) return agentconst dflt = r.engine === 'codex'? codexDefault: r.engine === 'claude'@@ -661,7 +686,7 @@ export async function listAgentsForComputer(computerId: string): Promise<: r.engine === 'antigravity'? antigravityDefault: null- return dflt ? { ...r, model: dflt } : r+ return dflt ? { ...agent, model: dflt } : agent})}diff --git a/src/types.ts b/src/types.tsindex 66b5dc1..f58de88 100644--- a/src/types.ts+++ b/src/types.ts@@ -20,6 +20,7 @@ export interface EngineModelCatalog {models: EngineModelOption[]defaultModel: string | nulldefaultFastModel: string | null+ prefersLocalDefault?: booleansupportsCustom: booleanfastModelScope: 'agent' | 'computer' | 'unsupported'source: 'protocol' | 'cli' | 'presets'