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): add agent-scoped Claude provider profiles
lyly4788fc60c316
diff --git a/README.md b/README.mdindex 013a687..39dc4f3 100644--- a/README.md+++ b/README.md@@ -109,6 +109,7 @@ INTEGRATION_DATABASE_URL=postgres://$USER@localhost:5432/cumora_test \## Docs- [`docs/BYOA.md`](docs/BYOA.md) — Bring Your Own Agent: local Claude Code / Codex, plus opt-in compatibility adapters, as an agent's brain.+- [`docs/PROVIDER_PROFILES.md`](docs/PROVIDER_PROFILES.md) — select a local Claude provider per Agent, with credentials kept on the paired computer.- [`docs/COORDINATION.md`](docs/COORDINATION.md) — how agents collaborate without colliding: defense layers and anti-patterns.- [`docs/email.md`](docs/email.md) — per-agent real email (Resend out, Cloudflare Email Worker in).- [`docs/I18N.md`](docs/I18N.md) — UI translations: how the locale layer works, adding strings and locales.diff --git a/docs/PROVIDER_PROFILES.md b/docs/PROVIDER_PROFILES.mdnew file mode 100644index 0000000..5bc3201--- /dev/null+++ b/docs/PROVIDER_PROFILES.md@@ -0,0 +1,113 @@+# Agent-scoped Claude providers++A paired computer can give different Agents different Claude-compatible+endpoints and credentials. Profiles are configured by the computer's operator;+workspace owners/admins select a profile in the Agent editor. The first version+supports Claude in secure BYOA mode only.++## Configure the computer++Create `~/.cumora/providers.json` as the user running the daemon. Keep this file+outside Agent homes and source control. On macOS/Linux it must be owned by that+user with permissions `0600`; symlinks and group/world-readable files are rejected.++```sh+mkdir -p ~/.cumora+(umask 077; touch ~/.cumora/providers.json)+chmod 600 ~/.cumora/providers.json+```++Edit the file with an editor on that computer. This example uses placeholder+credentials and model ids; replace them with values supported by your gateway:++```json+{+ "version": 1,+ "profiles": [+ {+ "id": "work",+ "label": "Work gateway",+ "baseUrl": "https://gateway.example.com",+ "model": "gateway/main-model",+ "fastModel": "gateway/fast-model",+ "auth": { "apiKey": "replace-with-local-credential" }+ },+ {+ "id": "personal",+ "label": "Personal gateway",+ "baseUrl": "https://personal.example.com",+ "model": "personal/main-model",+ "fastModel": "personal/fast-model",+ "auth": { "authToken": "replace-with-local-credential" }+ }+ ]+}+```++Each profile requires an id, label, endpoint, main model, fast model and exactly+one credential: `apiKey` maps to `ANTHROPIC_API_KEY`, or `authToken` maps to+`ANTHROPIC_AUTH_TOKEN`. URLs require HTTPS, except HTTP on loopback for local+gateways. URL credentials, query strings and fragments are rejected. Profile ids+are 1–64 letters, digits, underscores or hyphens, starting with a letter/digit.+The file allows at most 50 profiles and 1 MiB.++Test a single profile with:++```sh+npx cumora@latest agent computer --doctor --provider work+```++This runs Claude's main, small and wake-path probes using that profile. It makes+real model requests. It does not probe other engines or the computer's default+account. The daemon must be upgraded to a build containing provider support;+older releases do not understand these options.++The daemon advertises profile ids, labels and model defaults on its next engine+scan. Use the computer's engine refresh control to request an immediate scan.+In the Agent editor, select the paired computer, Claude, then the provider.+Credentials and endpoint URLs stay local; the participant row stores only the+profile id. Profiles are scoped to a computer, so moving an Agent requires a+fresh selection.++## Runtime behavior++- Each runner receives its own environment snapshot. Main turns, persistent+ sessions and small-brain triage all use the selected profile. The process-wide+ environment is never modified.+- Explicit Agent model pins override the profile's model defaults. Computer and+ deployment model defaults apply only when no profile is selected. Model pins+ are cleared in the editor when switching providers, engines or computers.+- Profile environments clear inherited Claude provider credentials, OAuth+ tokens, provider-selection flags and model aliases. Secure mode still denies+ credentials to model-spawned tools. Unsandboxed compatibility mode cannot run+ or advertise profiles.+- A profile is reread on Agent synchronization. Changed runtime configuration+ stops the previous runner and waits for its engine to terminate before starting+ the replacement. An in-progress turn can be interrupted; it is not retried as+ part of the configuration switch.+- Native session pointers are separated by a local digest of the profile id,+ endpoint, credentials and model defaults. Changing these values starts a new+ native session; returning to an unchanged profile may resume that profile's+ earlier session. Agent files, memory and Cumora conversation history persist+ and can still be included in future prompts.+- If the file becomes invalid, unreadable or disappears, a bound Agent stops on+ the next successful synchronization. A missing profile or unavailable Claude+ never falls back to another provider or engine. Other Agents using the+ computer default continue normally. Diagnostics appear in the daemon log.++## Deployment and compatibility++Apply migration `0008_agent_provider_profile` before starting this server build.+Existing participants have a null profile and retain their current behavior.+The migration also rotates runtime assignment tokens when the profile changes.++New daemons request profile-aware discovery and include their selected profile+when requesting runtime tokens. Older daemons cannot discover profile-bound+Agents or mint replacement tokens for them. Switching profiles invalidates the+old runner's authorization. This does not undo tool actions already completed+before the switch, or erase a request already sent to a provider.++The first version does not synchronize credentials through Cumora, manage them+in the browser, probe gateway model catalogs, or implement provider failover.+It uses Claude Code's existing secure execution requirements and supports+gateways compatible with the Claude Code request protocol.diff --git a/server/src/__integration__/agent-provider-profiles.test.ts b/server/src/__integration__/agent-provider-profiles.test.tsnew file mode 100644index 0000000..baa0f4f--- /dev/null+++ b/server/src/__integration__/agent-provider-profiles.test.ts@@ -0,0 +1,93 @@+import assert from 'node:assert/strict'+import { after, before, beforeEach, test } from 'node:test'+import { pool } from '../db/pool.js'+import { createAgentRecord } from '../agents/create.js'+import { assignAgentToComputer, listAgentsForComputer, mintAgentRuntimeToken, resolveComputerAssignment, sanitizeDetectedEngines } from '../agents/computer/registry.js'+import { isRuntimeAgentAuthorized } from '../agents/runtime/authorization.js'+import { verifyAgentToken } from '../agents/runtime/jwt.js'+import { ensureSchemaOnce, resetAllTables, seedCompanyWithAgent, teardownAll } from './_helpers.js'++const companyId = 'co-provider-test'+const computerId = 'comp-provider-test'+const agentId = 'agent-provider-test'+const metadata = { id: 'work', label: 'Work', model: 'work/big', fastModel: 'work/small' }+const placement = { companyId, computerId, engine: 'claude', inherit: false }++before(async () => { await ensureSchemaOnce() })+beforeEach(async () => {+ await resetAllTables()+ await seedCompanyWithAgent({ companyId, agentId })+ const detected = sanitizeDetectedEngines([{+ id: 'claude', bin: 'claude', path: '/usr/bin/claude', providerProfiles: [+ { ...metadata, baseUrl: 'https://private.example.test', auth: { apiKey: 'must-not-persist' } },+ { ...metadata, id: 'personal' },+ ],+ }], ['claude', 'codex'])+ await pool.query(+ `INSERT INTO computers (id, company_id, name, kind, available_engines, detected_engines)+ VALUES ($1, $2, 'Fixture', 'local', $3::jsonb, $4::jsonb)`,+ [computerId, companyId, JSON.stringify(['claude', 'codex']), JSON.stringify(detected)],+ )+ await assignAgentToComputer({ ...placement, agentId })+})+after(async () => { await teardownAll() })++test('[integration] provider assignment requires explicit Claude and a profile on this computer', async () => {+ assert.ok(await resolveComputerAssignment({ ...placement, providerProfile: 'work' }))+ for (const invalid of [+ { providerProfile: 'unknown' }, { providerProfile: '../work' },+ { providerProfile: 'work', engine: 'codex' }, { providerProfile: 'work', inherit: true },+ { providerProfile: 'work', companyId: 'foreign-company' },+ ]) {+ assert.equal(await assignAgentToComputer({ ...placement, agentId, ...invalid }), null)+ }+ const { rows } = await pool.query('SELECT provider_profile FROM participants WHERE id = $1', [agentId])+ assert.equal(rows[0].provider_profile, null)+ const computers = await pool.query('SELECT detected_engines FROM computers WHERE id = $1', [computerId])+ assert.doesNotMatch(JSON.stringify(computers.rows), /must-not-persist|private\.example|baseUrl|apiKey/)+})++test('[integration] old daemons cannot discover or mint tokens for a bound profile; pins stay local', async () => {+ const oldDefault = process.env.CUMORA_DEFAULT_CLAUDE_MODEL+ process.env.CUMORA_DEFAULT_CLAUDE_MODEL = 'deployment/anthropic-model'+ try {+ const old = await mintAgentRuntimeToken({ computerId, agentId })+ assert.ok(old)+ assert.equal(await isRuntimeAgentAuthorized(verifyAgentToken(old.token)), true)+ assert.ok(await assignAgentToComputer({ ...placement, agentId, providerProfile: 'work', model: null, fastModel: null }))+ assert.equal(await isRuntimeAgentAuthorized(verifyAgentToken(old.token)), false)+ assert.equal(await mintAgentRuntimeToken({ computerId, agentId }), null)+ assert.equal(await mintAgentRuntimeToken({ computerId, agentId, providerProfile: 'personal' }), null)+ assert.deepEqual(await listAgentsForComputer(computerId), [])+ const listed = await listAgentsForComputer(computerId, true)+ assert.equal(listed[0].providerProfile, 'work')+ assert.equal(listed[0].model, null)+ assert.equal(listed[0].fastModel, null)+ const work = await mintAgentRuntimeToken({ computerId, agentId, providerProfile: 'work' })+ assert.ok(work)+ assert.equal(await isRuntimeAgentAuthorized(verifyAgentToken(work.token)), true)+ assert.ok(await assignAgentToComputer({ ...placement, agentId, providerProfile: 'personal' }))+ assert.equal(await isRuntimeAgentAuthorized(verifyAgentToken(work.token)), false)+ // Clearing a profile restores the legacy discovery/token behavior.+ await assignAgentToComputer({ ...placement, agentId, providerProfile: null })+ assert.equal((await listAgentsForComputer(computerId))[0].model, 'deployment/anthropic-model')+ assert.ok(await mintAgentRuntimeToken({ computerId, agentId }))+ } finally {+ if (oldDefault === undefined) delete process.env.CUMORA_DEFAULT_CLAUDE_MODEL+ else process.env.CUMORA_DEFAULT_CLAUDE_MODEL = oldDefault+ }+})++test('[integration] Agent creation persists the profile atomically and includes it in retry identity', async () => {+ const input = {+ ...placement, name: 'Provider Agent', tier: 'pro' as const, maxActiveAgents: 20,+ systemPrompt: 'Test fixture', providerProfile: 'work', requestId: 'profile-create-fixture',+ }+ const created = await createAgentRecord(input)+ assert.equal((await createAgentRecord(input)).id, created.id)+ assert.equal((await listAgentsForComputer(computerId, true)).find((a) => a.id === created.id)?.providerProfile, 'work')+ await assert.rejects(createAgentRecord({ ...input, providerProfile: 'personal' }), /different agent data/)+ await assert.rejects(createAgentRecord({ ...input, requestId: 'profile-invalid-fixture', providerProfile: 'missing' }), /invalid computer or engine/)+ const { rows } = await pool.query('SELECT count(*)::int AS n FROM participants WHERE creation_request_id = $1', ['profile-invalid-fixture'])+ assert.equal(rows[0].n, 0)+})diff --git a/server/src/__tests__/agents-computer-engine-detect.test.ts b/server/src/__tests__/agents-computer-engine-detect.test.tsindex 3535cf1..156b628 100644--- a/server/src/__tests__/agents-computer-engine-detect.test.ts+++ b/server/src/__tests__/agents-computer-engine-detect.test.ts@@ -245,6 +245,6 @@ test('assignAgentToComputer persists model pins in the host assignment update',assert.match(update?.sql ?? '', /model = \$4/)assert.match(update?.sql ?? '', /fast_model = \$5/)assert.deepEqual(update?.params, [- 'comp-1', 'codex', false, 'gpt-5.6-sol', null, 'bram', 'co-1',+ 'comp-1', 'codex', false, 'gpt-5.6-sol', null, null, 'bram', 'co-1',])})diff --git a/server/src/__tests__/agents-computer-engine.test.ts b/server/src/__tests__/agents-computer-engine.test.tsindex f6c39ea..c2f566d 100644--- a/server/src/__tests__/agents-computer-engine.test.ts+++ b/server/src/__tests__/agents-computer-engine.test.ts@@ -10,6 +10,7 @@ import { delimiter, dirname, join } from 'node:path'import { afterEach, test } from 'node:test'import { setTimeout as delay } from 'node:timers/promises'import { type EngineHopReport, type EngineRunResult, getAdapter, headlessSpawnOptions, resolveSpawn, runnableEngineIds, secureEngineCapabilityReason } from '../agents/computer/engine.js'+import { type ProviderProfile, providerProfileEnv } from '../agents/computer/provider-profiles.js'import { CLAUDE_CORE_ENV_KEYS, CLAUDE_TURN_ENV_KEYS } from '../agents/computer/claude-user-settings.js'const IS_WIN = process.platform === 'win32'@@ -1132,3 +1133,83 @@ test('a Grok ACP turn still settles when no model is announced', { skip: IS_WINassert.equal(result.model, null, 'with nothing announced and nothing pinned there is no model to report')assert.equal(hops[0].model, 'grok', 'the hop keeps its last-resort label')})+++test('concurrent Claude profiles isolate one-shot, persistent, triage and doctor processes', { skip: IS_WIN }, async () => {+ delete process.env.CUMORA_BYOA_ALLOW_UNSANDBOXED+ const root = await mkdtemp(join(tmpdir(), 'cumora-profile-isolation-'))+ tempDirs.push(root)+ const binDir = join(root, 'bin')+ const configDir = join(root, 'host-config')+ await Promise.all([mkdir(binDir), mkdir(configDir)])+ await writeFile(join(configDir, 'settings.json'), JSON.stringify({ env: {+ ANTHROPIC_API_KEY: 'host-key-must-not-leak', ANTHROPIC_AUTH_TOKEN: 'host-token-must-not-leak',+ ANTHROPIC_BASE_URL: 'https://host.example.test', ANTHROPIC_DEFAULT_OPUS_MODEL: 'host/opus',+ } }))+ await writeFakeCli(binDir, 'claude', `+const argv = process.argv.slice(2)+const capture = () => JSON.stringify({ argv, env: Object.fromEntries(+ ${JSON.stringify([...CLAUDE_CORE_ENV_KEYS, 'ANTHROPIC_MODEL', 'CLAUDE_CODE_OAUTH_TOKEN'])}.map(k => [k, process.env[k]])+) })+if (argv.includes('--input-format')) {+ require('node:readline').createInterface({ input: process.stdin }).on('line', () => {+ process.stderr.write(capture() + '\\n')+ process.stdout.write(JSON.stringify({type:'result', subtype:'success', result:'OK', session_id:'fixture'}) + '\\n')+ })+} else if (argv[argv.indexOf('--output-format') + 1] === 'json') {+ process.stdout.write(JSON.stringify({result: capture()}))+} else {+ process.stderr.write(capture() + '\\n')+ process.stdout.write((argv[argv.indexOf('--output-format') + 1] === 'text'+ ? capture() : JSON.stringify({type:'result', subtype:'success', result:'OK'})) + '\\n')+}+`)+ useFakeCliPath(binDir)+ const adapter = getAdapter('claude')+ const profiles: ProviderProfile[] = ['alpha', 'beta'].map((id, index) => ({+ id, label: id, baseUrl: `https://${id}.example.test`, model: `${id}/big`, fastModel: `${id}/small`,+ auth: index === 0 ? { apiKey: 'alpha-secret' } : { authToken: 'beta-secret' },+ }))+ await Promise.all(profiles.map(async (profile) => {+ const home = join(root, profile.id)+ await mkdir(home)+ const env = providerProfileEnv(secureClaudeEnv(root, {+ CLAUDE_CONFIG_DIR: configDir, CUMORA_ENGINE_MODEL: 'host-big', CUMORA_TRIAGE_MODEL: 'host-fast',+ CLAUDE_CODE_OAUTH_TOKEN: 'host-oauth',+ }), profile)+ const captures: string[] = []+ const args = { home, env, model: profile.model, fastModel: profile.fastModel, onLog: (line: string) => captures.push(line) }+ await adapter.run({ ...args, prompt: 'wake', signal: new AbortController().signal })+ const session = adapter.startSession?.(args)+ assert.ok(session)+ liveSessions.push(session)+ assert.equal((await session.send('wake')).exitCode, 0)+ await session.stop()+ const triage = await adapter.classify({ cwd: home, env, prompt: 'triage', signal: new AbortController().signal })+ captures.push(triage.text)+ for (const tier of ['big', 'small'] as const) {+ const probe = await adapter.probe({ cwd: home, env, tier, signal: new AbortController().signal })+ captures.push(probe.text.trim())+ }+ const capturedProcesses = captures.filter((line) => line.startsWith('{"argv":'))+ assert.equal(capturedProcesses.length, 5)+ for (const text of capturedProcesses) {+ const captured = JSON.parse(text) as { argv: string[]; env: Record<string, string> }+ assert.equal(captured.env.ANTHROPIC_BASE_URL, profile.baseUrl)+ assert.equal(captured.env.ANTHROPIC_MODEL, profile.model)+ assert.equal(captured.env.ANTHROPIC_API_KEY, 'apiKey' in profile.auth ? profile.auth.apiKey : '')+ assert.equal(captured.env.ANTHROPIC_AUTH_TOKEN, 'authToken' in profile.auth ? profile.auth.authToken : '')+ assert.equal(captured.env.CLAUDE_CODE_OAUTH_TOKEN, '')+ assert.ok(captured.argv.includes('--restricted'))+ assert.doesNotMatch(text, /host-key-must-not-leak|host-token-must-not-leak|host\/opus|host-big|host-fast/)+ if (captured.argv.includes('--settings')) {+ const settings = JSON.parse(captured.argv[captured.argv.indexOf('--settings') + 1])+ for (const name of ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN']) {+ assert.ok(settings.sandbox.credentials.envVars.some((entry: { name: string; mode: string }) => entry.name === name && entry.mode === 'deny'))+ }+ }+ }+ const triageArgv = JSON.parse(triage.text).argv as string[]+ assert.equal(triageArgv[triageArgv.indexOf('--model') + 1], profile.fastModel)+ }))+})diff --git a/server/src/__tests__/agents-computer-provider-profiles.test.ts b/server/src/__tests__/agents-computer-provider-profiles.test.tsnew file mode 100644index 0000000..39ccbe5--- /dev/null+++ b/server/src/__tests__/agents-computer-provider-profiles.test.ts@@ -0,0 +1,138 @@+import assert from 'node:assert/strict'+import { chmodSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { basename, dirname, join } from 'node:path'+import { test } from 'node:test'+import { AgentRunner } from '../agents/computer/daemon.js'+import { withClaudeUserSettingsEnv } from '../agents/computer/claude-user-settings.js'+import {+ type ProviderProfile, parseProviderProfiles, providerProfileEnv, providerProfileFingerprint,+ providerProfileMetadata, readProviderProfiles, redactProviderSecret, sanitizeProviderProfiles,+} from '../agents/computer/provider-profiles.js'++const profile: ProviderProfile = {+ id: 'work', label: 'Work', baseUrl: 'https://work.example.test',+ model: 'work/reasoning', fastModel: 'work/fast', auth: { apiKey: 'fixture-work-secret' },+}+const config = (profiles: unknown[] = [profile]) => ({ version: 1, profiles })++test('profile parsing rejects ambiguous auth, duplicate ids and unsafe URLs without logging secrets', () => {+ assert.deepEqual(parseProviderProfiles(config()), [profile])+ for (const invalid of [+ { ...profile, id: '../work' },+ { ...profile, auth: {} },+ { ...profile, auth: { apiKey: 'secret', authToken: 'secret' } },+ { ...profile, baseUrl: 'http://remote.example.test' },+ { ...profile, baseUrl: 'https://user:[email protected]' },+ { ...profile, baseUrl: 'https://work.example.test?key=secret' },+ { ...profile, fastModel: '' },+ ]) {+ assert.throws(() => parseProviderProfiles(config([invalid])), (err: unknown) => {+ assert.ok(err instanceof Error)+ assert.doesNotMatch(err.message, /fixture-work-secret|user:secret|key=secret/)+ return true+ })+ }+ assert.throws(() => parseProviderProfiles(config([profile, profile])))+ assert.throws(() => parseProviderProfiles({ version: 2, profiles: [] }))+ assert.equal(parseProviderProfiles(config([{ ...profile, baseUrl: 'http://127.0.0.1:8080/' }]))[0].baseUrl, 'http://127.0.0.1:8080')+})++test('local file loading checks permissions, rejects symlinks and fails closed on corruption', () => {+ const root = mkdtempSync(join(tmpdir(), 'cumora-profiles-'))+ const file = join(root, 'providers.json')+ try {+ assert.deepEqual(readProviderProfiles(file), [])+ writeFileSync(file, JSON.stringify(config()), { mode: 0o600 })+ assert.deepEqual(readProviderProfiles(file), [profile])+ if (process.platform !== 'win32') {+ chmodSync(file, 0o644)+ assert.throws(() => readProviderProfiles(file), /0600/)+ chmodSync(file, 0o600)+ symlinkSync(file, join(root, 'linked.json'))+ assert.throws(() => readProviderProfiles(join(root, 'linked.json')), /regular local file/)+ }+ writeFileSync(file, '{"secret": "fixture-work-secret",')+ assert.throws(() => readProviderProfiles(file), /not valid JSON/)+ } finally { rmSync(root, { recursive: true, force: true }) }+})++test('discovery metadata is an explicit public projection', () => {+ const metadata = providerProfileMetadata(profile)+ assert.deepEqual(Object.keys(metadata).sort(), ['fastModel', 'id', 'label', 'model'])+ assert.deepEqual(sanitizeProviderProfiles([profile]), [metadata])+ assert.doesNotMatch(JSON.stringify(metadata), /fixture-work-secret|baseUrl|auth/)+})++test('profile environments cannot borrow host credentials, aliases or global model overrides', () => {+ const ambient = {+ ANTHROPIC_API_KEY: 'host-api-key', ANTHROPIC_AUTH_TOKEN: 'host-token',+ ANTHROPIC_DEFAULT_OPUS_MODEL: 'host-opus', CLAUDE_CODE_USE_BEDROCK: '1',+ CLAUDE_CODE_USE_VERTEX: '1', CLAUDE_CODE_OAUTH_TOKEN: 'host-oauth',+ CUMORA_TRIAGE_MODEL: 'host-fast', CUMORA_ENGINE_MODEL: 'host-big',+ CLAUDE_CONFIG_DIR: '/nonexistent-cumora-fixture',+ }+ const env = providerProfileEnv(ambient, profile)+ const other = providerProfileEnv(ambient, { ...profile, auth: { authToken: 'other-token' } })+ assert.equal(env.ANTHROPIC_API_KEY, 'fixture-work-secret')+ assert.equal(env.ANTHROPIC_AUTH_TOKEN, '')+ assert.equal(other.ANTHROPIC_API_KEY, '')+ assert.equal(other.ANTHROPIC_AUTH_TOKEN, 'other-token')+ assert.equal(ambient.ANTHROPIC_API_KEY, 'host-api-key')+ for (const key of ['CLAUDE_CODE_OAUTH_TOKEN', 'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX', 'ANTHROPIC_DEFAULT_OPUS_MODEL', 'CUMORA_TRIAGE_MODEL']) {+ assert.equal(env[key as keyof typeof env], '')+ }+ assert.deepEqual(withClaudeUserSettingsEnv(env), env)+ assert.throws(() => providerProfileEnv({ CUMORA_BYOA_ALLOW_UNSANDBOXED: '1' }, profile), /secure BYOA/)+})++test('provider runtime identity separates sessions and restarts only when runtime configuration changes', () => {+ const agent = { id: 'profile-fixture', name: 'Fixture', role: null, systemPrompt: null, engine: 'claude' as const, model: null, fastModel: null, providerProfile: profile.id }+ const cfg = { serverUrl: 'https://server.example.test', computerId: 'fixture', deviceToken: 'fixture' }+ const first = new AgentRunner(cfg, agent, 'claude', profile)+ assert.equal(first.configMatches(agent, 'claude', { ...profile, label: 'Renamed' }), true)+ assert.equal(first.configMatches(agent, 'claude'), false)+ const changed = { ...profile, auth: { apiKey: 'rotated-key' } }+ assert.equal(first.configMatches(agent, 'claude', changed), false)+ assert.notEqual(providerProfileFingerprint(profile), providerProfileFingerprint({ ...profile, baseUrl: 'https://other.example.test' }))+ type RunnerInternals = { sessionStore: { sessionFile: string }; engineModel(): string | null; engineFastModel(): string | null; triageModelPin(): string | undefined; visibleEngineError(code: number, detail: string): string }+ const a = first as unknown as RunnerInternals+ const b = new AgentRunner(cfg, agent, 'claude', changed) as unknown as RunnerInternals+ const legacy = new AgentRunner(cfg, { ...agent, providerProfile: null }, 'claude') as unknown as RunnerInternals+ // The profile fingerprint is a third session dimension next to agent and+ // engine: same engine-scoped directory, distinct pointer per profile.+ assert.notEqual(a.sessionStore.sessionFile, b.sessionStore.sessionFile)+ assert.notEqual(a.sessionStore.sessionFile, legacy.sessionStore.sessionFile)+ assert.equal(dirname(a.sessionStore.sessionFile), dirname(legacy.sessionStore.sessionFile))+ assert.equal(basename(dirname(legacy.sessionStore.sessionFile)), 'profile-fixture')+ assert.equal(basename(legacy.sessionStore.sessionFile), 'claude.session')+ assert.equal(basename(a.sessionStore.sessionFile), `claude.${providerProfileFingerprint(profile)}.session`)+ assert.equal(a.engineModel(), profile.model)+ assert.equal(a.engineFastModel(), profile.fastModel)+ assert.equal(a.triageModelPin(), profile.fastModel)+ assert.doesNotMatch(a.visibleEngineError(1, 'auth failed: fixture-work-secret'), /fixture-work-secret/)+ assert.equal(redactProviderSecret('fixture-work-secret / fixture-work-secret', profile), '[redacted] / [redacted]')+})+++test('runner replacement waits for in-flight triage and cannot respawn a stopped persistent session', async () => {+ const runner = new AgentRunner(+ { serverUrl: 'https://server.example.test', computerId: 'fixture', deviceToken: 'fixture' },+ { id: 'fixture', name: 'Fixture', role: null, systemPrompt: null, engine: 'claude', model: null, fastModel: null },+ 'claude', profile,+ )+ let finish!: () => void+ const internals = runner as unknown as {+ activeTriage: Promise<unknown> | null; teardown: AbortController; ensureEngineSession(): unknown+ }+ internals.activeTriage = new Promise<void>((resolve) => { finish = resolve })+ let stopped = false+ const stopping = runner.stop({ forceEngine: true }).then(() => { stopped = true })+ await Promise.resolve()+ assert.equal(internals.teardown.signal.aborted, true)+ assert.equal(stopped, false, 'the replacement must not start while old triage is alive')+ assert.equal(internals.ensureEngineSession(), null)+ finish()+ await stopping+ assert.equal(stopped, true)+})diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.tsindex 5bcb32f..54c3fe4 100644--- a/server/src/agents/computer/daemon.ts+++ b/server/src/agents/computer/daemon.ts@@ -38,6 +38,7 @@ import {uniqueProjectIds,} from '../memory-scope.js'import { parseSseStream, wakeStreamWasStable } from '../runtime/sse-parse.js'+import { type ProviderProfile, providerProfileEnv, providerProfileFingerprint, providerProfileMetadata, readProviderProfiles, redactProviderSecret } from './provider-profiles.js'import { parseComputerControlEvent } from './control-event.js'import {mergeWakeBackgroundBriefs,@@ -424,6 +425,7 @@ interface DaemonConfig {}interface AgentInfo {+ providerProfile?: string | nullid: stringname: stringrole: string | null@@ -558,7 +560,7 @@ interface RuntimeTriagePayload {// ─── arg parsing ────────────────────────────────────────────────────────function parseArgs(argv: string[]): {- pair?: string; server?: string; engine?: string+ pair?: string; server?: string; engine?: string; provider?: stringinstallService?: boolean; uninstallService?: boolean; restart?: boolean; stop?: booleanstatus?: boolean; logs?: boolean; version?: boolean; doctor?: boolean; help?: boolean} {@@ -567,6 +569,8 @@ function parseArgs(argv: string[]): {if (argv[i] === '--help' || argv[i] === '-h' || argv[i] === 'help') out.help = trueelse if (argv[i] === '--pair') out.pair = argv[++i]else if (argv[i].startsWith('--pair=')) out.pair = argv[i].slice('--pair='.length)+ else if (argv[i] === '--provider') out.provider = argv[++i] || ''+ else if (argv[i].startsWith('--provider=')) out.provider = argv[i].slice('--provider='.length)else if (argv[i] === '--server') out.server = argv[++i]else if (argv[i].startsWith('--server=')) out.server = argv[i].slice('--server='.length)else if (argv[i] === '--engine') out.engine = argv[++i]@@ -868,6 +872,7 @@ function helpText(): string {'','Diagnostics:',' --doctor check engines, PATH, login/quota',+ ' --provider <id> with --doctor: check one local Claude provider profile',' --version, -v print the daemon version',' --help, -h show this help','',@@ -1620,7 +1625,7 @@ export function resolveTriageModel(return resolveEngineFastModel(configured, engineOverride)?.trim() || computerDefault?.trim() || undefined}-class AgentRunner {+export class AgentRunner {/** Aborted once in stop(). Handed to every one-shot `adapter.run(...)` so the* engine child dies with its runner, the way the persistent session already* does. Without it those children were orphaned: they keep the `cumora` IPC@@ -1685,6 +1690,7 @@ class AgentRunner {* Runner replacement aborts/stops it and awaits this barrier before the next* runner rewrites persona or standing-prompt files. */private activeEngineRun: Promise<EngineRunResult> | null = null+ private activeTriage: Promise<unknown> | null = null/** When the last engine turn (chat OR agenda) finished — the "quiet" anchor for* agenda wakes, and the throttle for how often we check the board. */private lastTurnEndedAt = 0@@ -1716,6 +1722,7 @@ class AgentRunner {private readonly cfg: DaemonConfig,private readonly agent: AgentInfo,engine: EngineId,+ private readonly provider?: ProviderProfile,) {this.engine = enginethis.home = join(AGENTS_ROOT, agent.id)@@ -1727,7 +1734,10 @@ class AgentRunner {// granted only the two leaf request/response directories; Claude reaches// them through the fixed MCP bridge, not a model-controlled shell.this.ipcDir = join(CONFIG_DIR, '.runtime-cli-ipc', this.agent.id)- this.sessionStore = new EngineSessionStore(SESSIONS_DIR, agent.id, engine)+ // The profile is a third dimension of session identity alongside agent and+ // engine: a different endpoint/account owns a different transcript, so its+ // session id must never be offered to another profile's provider.+ this.sessionStore = new EngineSessionStore(SESSIONS_DIR, agent.id, engine, providerProfileFingerprint(provider) || undefined)this.adapter = getAdapter(engine)}@@ -1975,6 +1985,7 @@ class AgentRunner {await Promise.allSettled([session?.stop({ force: options.forceEngine }) ?? Promise.resolve(),this.activeEngineRun ?? Promise.resolve(),+ this.activeTriage ?? Promise.resolve(),])await this.sessionStore.flush()}@@ -1984,8 +1995,9 @@ class AgentRunner {* fixed, and seedHome runs once in start()), so when any of them changes in* Cumora, sync() must tear this runner down and build a fresh one — otherwise* e.g. a Claude→Codex switch wouldn't take effect until a daemon restart. */- configMatches(agent: AgentInfo, engine: EngineId): boolean {+ configMatches(agent: AgentInfo, engine: EngineId, provider?: ProviderProfile): boolean {return this.adapter.id === engine+ && providerProfileFingerprint(this.provider) === providerProfileFingerprint(provider)&& this.agent.name === agent.name&& this.agent.role === agent.role&& this.agent.systemPrompt === agent.systemPrompt@@ -1997,7 +2009,7 @@ class AgentRunner {if (this.token && Date.now() < this.tokenExpiresAt - TOKEN_REFRESH_SKEW_MS) return this.tokenconst minted = await api<{ token: string; expiresInSeconds: number }>(this.cfg.serverUrl, `/api/agents/${this.agent.id}/runtime-token`,- { method: 'POST', headers: { Authorization: `Bearer ${this.cfg.deviceToken}` }, body: '{}', signal },+ { method: 'POST', headers: { Authorization: `Bearer ${this.cfg.deviceToken}` }, body: JSON.stringify({ providerProfile: this.agent.providerProfile ?? null }), signal },)this.token = minted.tokenthis.tokenExpiresAt = Date.now() + minted.expiresInSeconds * 1000@@ -2053,11 +2065,13 @@ class AgentRunner {* or bearer token crosses the model-process boundary. *//** Big-brain model for the local engine, after the CUMORA_ENGINE_MODEL escape. */private engineModel(): string | null {+ if (this.provider) return this.agent.model || this.provider.modelreturn resolveEngineModel(this.agent.model, process.env.CUMORA_ENGINE_MODEL)}/** Small/fast-brain model for the local engine, after the same escape. */private engineFastModel(): string | null {+ if (this.provider) return this.agent.fastModel || this.provider.fastModelreturn resolveEngineFastModel(this.agent.fastModel, process.env.CUMORA_ENGINE_MODEL)}@@ -2066,17 +2080,19 @@ class AgentRunner {* already accepts a model, while preserving CUMORA_TRIAGE_MODEL as a fallback* for old deployments and engines left on their default. */private triageModelPin(): string | undefined {+ if (this.provider) return this.agent.fastModel || this.provider.fastModelreturn resolveTriageModel(this.agent.fastModel, process.env.CUMORA_TRIAGE_MODEL, process.env.CUMORA_ENGINE_MODEL)}private engineEnv(): NodeJS.ProcessEnv {- return {+ const env = {...process.env,PATH: engineProcessPath(this.binDir),CUMORA_AGENT_IPC_DIR: this.ipcDir,CUMORA_AGENT_MCP_SHIM: join(this.trustedCliDir, 'cumora-mcp'),CUMORA_AGENT_ID: this.agent.id,}+ return this.provider ? providerProfileEnv(env, this.provider) : env}/** The long-lived engine process for this agent (persistent stream-json),@@ -2086,6 +2102,7 @@ class AgentRunner {* prior process has died it respawns, resuming this.sessionId so context* carries across the restart. */private ensureEngineSession(resumeSessionId = this.resumeSessionId()): EngineSession | null {+ if (this.stopped) return nullif (!this.adapter.startSession) return nullif (this.persistentUnusable) return nullif (this.engineSession?.alive) return this.engineSession@@ -2120,7 +2137,7 @@ class AgentRunner {}private visibleEngineError(exitCode: number, detail?: string): string {- const raw = conciseError(detail || `process exited with code ${exitCode}`)+ const raw = conciseError(redactProviderSecret(detail || `process exited with code ${exitCode}`, this.provider))const redacted = raw.split(this.home).join('<agent home>').split(homedir()).join('~')@@ -2216,10 +2233,13 @@ class AgentRunner {await spawnPacer.gate()const controller = new AbortController()const timer = setTimeout(() => controller.abort(), TRIAGE_TIMEOUT_MS)+ const onStop = () => controller.abort(this.teardown.signal.reason)+ this.teardown.signal.addEventListener('abort', onStop, { once: true })let res: { text: string; error?: string; usage?: EngineUsage; model?: string | null }try {await mkdir(TRIAGE_DIR, { recursive: true })- res = await this.adapter.classify({+ this.teardown.signal.throwIfAborted()+ const pending = this.adapter.classify({cwd: TRIAGE_DIR,prompt: `${payload.instructions}\n\n${payload.input}`,env: this.engineEnv(),@@ -2228,13 +2248,19 @@ class AgentRunner {model: this.triageModelPin(),signal: controller.signal,})+ this.activeTriage = pending+ res = await pending} catch (err) {res = { text: '', error: err instanceof Error ? err.message : String(err) }} finally {clearTimeout(timer)triageSem.release()+ this.activeTriage = null+ this.teardown.signal.removeEventListener('abort', onStop)}+ res.text = redactProviderSecret(res.text, this.provider)+ if (res.error) res.error = redactProviderSecret(res.error, this.provider)if (res.error || !res.text.trim()) {const errText = res.error ?? 'no output'// CRITICAL: a rate-limited small model must NOT fail-open. Fail-open wakes@@ -2436,6 +2462,7 @@ class AgentRunner {* hook chatter (started/response × N hooks) and rate-limit keepalives. We* keep the signal — assistant text, tool calls/results, init, errors. */private logEngineLine(line: string): void {+ line = redactProviderSecret(line, this.provider)if (line.includes('"hook_started"') || line.includes('"hook_response"') || line.includes('"rate_limit_event"')) returnconsole.log(`[${this.agent.id}/${this.adapter.id}] ${line.slice(0, 500)}`)}@@ -2643,6 +2670,7 @@ class AgentRunner {this.memoryDigest(),runtimeGet<{ roster: string }>(this.cfg.serverUrl, '/roster', token).then((r) => r?.roster ?? '').catch(() => ''),])+ this.teardown.signal.throwIfAborted()const result = await this.runWithSessionRecovery(this.agendaDelta(ag.brief, memoryDigest, roster))exitCode = result.exitCodeturnUsage = result.usage@@ -2888,6 +2916,7 @@ class AgentRunner {// `briefedManual` path. Only ordinary inbox wakes need the small-brain// triage decision.const triage = activeBackgroundBrief ? null : await this.inboxTriage(token)+ if (this.stopped) breakconst triageMs = Date.now() - turnStart // ensureToken + snapshot + triage// Triage was rate-limited → STOP. Do NOT retry, do NOT wake the big brain,// do NOT ack (the message is retried after the cooldown). Back off@@ -3023,6 +3052,7 @@ class AgentRunner {runtimeGet<{ roster: string }>(this.cfg.serverUrl, '/roster', token).then((r) => r?.roster ?? '').catch(() => ''),])+ this.teardown.signal.throwIfAborted()const delta = turnBackgroundBrief? this.manualBriefDelta(turnBackgroundBrief, memoryDigest, digest, roster): this.chatDelta(memoryDigest, triageNote, digest, roster)@@ -3038,7 +3068,7 @@ class AgentRunner {await this.resetEngineSession(this.resetReason(engineError))}} catch (err) {- console.error(`[computer] ${this.agent.id} engine spawn failed:`, err instanceof Error ? err.message : err)+ console.error(`[computer] ${this.agent.id} engine spawn failed:`, redactProviderSecret(err instanceof Error ? err.message : String(err), this.provider))exitCode = 1engineError = this.visibleEngineError(exitCode, err instanceof Error ? (err.stack || err.message) : String(err))} finally {@@ -3308,7 +3338,7 @@ async function doRun(serverOverride?: string): Promise<void> {const syncOnce = async (): Promise<void> => {let agents: AgentInfo[]try {- agents = await api<AgentInfo[]>(cfg.serverUrl, '/api/computers/me/agents', {+ agents = await api<AgentInfo[]>(cfg.serverUrl, '/api/computers/me/agents?providerProfiles=1', {headers: { Authorization: `Bearer ${cfg.deviceToken}` },})} catch (err) {@@ -3316,8 +3346,16 @@ async function doRun(serverOverride?: string): Promise<void> {return}const available = engineInventory.current+ let profiles: ProviderProfile[] = []+ try { profiles = readProviderProfiles(join(CONFIG_DIR, 'providers.json')) }+ catch (err) { console.warn('[computer]', (err as Error).message) }for (const agent of agents) {- const engine = resolveAvailableEngine(agent.engine, available)+ const provider = profiles.find((p) => p.id === agent.providerProfile)+ // A bound profile must never fall through to another engine or account.+ const engine = agent.providerProfile+ ? (provider && !allowUnsandboxedByoa() && agent.engine === 'claude' && available.includes('claude') ? 'claude' : null)+ : resolveAvailableEngine(agent.engine, available)+ if (agent.providerProfile && !engine) console.warn(`[computer] provider unavailable for ${agent.id}; runner stopped`)if (!engine) {// A successful rescan may legitimately find that the last installed CLI// was removed. Stop an existing runner instead of leaving it alive on an@@ -3332,14 +3370,14 @@ async function doRun(serverOverride?: string): Promise<void> {}const existing = runners.get(agent.id)if (existing) {- if (existing.configMatches(agent, engine)) continue+ if (existing.configMatches(agent, engine, provider)) continue// Engine/model/persona was edited in Cumora — restart the runner so the// change takes effect on the next wake without a daemon restart.console.log(`[computer] agent ${agent.name} (${agent.id}) config changed → restarting on ${engine}`)runners.delete(agent.id)await existing.stop({ forceEngine: true })}- const runner = new AgentRunner(cfg, agent, engine)+ const runner = new AgentRunner(cfg, agent, engine, provider)runners.set(agent.id, runner)console.log(`[computer] hosting agent ${agent.name} (${agent.id}) on ${engine}`)await runner.start()@@ -3423,13 +3461,18 @@ async function doRun(serverOverride?: string): Promise<void> {// when the card's version line goes stale. The blocked reasons are part// of the fingerprint: fixing the cause (upgrading the CLI, installing// bwrap) has to clear the card, not wait for an unrelated change.- const fingerprint = JSON.stringify(snapshot)+ let profiles: ProviderProfile[] = []+ try { profiles = readProviderProfiles(join(CONFIG_DIR, 'providers.json')) }+ catch (err) { console.warn('[computer]', (err as Error).message) }+ const advertisedSnapshot = snapshot.map((entry) => entry.id === 'claude'+ ? { ...entry, providerProfiles: allowUnsandboxedByoa() ? [] : profiles.map(providerProfileMetadata) } : entry)+ const fingerprint = JSON.stringify(advertisedSnapshot)if (shouldReportEngineSnapshot(fingerprint, lastEngineSnapshot, forceReport)) {lastEngineSnapshot = fingerprintawait api(cfg.serverUrl, '/api/computers/me/engines', {method: 'POST',headers: { Authorization: `Bearer ${cfg.deviceToken}` },- body: JSON.stringify({ engines: next, detected: snapshot, blocked: blockedIds }),+ body: JSON.stringify({ engines: next, detected: advertisedSnapshot, blocked: blockedIds }),}).catch((err) => {console.warn('[computer] engine snapshot report failed', err instanceof Error ? err.message : err)})@@ -3957,7 +4000,7 @@ export async function restartService(hooks: RestartServiceHooks = {}): Promise<v* match incidentally elsewhere in the command line. */export const ONE_SHOT_FLAGS = ['stop', 'status', 'restart', 'logs', 'version', 'install-service',- 'uninstall-service', 'pair', 'doctor', 'help',+ 'uninstall-service', 'pair', 'doctor', 'provider', 'help',] as constconst ONE_SHOT_FLAG_RE = new RegExp(`--(?:${ONE_SHOT_FLAGS.join('|')})\\b`)@@ -4284,11 +4327,23 @@ async function tailLogs(): Promise<void> {* brain (the triage cerebellum) reachable + authed? Each tier gets a trivial* one-shot probe over the SAME spawn path real wakes use, so green here means* real wakes will work. Pure local: no cloud, no DB, no pairing required. */-async function runDoctor(): Promise<void> {+async function runDoctor(providerId?: string): Promise<void> {+ const provider = providerId !== undefined+ ? readProviderProfiles(join(CONFIG_DIR, 'providers.json')).find((p) => p.id === providerId) : undefined+ if (providerId !== undefined && !provider) throw new Error('provider profile not found in providers.json')console.log(`cumora ${CURRENT_VERSION} · engine doctor`)console.log('probing local engines (big brain = main reasoning, small brain = triage cerebellum)…\n')- const results = await runEngineDoctor({ onLog: (l) => console.error(` · ${l}`) })+ const results = await runEngineDoctor({+ env: provider ? providerProfileEnv(process.env, provider) : undefined,+ engines: provider ? ['claude'] : undefined,+ onLog: (l) => console.error(` · ${redactProviderSecret(l, provider)}`),+ })+ for (const result of results) {+ for (const health of [result.big, result.small, result.wake]) {+ if (health) health.detail = redactProviderSecret(health.detail, provider)+ }+ }console.log('')let anyUsable = false@@ -4339,10 +4394,11 @@ async function runDoctor(): Promise<void> {export async function runComputerDaemon(argv: string[]): Promise<void> {const args = parseArgs(argv)+ if (args.provider !== undefined && !args.doctor) throw new Error('--provider requires --doctor')const serverUrl = (args.server || DEFAULT_SERVER).replace(/\/+$/, '')if (args.help) { console.log(helpText()); return }if (args.version) { console.log(CURRENT_VERSION); return }- if (args.doctor) { await runDoctor(); return }+ if (args.doctor) { await runDoctor(args.provider); return }if (args.restart) { await restartService(); return }if (args.stop) { await stopService(); return }if (args.status) { await printStatus(); return }diff --git a/server/src/agents/computer/engine.ts b/server/src/agents/computer/engine.tsindex f5c4564..18cf984 100644--- a/server/src/agents/computer/engine.ts+++ b/server/src/agents/computer/engine.ts@@ -5446,6 +5446,7 @@ function salientError(raw: string): string {* real wakes will work. Engines are probed in parallel; the two tiers of one* engine run sequentially to avoid self-induced rate limits. Never throws. */export async function runEngineDoctor(opts?: {+ engines?: EngineId[]env?: NodeJS.ProcessEnv/** Per-tier timeout. Default 60s — a cold engine + auth handshake can be slow. */timeoutMs?: number@@ -5454,7 +5455,7 @@ export async function runEngineDoctor(opts?: {const env = opts?.env ?? process.envconst timeoutMs = opts?.timeoutMs ?? 60_000const cwd = await mkdtemp(join(tmpdir(), 'cumora-doctor-'))- const ids = Object.keys(ADAPTERS) as EngineId[]+ const ids = opts?.engines ?? Object.keys(ADAPTERS) as EngineId[]return Promise.all(ids.map(async (id): Promise<EngineHealth> => {const adapter = ADAPTERS[id]const path = (await resolveBinPath(adapter.bin)) ?? (id === 'grok' ? resolveGrokBin(env) : null)diff --git a/server/src/agents/computer/provider-profiles.ts b/server/src/agents/computer/provider-profiles.tsnew file mode 100644index 0000000..3bc403d--- /dev/null+++ b/server/src/agents/computer/provider-profiles.ts@@ -0,0 +1,137 @@+/** Local-only Claude credentials. Only providerProfileMetadata may cross the+ * daemon/server boundary; the configuration lives outside every Agent home. */+import { createHash } from 'node:crypto'+import { closeSync, constants, fstatSync, openSync, readFileSync } from 'node:fs'+import { CLAUDE_CORE_ENV_KEYS } from './claude-user-settings.js'++export interface ProviderProfileMetadata {+ id: string+ label: string+ model: string+ fastModel: string+}++export interface ProviderProfile extends ProviderProfileMetadata {+ baseUrl: string+ auth: { apiKey: string } | { authToken: string }+}++export function isProviderProfileId(value: unknown): value is string {+ return typeof value === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(value)+}++function record(value: unknown): Record<string, unknown> {+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('expected an object')+ return value as Record<string, unknown>+}++function field(value: unknown, max: number): string {+ if (typeof value !== 'string' || !value.trim() || value.length > max || /[\x00-\x1f\x7f]/.test(value)) {+ throw new Error('invalid text field')+ }+ return value.trim()+}++/** Explicit projection also protects against accidentally reporting newly+ * added private fields. The server repeats this projection on untrusted input. */+export function providerProfileMetadata(profile: ProviderProfileMetadata): ProviderProfileMetadata {+ return { id: profile.id, label: profile.label, model: profile.model, fastModel: profile.fastModel }+}++export function sanitizeProviderProfiles(value: unknown): ProviderProfileMetadata[] {+ if (!Array.isArray(value)) return []+ const result = new Map<string, ProviderProfileMetadata>()+ for (const item of value.slice(0, 50)) {+ try {+ const p = record(item)+ if (!isProviderProfileId(p.id)) continue+ result.set(p.id, { id: p.id, label: field(p.label, 80), model: field(p.model, 160), fastModel: field(p.fastModel, 160) })+ } catch { /* malformed discovery metadata is not selectable */ }+ }+ return [...result.values()]+}++export function parseProviderProfiles(raw: unknown): ProviderProfile[] {+ try {+ const config = record(raw)+ if (config.version !== 1 || !Array.isArray(config.profiles) || config.profiles.length > 50) throw new Error()+ const ids = new Set<string>()+ return config.profiles.map((value) => {+ const p = record(value)+ if (!isProviderProfileId(p.id) || ids.has(p.id)) throw new Error()+ ids.add(p.id)+ const baseUrl = field(p.baseUrl, 2048)+ const url = new URL(baseUrl)+ if (url.username || url.password || url.search || url.hash) throw new Error()+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))) throw new Error()+ const auth = record(p.auth)+ const keys = Object.keys(auth)+ if (keys.length !== 1 || !['apiKey', 'authToken'].includes(keys[0])) throw new Error()+ const secret = field(auth[keys[0]], 8192)+ return {+ id: p.id, label: field(p.label, 80), baseUrl: url.href.replace(/\/$/, ''),+ model: field(p.model, 160), fastModel: field(p.fastModel, 160),+ auth: keys[0] === 'apiKey' ? { apiKey: secret } : { authToken: secret },+ }+ })+ } catch {+ // Never put JSON values, URL parser errors, or credentials into daemon logs.+ throw new Error('invalid providers.json: expected version 1 and unique Claude profiles with id, label, baseUrl, model, fastModel and one auth credential')+ }+}++export function readProviderProfiles(path: string): ProviderProfile[] {+ let fd: number+ try {+ fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0))+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return []+ throw new Error('cannot open providers.json (must be a regular local file)')+ }+ try {+ const stat = fstatSync(fd)+ if (!stat.isFile() || stat.size > 1024 * 1024) throw new Error('providers.json must be a regular file under 1 MiB')+ if (process.platform !== 'win32' && ((stat.mode & 0o077) !== 0 || stat.uid !== process.getuid?.())) {+ throw new Error('providers.json must be owned by the daemon user with permissions 0600')+ }+ let raw: unknown+ try { raw = JSON.parse(readFileSync(fd, 'utf8')) } catch { throw new Error('providers.json is not valid JSON') }+ return parseProviderProfiles(raw)+ } finally {+ closeSync(fd)+ }+}++/** Changing credentials, endpoint or model namespace starts a separate native+ * session. The digest stays local and is never included in discovery metadata. */+export function providerProfileFingerprint(profile?: ProviderProfile): string {+ return profile ? createHash('sha256').update(JSON.stringify({ id: profile.id, baseUrl: profile.baseUrl, auth: profile.auth, model: profile.model, fastModel: profile.fastModel })).digest('hex') : ''+}++export function providerProfileEnv(env: NodeJS.ProcessEnv, profile: ProviderProfile): NodeJS.ProcessEnv {+ if (env.CUMORA_BYOA_ALLOW_UNSANDBOXED === '1') throw new Error('provider profiles require secure BYOA mode')+ const next = { ...env }+ for (const key of Object.keys(next)) {+ if (key.startsWith('ANTHROPIC_') || key.startsWith('CLAUDE_CODE_USE_')) next[key] = ''+ }+ // Empty values suppress the restricted adapter's ~/.claude provider bootstrap.+ for (const key of CLAUDE_CORE_ENV_KEYS) next[key] = ''+ return {+ ...next,+ CUMORA_BYOA_ALLOW_UNSANDBOXED: '0',+ CUMORA_ENGINE_MODEL: '', CUMORA_TRIAGE_MODEL: '',+ CLAUDE_CODE_OAUTH_TOKEN: '',+ ANTHROPIC_BASE_URL: profile.baseUrl,+ ANTHROPIC_API_KEY: 'apiKey' in profile.auth ? profile.auth.apiKey : '',+ ANTHROPIC_AUTH_TOKEN: 'authToken' in profile.auth ? profile.auth.authToken : '',+ ANTHROPIC_MODEL: profile.model,+ ANTHROPIC_DEFAULT_HAIKU_MODEL: profile.fastModel,+ ANTHROPIC_SMALL_FAST_MODEL: profile.fastModel,+ }+}++export function redactProviderSecret(text: string, profile?: ProviderProfile): string {+ if (!profile) return text+ const secret = 'apiKey' in profile.auth ? profile.auth.apiKey : profile.auth.authToken+ return text.split(secret).join('[redacted]')+}diff --git a/server/src/agents/computer/registry.ts b/server/src/agents/computer/registry.tsindex 58f9ed1..c738ef0 100644--- a/server/src/agents/computer/registry.ts+++ b/server/src/agents/computer/registry.ts@@ -14,6 +14,7 @@* - per-agent runtime JWTs minted for a paired device (reuses* runtime/jwt.ts — the same token a pod gets)*/+import { type ProviderProfileMetadata, isProviderProfileId, sanitizeProviderProfiles } from './provider-profiles.js'import { createHash, randomBytes, randomUUID } from 'node:crypto'import { pool } from '../../db/pool.js'import { CH_STATUS, publish } from '../../redis.js'@@ -117,6 +118,7 @@ const ENGINE_BINS: Record<Exclude<EngineId, 'managed'>, string> = {/** Cached PATH snapshot from the daemon. The app reads this; it never probes. */export interface DetectedEngine {+ providerProfiles?: ProviderProfileMetadata[]id: stringbin: stringpath: string | null@@ -247,6 +249,7 @@ export function sanitizeDetectedEngines(byId.set(id, {id, bin, path, ...sanitizeVersionFields(rec), blockedReason,...(modelCatalog ? { modelCatalog } : {}),+ ...(id === 'claude' && Array.isArray(rec.providerProfiles) ? { providerProfiles: sanitizeProviderProfiles(rec.providerProfiles) } : {}),})}// Every row carries the same keys, reported or not, so the app never has to@@ -604,6 +607,7 @@ export async function resolveDevice(token: string): Promise<{ computerId: string* This is the credential the daemon uses for the agent's wake-stream SSE and* daemon-side runtime calls. It never enters the model process or agent home. */export async function mintAgentRuntimeToken(args: {+ providerProfile?: string | nullcomputerId: stringagentId: string}): Promise<{ token: string; expiresInSeconds: number } | null> {@@ -620,8 +624,9 @@ export async function mintAgentRuntimeToken(args: {AND c.revoked_at IS NULLWHERE p.id = $1 AND p.kind = 'agent' AND p.computer_id = $2AND p.departed_at IS NULL+ AND p.provider_profile IS NOT DISTINCT FROM $3::textLIMIT 1`,- [args.agentId, args.computerId],+ [args.agentId, args.computerId, args.providerProfile ?? null],)if (!rows[0]) return nullconst token = signAgentToken({@@ -646,23 +651,25 @@ export async function mintAgentRuntimeToken(args: {* changes 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 }>+export async function listAgentsForComputer(computerId: string, supportsProviderProfiles = false): Promise<+ Array<{ id: string; name: string; role: string | null; systemPrompt: string | null; engine: EngineId | null; model: string | null; fastModel: string | null; providerProfile: string | null }>> {const { rows } = await pool.query<{id: string; name: string; role: string | null; systemPrompt: string | nullengine: EngineId | null; model: string | null; fastModel: string | null+ providerProfile: string | nullavailableEngines?: string[]; detectedEngines?: unknown; engineDefaults?: 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",+ p.fast_model AS "fastModel", p.provider_profile AS "providerProfile", c.available_engines AS "availableEngines",COALESCE(c.detected_engines, '[]'::jsonb) AS "detectedEngines",COALESCE(c.engine_defaults, '{}'::jsonb) AS "engineDefaults"FROM participants pJOIN computers c ON c.id = p.computer_idWHERE p.computer_id = $1 AND p.kind = 'agent' AND p.departed_at IS NULL+ AND ($2::boolean OR p.provider_profile IS NULL)ORDER BY p.name ASC`,- [computerId],+ [computerId, supportsProviderProfiles],)const claudeDefault = process.env.CUMORA_DEFAULT_CLAUDE_MODEL?.trim() || nullconst codexDefault = process.env.CUMORA_DEFAULT_CODEX_MODEL?.trim() || null@@ -675,6 +682,9 @@ export async function listAgentsForComputer(computerId: string): Promise<const antigravityDefault = process.env.CUMORA_DEFAULT_ANTIGRAVITY_MODEL?.trim() || nullreturn rows.map((r) => {const { availableEngines, detectedEngines, engineDefaults, ...agent } = r+ // A profile's endpoint owns its model namespace: neither the computer's+ // engine_defaults nor the deploy-level pin may name a model for it.+ if (agent.providerProfile) return agentconst localCatalog = sanitizeDetectedEngines(detectedEngines, availableEngines ?? []).find((entry) => entry.id === agent.engine)?.modelCatalog// Parse the engine_defaults JSONB@@ -947,6 +957,7 @@ export function isByoaKind(kind: ComputerKind | null): boolean {* `strictEngine` so an unavailable explicit pin fails instead of silently* selecting the Computer default. */export async function resolveComputerAssignment(args: {+ providerProfile?: string | nullcompanyId: stringcomputerId: stringengine?: string@@ -954,8 +965,8 @@ export async function resolveComputerAssignment(args: {inherit?: booleanstrictEngine?: boolean}, db: Queryable = pool): Promise<{ kind: ComputerKind; engine: EngineId; inherit: boolean } | null> {- const { rows } = await db.query<{ kind: ComputerKind; available_engines: string[] }>(- `SELECT kind, available_engines FROM computers+ const { rows } = await db.query<{ kind: ComputerKind; available_engines: string[]; detected_engines?: unknown }>(+ `SELECT kind, available_engines, detected_engines FROM computersWHERE id = $1 AND company_id = $2 AND revoked_at IS NULLLIMIT 1 FOR SHARE`,[args.computerId, args.companyId],@@ -985,6 +996,12 @@ export async function resolveComputerAssignment(args: {inherit = wantInherit}+ if (args.providerProfile != null) {+ if (!isProviderProfileId(args.providerProfile) || engine !== 'claude' || inherit) return null+ const profiles = sanitizeDetectedEngines(computer.detected_engines, computer.available_engines)+ .find((entry) => entry.id === 'claude')?.providerProfiles ?? []+ if (!profiles.some((p) => p.id === args.providerProfile)) return null+ }return { kind: computer.kind, engine, inherit }}@@ -994,6 +1011,7 @@ export async function resolveComputerAssignment(args: {* Returns the resolved { kind, engine } or null if the computer/agent is* invalid for this company. */export async function assignAgentToComputer(args: {+ providerProfile?: string | nullagentId: stringcompanyId: stringcomputerId: string@@ -1018,6 +1036,8 @@ export async function assignAgentToComputer(args: {params.push(args.fastModel)sets.push(`fast_model = $${params.length}`)}+ params.push(args.providerProfile ?? null)+ sets.push(`provider_profile = $${params.length}`)params.push(args.agentId, args.companyId)const { rowCount } = await pool.query(`UPDATE participants SET ${sets.join(', ')}diff --git a/server/src/agents/computer/session-store.ts b/server/src/agents/computer/session-store.tsindex cfcfbdd..c65d865 100644--- a/server/src/agents/computer/session-store.ts+++ b/server/src/agents/computer/session-store.ts@@ -26,9 +26,13 @@ export class EngineSessionStore {sessionsDir: string,private readonly agentId: string,engine: EngineId,+ /** Opaque extra dimension of session identity (currently the provider+ * profile fingerprint). A different value is a different endpoint or+ * account, so its pointer must never be offered to the other one. */+ scope?: string,) {this.engine = engine- this.sessionFile = join(sessionsDir, agentId, `${engine}.session`)+ this.sessionFile = join(sessionsDir, agentId, `${engine}${scope ? `.${scope}` : ''}.session`)this.legacyFile = join(sessionsDir, `${agentId}.session`)}diff --git a/server/src/agents/create.ts b/server/src/agents/create.tsindex 065d2a8..0c06f73 100644--- a/server/src/agents/create.ts+++ b/server/src/agents/create.ts@@ -32,6 +32,7 @@ export interface CreateAgentRecordInput {avatarBg?: stringmodel?: string | nullfastModel?: string | null+ providerProfile?: string | nulltools?: string[]computerId?: string | nullengine?: string@@ -93,6 +94,7 @@ function creationRequestHash(input: CreateAgentRecordInput): string {avatarBg: input.avatarBg ?? '',model: input.model ?? null,fastModel: input.fastModel ?? null,+ ...(input.providerProfile ? { providerProfile: input.providerProfile } : {}),tools: input.tools ?? ['bash'],computerId: input.computerId ?? null,engine: input.engine ?? null,@@ -187,12 +189,14 @@ export async function createAgentRecord(engine: input.engine,inherit: input.inherit,strictEngine: true,+ providerProfile: input.providerProfile,}, client)if (!placement) {throw new AgentCreationError(400, 'invalid computer or engine for this company')}}+ if (input.providerProfile && !placement) throw new AgentCreationError(400, 'provider profile requires a paired computer')const tools = input.tools ?? ['bash']for (const agentId of candidateAgentIds(input.name)) {const initial = input.initial || input.name.charAt(0).toUpperCase()@@ -201,10 +205,10 @@ export async function createAgentRecord(`INSERT INTO participants(id, kind, name, role, initial, avatar_bg, status, bio, tools,system_prompt, model, fast_model, company_id, computer_id, engine,- engine_inherit, creation_request_id, creation_request_hash)+ engine_inherit, creation_request_id, creation_request_hash, provider_profile)VALUES($1, 'agent', $2, $3, $4, $5, 'avail', $6, $7::jsonb,- $8, $9, $10, $11, $12, $13, $14, $15, $16)+ $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)ON CONFLICT DO NOTHINGRETURNING id`,[@@ -212,7 +216,7 @@ export async function createAgentRecord(JSON.stringify(tools), input.systemPrompt, input.model ?? null,input.fastModel ?? null, input.companyId, computerId,placement?.engine ?? null, placement?.inherit ?? true,- requestId, requestHash,+ requestId, requestHash, input.providerProfile ?? null,],)if (rows[0]) {diff --git a/server/src/api/router.ts b/server/src/api/router.tsindex dbfb180..e8cc07b 100644--- a/server/src/api/router.ts+++ b/server/src/api/router.ts@@ -1,4 +1,5 @@import { Router, json, type Request, type Response, type NextFunction } from 'express'+import { isProviderProfileId } from '../agents/computer/provider-profiles.js'import type { PoolClient } from 'pg'import {storage, UPLOAD_DIR, freshenAttachmentUrl, normalizeStorageKey,@@ -1203,6 +1204,11 @@ api.delete('/computers/:id', safe(async (req, res) => {res.json({ ok: true })}))+function readProviderProfile(value: unknown): string | null {+ if (value == null) return null+ if (!isProviderProfileId(value)) throw new HttpError(400, 'invalid provider profile id')+ return value+}// Assign an agent to a computer (move between Cumora Cloud and a paired// machine), choosing its engine (owner/admin).api.post('/agents/:id/computer', safe(async (req, res) => {@@ -1219,8 +1225,9 @@ api.post('/agents/:id/computer', safe(async (req, res) => {const out = await assignAgentToComputer({agentId: String(req.params.id), companyId, computerId, engine, inherit: inherit || !engine,model: modelPins.model, fastModel: modelPins.fastModel,+ providerProfile: readProviderProfile(req.body?.providerProfile),})- if (!out) throw new HttpError(400, 'invalid computer, agent, or engine for this company')+ if (!out) throw new HttpError(400, 'invalid computer, agent, engine, or provider profile for this company')res.json({ ok: true, ...out })}))@@ -1364,7 +1371,7 @@ api.get('/computers/me/control-stream', safe(async (req, res) => {// Agents assigned to the calling computer (daemon discovery on boot).api.get('/computers/me/agents', safe(async (req, res) => {const { computerId } = await requireDevice(req)- res.json(await listAgentsForComputer(computerId))+ res.json(await listAgentsForComputer(computerId, req.query.providerProfiles === '1'))}))// Daemon liveness heartbeat — keeps the computer 'online' (an offline sweep@@ -1385,7 +1392,7 @@ api.post('/computers/heartbeat', safe(async (req, res) => {// Mint a per-agent runtime JWT for the calling computer (daemon refresh loop).api.post('/agents/:id/runtime-token', safe(async (req, res) => {const { computerId } = await requireDevice(req)- const minted = await mintAgentRuntimeToken({ computerId, agentId: String(req.params.id) })+ const minted = await mintAgentRuntimeToken({ computerId, agentId: String(req.params.id), providerProfile: readProviderProfile(req.body?.providerProfile) })if (!minted) throw new HttpError(403, 'agent not assigned to this computer')res.json(minted)}))@@ -2445,14 +2452,14 @@ api.get('/participants', async (req, res) => {systemPrompt: string | null; model: string | nullemail: string | null; companySlug: string | nulldepartedAt: string | null- computerId: string | null; engine: string | null; fastModel: string | null+ computerId: string | null; engine: string | null; fastModel: string | null; providerProfile: string | nullengineInherit: boolean | null}>(`SELECT p.id, p.kind, p.name, p.role, p.initial,p.avatar_bg AS "avatarBg", p.avatar_url AS "avatarUrl",p.status, p.status_updated_at AS "statusUpdatedAt",p.bio, p.tools, p.system_prompt AS "systemPrompt", p.model,- p.computer_id AS "computerId", p.engine, p.fast_model AS "fastModel",+ p.computer_id AS "computerId", p.engine, p.fast_model AS "fastModel", p.provider_profile AS "providerProfile",p.engine_inherit AS "engineInherit",-- Email resolution differs by kind:-- - agents carry their own minted address on participants.email@@ -2942,6 +2949,7 @@ api.post('/agents', async (req, res) => {const computerId = typeof req.body?.computerId === 'string' ? req.body.computerId.trim() || null : nullconst engine = typeof req.body?.engine === 'string' ? req.body.engine : undefinedconst inherit = req.body?.inherit === true+ const providerProfile = readProviderProfile(req.body?.providerProfile)let creation: Awaited<ReturnType<typeof createAgentRecord>>try {creation = await createAgentRecord({@@ -2957,6 +2965,7 @@ api.post('/agents', async (req, res) => {avatarBg: data.avatarBg,model: data.model,fastModel: data.fastModel,+ providerProfile,tools: data.tools ?? undefined,computerId,engine,diff --git a/server/src/db/migrate.ts b/server/src/db/migrate.tsindex c4fc6fe..b465316 100644--- a/server/src/db/migrate.ts+++ b/server/src/db/migrate.ts@@ -5,6 +5,7 @@* Application replicas use the read-only compatibility gate in* schema-version.ts and never execute DDL while starting.*/+import { AGENT_PROVIDER_PROFILE_SQL, agentProviderProfileChecksum } from './migrations/0008-agent-provider-profile.js'import { createHash } from 'node:crypto'import { pool } from './pool.js'import {@@ -2595,6 +2596,12 @@ const VERSIONED_MIGRATIONS: readonly VersionedMigration[] = [transactional: true,up: applyEngineDefaults,},+ {+ ...SCHEMA_MIGRATIONS[7],+ sourceChecksum: agentProviderProfileChecksum(),+ transactional: true,+ up: async (client) => { await client.query(AGENT_PROVIDER_PROFILE_SQL) },+ },]export async function applyPendingMigration(diff --git a/server/src/db/migrations/0008-agent-provider-profile.ts b/server/src/db/migrations/0008-agent-provider-profile.tsnew file mode 100644index 0000000..e76abe1--- /dev/null+++ b/server/src/db/migrations/0008-agent-provider-profile.ts@@ -0,0 +1,33 @@+import { createHash } from 'node:crypto'++/** Bind runtime credentials to the selected local provider as well as the host. */+export const AGENT_PROVIDER_PROFILE_SQL = `+ALTER TABLE participants+ ADD COLUMN provider_profile TEXT CHECK (provider_profile ~ '^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$');++CREATE OR REPLACE FUNCTION rotate_participant_runtime_assignment_id()+RETURNS TRIGGER+LANGUAGE plpgsql+AS $migration$+BEGIN+ IF NEW.company_id IS DISTINCT FROM OLD.company_id+ OR NEW.computer_id IS DISTINCT FROM OLD.computer_id+ OR NEW.provider_profile IS DISTINCT FROM OLD.provider_profile+ OR NEW.kind IS DISTINCT FROM OLD.kind+ OR NEW.departed_at IS DISTINCT FROM OLD.departed_at THEN+ NEW.runtime_assignment_id := gen_random_uuid()::text;+ END IF;+ RETURN NEW;+END;+$migration$;++DROP TRIGGER participants_runtime_assignment_rotation ON participants;+CREATE TRIGGER participants_runtime_assignment_rotation+BEFORE UPDATE OF company_id, computer_id, kind, departed_at, provider_profile ON participants+FOR EACH ROW+EXECUTE FUNCTION rotate_participant_runtime_assignment_id();+`++export function agentProviderProfileChecksum(): string {+ return createHash('sha256').update(AGENT_PROVIDER_PROFILE_SQL).digest('hex')+}diff --git a/server/src/db/migrations/manifest.ts b/server/src/db/migrations/manifest.tsindex b9b86ac..73e276c 100644--- a/server/src/db/migrations/manifest.ts+++ b/server/src/db/migrations/manifest.ts@@ -52,12 +52,17 @@ export const SCHEMA_MIGRATIONS = [name: '0007_engine_defaults',checksum: '1d81ce74821ff467e73feac0d8116520c742775b7ef31badab22480e7c679632',},+ {+ version: 8,+ name: '0008_agent_provider_profile',+ checksum: '8816423a0ad867d4781c6a9e323e6e34ecadca0ecaf82bd0b9541f164a199fa0',+ },] as const satisfies readonly MigrationMetadata[]/** This build intentionally supports one exact schema range. Expand/contract* releases may widen the range, but both bounds must remain explicit. */-export const MIN_SUPPORTED_SCHEMA_VERSION = 7-export const MAX_SUPPORTED_SCHEMA_VERSION = 7+export const MIN_SUPPORTED_SCHEMA_VERSION = 8+export const MAX_SUPPORTED_SCHEMA_VERSION = 8function assertManifestShape(): void {for (let i = 0; i < SCHEMA_MIGRATIONS.length; i++) {diff --git a/src/api/client.ts b/src/api/client.tsindex f09dbac..3ca5e6e 100644--- a/src/api/client.ts+++ b/src/api/client.ts@@ -225,6 +225,7 @@ export interface ApiParticipant {computerId?: string | nullengine?: string | nullengineInherit?: boolean | null+ providerProfile?: string | nullfastModel?: string | null}@@ -314,6 +315,7 @@ export interface AgentInput {}export interface AgentCreateInput extends AgentInput {+ providerProfile?: string | null/** Stable for the lifetime of one create form so ambiguous retries replay. */requestId: string/** Initial host placement is committed atomically with the Agent row. */@@ -1010,10 +1012,11 @@ export const api = {inherit?: boolean,model?: string | null,fastModel?: string | null,+ providerProfile?: string | null,) =>http<{ ok: boolean; kind: ComputerKind; engine: EngineId; inherit?: boolean }>(`/agents/${encodeURIComponent(agentId)}/computer`,- { method: 'POST', body: JSON.stringify({ computerId, engine, inherit, model, fastModel }) }),+ { method: 'POST', body: JSON.stringify({ computerId, engine, inherit, model, fastModel, providerProfile }) }),createAgent: (input: AgentCreateInput) =>http<{id: stringdiff --git a/src/components/AgentEditor.tsx b/src/components/AgentEditor.tsxindex ef80935..d797f91 100644--- a/src/components/AgentEditor.tsx+++ b/src/components/AgentEditor.tsx@@ -26,6 +26,7 @@ function newCreateRequestId(): string {* the computer default means the user pinned it. */function initialEngineChoice(agent: Participant | null, computer: { kind: string; availableEngines: EngineId[] } | undefined): string {if (!agent || !computer || computer.kind === 'cloud') return INHERIT_ENGINE+ if (agent.providerProfile) return 'claude'const advertised = computer.availableEnginesconst engine = agent.engineif (!engine || engine === 'managed' || !advertised.includes(engine)) return INHERIT_ENGINE@@ -56,6 +57,7 @@ export function AgentEditor({ agent, onClose, onSaved }: Props) {const [systemPrompt, setSystemPrompt] = useState(agent?.systemPrompt ?? '')const [bio, setBio] = useState(agent?.bio ?? '')const [avatarBg, setAvatarBg] = useState(agent?.avatarBg ?? PALETTE[0])+ const [providerProfile, setProviderProfile] = useState(agent?.providerProfile ?? '')const [model, setModel] = useState(agent?.model ?? '')const [fastModel, setFastModel] = useState(agent?.fastModel ?? '')const [busy, setBusy] = useState(false)@@ -94,14 +96,21 @@ export function AgentEditor({ agent, onClose, onSaved }: Props) {: (selectedComputer?.availableEngines[0] ?? 'claude')) as EngineIdconst selectedComputerOffline = isByoa && selectedComputer.status !== 'online'- const modelCatalog = selectedComputer?.detectedEngines- ?.find((engine) => engine.id === selectedEngineId)- ?.modelCatalog+ const detectedEngine = selectedComputer?.detectedEngines?.find((engine) => engine.id === selectedEngineId)+ const profiles = detectedEngine?.providerProfiles ?? []+ const selectedProfile = profiles.find((p) => p.id === providerProfile)+ const modelCatalog = providerProfile ? {+ models: [], defaultModel: selectedProfile?.model, defaultFastModel: selectedProfile?.fastModel,+ supportsCustom: true, fastModelScope: 'agent',+ } : 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),// these Cumora-side settings show as the hint for "follow engine default".- const engineDefaultModel = selectedComputer?.engineDefaults?.[selectedEngineId]?.model ?? undefined- const engineDefaultFastModel = selectedComputer?.engineDefaults?.[selectedEngineId]?.fastModel ?? undefined+ // A profile's endpoint owns its own namespace, so the engine-wide default+ // must not be offered there — the server does not apply it either.+ const engineDefaults = providerProfile ? undefined : selectedComputer?.engineDefaults?.[selectedEngineId]+ const engineDefaultModel = engineDefaults?.model ?? undefined+ const engineDefaultFastModel = engineDefaults?.fastModel ?? undefinedconst modelOptions: Array<ComboboxOption<string>> = [{value: '',@@ -182,6 +191,7 @@ export function AgentEditor({ agent, onClose, onSaved }: Props) {if (id === computerId) returnengineTouched.current = truesetComputerId(id)+ setProviderProfile('')setEngineChoice(INHERIT_ENGINE)clearModelPins()}@@ -201,12 +211,12 @@ export function AgentEditor({ agent, onClose, onSaved }: Props) {const current = agent?.computerId ?? cloud?.idconst targetComputer = target ? computersById[target] : undefinedconst isByoaTarget = !!targetComputer && targetComputer.kind !== 'cloud'- const inherit = engineChoice === INHERIT_ENGINE- const pinned = inherit ? undefined : (engineChoice as EngineId)+ const inherit = !providerProfile && engineChoice === INHERIT_ENGINE+ const pinned = providerProfile ? 'claude' : inherit ? undefined : (engineChoice as EngineId)const savedChoice = initialEngineChoice(agent, targetComputer)const inheritChanged = isByoaTarget && inherit !== (savedChoice === INHERIT_ENGINE)const engineChanged = isByoaTarget && !inherit && pinned !== ((agent?.engine as EngineId) ?? null)- const assignmentChanged = Boolean(target && (target !== current || inheritChanged || engineChanged))+ const assignmentChanged = Boolean(target && (target !== current || inheritChanged || engineChanged || providerProfile !== (agent?.providerProfile ?? '')))const payload: AgentInput = {name, role, systemPrompt, bio, avatarBg,model: model.trim() || null,@@ -229,6 +239,7 @@ export function AgentEditor({ agent, onClose, onSaved }: Props) {...payload,requestId: createRequestId.current,computerId: target || null,+ providerProfile: providerProfile || null,engine: isByoaTarget ? pinned : undefined,inherit: isByoaTarget ? inherit : false,})@@ -249,6 +260,7 @@ export function AgentEditor({ agent, onClose, onSaved }: Props) {isByoaTarget ? inherit : false,model.trim() || null,fastModel.trim() || null,+ providerProfile || null,)if (isByoaTarget && pinned && out.engine !== pinned) {throw new Error(t('agent.enginePinRejected', { engine: engineLabel(pinned) }))@@ -362,6 +374,26 @@ export function AgentEditor({ agent, onClose, onSaved }: Props) {/></Field>+ {isByoa && selectedEngineId === 'claude' && (profiles.length > 0 || providerProfile) && (+ <Field label={t('agent.providerLabel')} hint={t('agent.providerHint')}>+ <Select+ ariaLabel={t('agent.providerLabel')}+ value={providerProfile}+ onValueChange={(value) => {+ setProviderProfile(value)+ if (value) { engineTouched.current = true; setEngineChoice('claude') }+ clearModelPins()+ }}+ options={[+ { value: '', label: t('agent.providerDefault') },+ ...profiles.map((p) => ({ value: p.id, label: p.label })),+ ...(providerProfile && !selectedProfile+ ? [{ value: providerProfile, label: t('agent.providerMissing', { id: providerProfile }), disabled: true }] : []),+ ]}+ />+ </Field>+ )}+<Fieldlabel={isByoa ? t('agent.modelLabelByoa') : t('agent.modelLabel')}hint={isByoa ? t('agent.modelHintByoaCatalog') : t('agent.modelHintCloud')}@@ -440,6 +472,7 @@ export function AgentEditor({ agent, onClose, onSaved }: Props) {if (value === engineChoice) returnengineTouched.current = truesetEngineChoice(value)+ setProviderProfile('')clearModelPins()}}options={(() => {diff --git a/src/locales/en.ts b/src/locales/en.tsindex 7a735d6..3d7aa86 100644--- a/src/locales/en.ts+++ b/src/locales/en.ts@@ -453,6 +453,10 @@ export const en = {'agent.bioHint': 'Optional, shown on the agent card.','agent.bioPh': "A one-line description of what they're best at.",'agent.modelLabel': 'Model',+ 'agent.providerLabel': 'Provider',+ 'agent.providerHint': 'Uses a profile configured on this computer. Changing providers starts a separate model session.',+ 'agent.providerDefault': 'Computer default account',+ '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.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 9d63bc0..1c9430e 100644--- a/src/locales/zh-CN.ts+++ b/src/locales/zh-CN.ts@@ -455,6 +455,10 @@ export const zhCN: Partial<Record<keyof typeof en, string>> = {'agent.bioHint': '可选,会显示在智能体卡片上。','agent.bioPh': '一行简介,说明它最擅长什么。','agent.modelLabel': '模型',+ 'agent.providerLabel': '模型服务商',+ 'agent.providerHint': '使用此电脑上配置的服务商。切换后使用独立的模型会话。',+ 'agent.providerDefault': '电脑默认账号',+ 'agent.providerMissing': '不可用:{id}','agent.modelLabelByoa': '主力模型(大脑)','agent.modelHintByoaCatalog': '从这台计算机上的引擎实际可用模型中选择;也可以搜索并输入自定义模型 ID。','agent.fastHintByoaCatalog': '用于收件箱分流等轻量判断的成员级模型。留空时使用该引擎的小脑默认值。',diff --git a/src/stores/participants.ts b/src/stores/participants.tsindex 8d792ed..df89954 100644--- a/src/stores/participants.ts+++ b/src/stores/participants.ts@@ -68,6 +68,7 @@ function fromApi(p: ApiParticipant): Participant {tools: p.tools ?? undefined,systemPrompt: p.systemPrompt ?? undefined,model: p.model ?? null,+ providerProfile: p.providerProfile ?? null,fastModel: p.fastModel ?? null,email: p.email ?? null,departedAt: p.departedAt ?? null,diff --git a/src/types.ts b/src/types.tsindex 39f915d..59766a9 100644--- a/src/types.ts+++ b/src/types.ts@@ -27,6 +27,7 @@ export interface EngineModelCatalog {}export interface DetectedEngine {+ providerProfiles?: Array<{ id: string; label: string; model: string; fastModel: string }>id: EngineIdbin: stringpath: string | null@@ -99,6 +100,7 @@ export interface Participant {/** big-brain (main) model override; null/undefined = use system default */model?: string | null/** small-brain (fast/auxiliary) model override */+ providerProfile?: string | nullfastModel?: string | null/** id of the Computer this agent runs on (null/undefined = Cumora Cloud) */computerId?: string | null