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): restore sandboxed Bash for Claude agents
bingqilinweimaotai12084d30343b
diff --git a/server/src/__tests__/agents-computer-codex-runtime.test.ts b/server/src/__tests__/agents-computer-codex-runtime.test.tsindex ea606c1..1fa9f8e 100644--- a/server/src/__tests__/agents-computer-codex-runtime.test.ts+++ b/server/src/__tests__/agents-computer-codex-runtime.test.ts@@ -460,6 +460,7 @@ test('daemon migrates automatically, isolates failures, deduplicates retries andconst logError = console.errorconsole.error = (...args) => { errors.push(args.join(' ')); logError(...args) }const connected = new Set()+ let inventoryReported = falselet scans = 0let notices = 0let noticeAttempts = 0@@ -491,7 +492,8 @@ test('daemon migrates automatically, isolates failures, deduplicates retries and}if (path.endsWith('wake-stream')) connected.add(options.headers.Authorization.slice(7))if (path.endsWith('stream')) return new Response(new ReadableStream({ start() {} }), { headers: { 'Content-Type': 'text/event-stream' } })- if (path === '/api/computers/heartbeat' || path === '/api/computers/me/engines') return Response.json({})+ if (path === '/api/computers/me/engines') { inventoryReported = true; return Response.json({}) }+ if (path === '/api/computers/heartbeat') return Response.json({})throw new Error('Unexpected fixture request: ' + path)}const waitFor = async (condition) => {@@ -523,7 +525,9 @@ test('daemon migrates automatically, isolates failures, deduplicates retries andassert.deepEqual(errors, [])}assert.equal(process.exitCode, undefined)- process.exit(0)+ // Finish startup probes and drain runners before the parent removes their runtime directory.+ await waitFor(() => inventoryReported)+ process.emit('SIGTERM')`for (const recover of [true, false]) {const result = await execFileAsync(process.execPath, ['--import', 'tsx', '--input-type=module', '-e', script(recover)], {@@ -531,6 +535,7 @@ test('daemon migrates automatically, isolates failures, deduplicates retries and})assert.match(result.stdout, /healthy restored codex session/)assert.match(result.stdout, /blocked restored codex session/)+ assert.match(result.stdout, /shutting down \(SIGTERM\)/)assert.doesNotMatch(result.stderr, /new-user paused:/)for (const [agent, thread] of agentThreads) {assert.equal(await new EngineSessionStore(pointers, agent, 'codex', CODEX_SESSION_SCOPE).load(), thread)diff --git a/server/src/__tests__/agents-computer-engine.test.ts b/server/src/__tests__/agents-computer-engine.test.tsindex f89fb53..e01152d 100644--- a/server/src/__tests__/agents-computer-engine.test.ts+++ b/server/src/__tests__/agents-computer-engine.test.ts@@ -9,7 +9,7 @@ import { tmpdir } from 'node:os'import { delimiter, dirname, join } from 'node:path'import { afterEach, beforeEach, test } from 'node:test'import { setTimeout as delay } from 'node:timers/promises'-import { type EngineHopReport, type EngineRunResult, getAdapter, headlessSpawnOptions, resolveSpawn, runnableEngineIds, secureEngineCapabilityReason } from '../agents/computer/engine.js'+import { claudeSecureFlags, 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'@@ -53,7 +53,7 @@ async function writeFakeCli(binDir: string, name: string, source: string): Promiawait chmod(launcher, 0o755)}-function useFakeCliPath(binDir: string): void {+function setFakeCliPath(binDir: string): void {process.env.PATH = `${binDir}${delimiter}${process.env.PATH ?? ''}`}@@ -165,7 +165,7 @@ test('local engine failure returns stderr tail for observability', async () => {'claude',"process.stderr.write('Claude Code error: usage limit reached, no tokens left\\n')\nprocess.exit(1)\n",)- useFakeCliPath(binDir)+ setFakeCliPath(binDir)const logs: string[] = []const result = await getAdapter('claude').run({@@ -183,7 +183,51 @@ test('local engine failure returns stderr tail for observability', async () => {assert.deepEqual(logs, ['Claude Code error: usage limit reached, no tokens left'])})-test('Claude secure mode is fail-closed and strips tool credentials', { skip: IS_WIN }, async () => {+test('Claude Bash remains sandboxed with private tools, network and credentials denied', () => {+ const home = '/home/cumora-policy-agent'+ const argv = claudeSecureFlags(home, {+ PATH: dirname(process.execPath),+ CLAUDE_CONFIG_DIR: join(home, 'missing-config'),+ CUMORA_AGENT_MCP_SHIM: join(home, 'trusted', 'cumora-mcp'),+ ANTHROPIC_API_KEY: 'fixture-provider-key',+ GITHUB_TOKEN: 'fixture-github-token',+ BASH_ENV: '/untrusted-shell-startup',+ })+ const tools = argv[argv.indexOf('--tools') + 1].split(',')+ assert.ok(tools.includes('Bash'))+ assert.ok(tools.includes('mcp__cumora__cli'))+ const allowed = argv.slice(argv.indexOf('--allowedTools') + 1, argv.indexOf('--disallowedTools'))+ assert.deepEqual(allowed,+ [`Read(/${home}/**)`, `Edit(/${home}/**)`, 'Bash', 'mcp__cumora__cli'])+ const disallowed = argv[argv.indexOf('--disallowedTools') + 1].split(',')+ assert.equal(disallowed.includes('Bash'), false)+ for (const tool of ['PowerShell', 'WebFetch', 'WebSearch']) {+ assert.equal(tools.includes(tool), false)+ assert.ok(disallowed.includes(tool))+ }+ assert.ok(argv.includes('--restricted'))+ assert.equal(argv[argv.indexOf('--permission-mode') + 1], 'dontAsk')+ assert.ok(argv.includes('--strict-mcp-config'))++ const { permissions, sandbox } = JSON.parse(argv[argv.indexOf('--settings') + 1])+ assert.deepEqual(permissions.allow, allowed)+ assert.ok(permissions.allow.includes('Bash'))+ assert.equal(permissions.deny.includes('Bash'), false)+ assert.ok(permissions.deny.includes(`Read(/${home}/bin/**)`))+ assert.ok(permissions.deny.includes(`Edit(/${home}/bin/**)`))+ assert.equal(sandbox.enabled, true)+ assert.equal(sandbox.failIfUnavailable, true)+ assert.equal(sandbox.allowUnsandboxedCommands, false)+ assert.deepEqual(sandbox.excludedCommands, [])+ assert.deepEqual(sandbox.network, { allowedDomains: [], strictAllowlist: true })+ assert.ok(sandbox.filesystem.denyRead.includes('~/'))+ assert.ok(sandbox.filesystem.allowRead.includes(home))+ for (const name of ['ANTHROPIC_API_KEY', 'GITHUB_TOKEN', 'BASH_ENV']) {+ assert.ok(sandbox.credentials.envVars.some((entry: { name: string; mode: string }) => entry.name === name && entry.mode === 'deny'))+ }+})++async function checkClaudeSecureTransport(persistent: boolean): Promise<void> {const root = await mkdtemp(join(tmpdir(), 'cumora-claude-secure-'))tempDirs.push(root)const binDir = join(root, 'bin')@@ -206,21 +250,28 @@ test('Claude secure mode is fail-closed and strips tool credentials', { skip: IS'claude',"process.stderr.write(JSON.stringify({ argv: process.argv.slice(2), scrub: process.env.CLAUDE_CODE_SUBPROCESS_ENV_SCRUB, coreEnv: { apiKey: process.env.ANTHROPIC_API_KEY, authToken: process.env.ANTHROPIC_AUTH_TOKEN, baseUrl: process.env.ANTHROPIC_BASE_URL, unrelated: process.env.UNRELATED_SECRET } }))\nprocess.exit(1)\n",)- useFakeCliPath(binDir)+ setFakeCliPath(binDir)const logs: string[] = []const mcpShim = join(root, 'trusted', 'cumora-mcp')- await getAdapter('claude').run({+ const args = {home,- prompt: 'wake',env: secureClaudeEnv(root, {CLAUDE_CONFIG_DIR: configDir,ANTHROPIC_API_KEY: 'explicit-daemon-api-key',OPENAI_API_KEY: 'must-not-appear-in-settings',}),- onLog: (line) => logs.push(line),- signal: new AbortController().signal,- })+ onLog: (line: string) => logs.push(line),+ }+ if (persistent) {+ const session = getAdapter('claude').startSession?.(args)+ assert.ok(session)+ liveSessions.push(session)+ await session.send('wake')+ await session.stop()+ } else {+ await getAdapter('claude').run({ ...args, prompt: 'wake', signal: new AbortController().signal })+ }const captured = JSON.parse(logs[0] ?? '{}') as {argv?: string[]@@ -235,7 +286,7 @@ test('Claude secure mode is fail-closed and strips tool credentials', { skip: IS})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'))+ assert.ok(captured.argv?.includes('Read,Write,Edit,Glob,Grep,Bash,mcp__cumora__cli'))assert.equal(captured.argv?.some((arg) => /Bash\(cumora/.test(arg)), false)assert.equal(captured.argv?.some((arg) => arg.includes('dangerously-skip-permissions')), false)const mcpIndex = captured.argv?.indexOf('--mcp-config') ?? -1@@ -257,10 +308,12 @@ test('Claude secure mode is fail-closed and strips tool credentials', { skip: IScredentials?: { envVars?: Array<{ name?: string; mode?: string }> }}}- assert.ok(settings.permissions?.allow?.includes('Read(/**)'))- assert.ok(settings.permissions?.allow?.includes('Edit(/**)'))- assert.ok(settings.permissions?.deny?.includes('Read(/bin/**)'))- assert.ok(settings.permissions?.deny?.includes('Edit(/bin/**)'))+ assert.ok(settings.permissions?.allow?.includes(`Read(/${home}/**)`))+ assert.ok(settings.permissions?.allow?.includes(`Edit(/${home}/**)`))+ assert.ok(settings.permissions?.allow?.includes('Bash'))+ assert.equal(settings.permissions?.deny?.includes('Bash'), false)+ assert.ok(settings.permissions?.deny?.includes(`Read(/${home}/bin/**)`))+ assert.ok(settings.permissions?.deny?.includes(`Edit(/${home}/bin/**)`))assert.equal(settings.sandbox?.failIfUnavailable, true)assert.equal(settings.sandbox?.allowUnsandboxedCommands, false)assert.ok(settings.sandbox?.filesystem?.denyRead?.includes(process.platform === 'darwin' ? '/Users' : '/home'))@@ -271,7 +324,12 @@ test('Claude secure mode is fail-closed and strips tool credentials', { skip: IS}assert.doesNotMatch(settingsText, /must-not-appear-in-settings/)assert.doesNotMatch(settingsText, /settings-auth-token|explicit-daemon-api-key|provider\.example\.test/)-})+}++for (const persistent of [false, true]) {+ test(`Claude secure ${persistent ? 'session' : 'one-shot'} preserves Bash and strips tool credentials`,+ { skip: IS_WIN }, () => checkClaudeSecureTransport(persistent))+}test('Claude secure triage stays inside the custom provider model namespace', { skip: IS_WIN }, async () => {const root = await mkdtemp(join(tmpdir(), 'cumora-claude-provider-model-'))@@ -287,7 +345,7 @@ test('Claude secure triage stays inside the custom provider model namespace', {'claude',"process.stdout.write(JSON.stringify({ result: JSON.stringify({ argv: process.argv.slice(2) }) }))\n",)- useFakeCliPath(binDir)+ setFakeCliPath(binDir)const settingsPath = join(configDir, 'settings.json')await writeFile(settingsPath, JSON.stringify({@@ -349,7 +407,7 @@ if (argv.includes('--input-format')) {process.stdout.write(JSON.stringify({type:'result', subtype:'success', result:'OK'}) + '\\n')}`)- useFakeCliPath(binDir)+ setFakeCliPath(binDir)const preferences = {effortLevel: 'xhigh', modelSettings: { 'claude-opus-5': { effortLevel: 'medium' } },alwaysThinkingEnabled: true, language: 'Chinese',@@ -436,7 +494,7 @@ const reply = () => {if (argv.includes('--input-format')) require('node:readline').createInterface({ input: process.stdin }).on('line', reply)else { process.stdin.resume(); process.stdin.on('end', reply) }`)- useFakeCliPath(binDir)+ setFakeCliPath(binDir)for (const compatibility of [false, true]) {if (compatibility) process.env.CUMORA_BYOA_ALLOW_UNSANDBOXED = '1'else delete process.env.CUMORA_BYOA_ALLOW_UNSANDBOXED@@ -493,7 +551,7 @@ test('persistent Claude startup failure keeps stderr for first send', async () ='claude',"process.stderr.write('Claude Code error: subscription expired\\n')\nprocess.exit(1)\n",)- useFakeCliPath(binDir)+ setFakeCliPath(binDir)const logs: string[] = []const session = getAdapter('claude').startSession?.({@@ -533,7 +591,7 @@ test('persistent Claude classifies a rejected resume from its result event', asy'})\n' +'setInterval(() => {}, 1 << 30)\n',)- useFakeCliPath(binDir)+ setFakeCliPath(binDir)const session = getAdapter('claude').startSession?.({home,@@ -567,7 +625,7 @@ test('grok adapter seeds AGENTS.md and reports sessionId from stream-json', asyn'grok',`process.stdout.write(${JSON.stringify(`${grokEvents.map((event) => JSON.stringify(event)).join('\n')}\n`)})\n`,)- useFakeCliPath(binDir)+ setFakeCliPath(binDir)const adapter = getAdapter('grok')await adapter.seedHome(home, { id: 'iris', name: 'Iris', role: 'Designer', systemPrompt: null })@@ -773,7 +831,7 @@ test('Claude and Codex one-shot adapters return structured engine failures', asyawait mkdir(home)await writeFakeCli(binDir, 'claude', "process.stderr.write('No conversation found with session ID: claude-stale\\n')\nprocess.exit(1)\n")await writeFakeCli(binDir, 'codex', "process.stderr.write('429 Too Many Requests: rate limit reached\\n')\nprocess.exit(1)\n")- useFakeCliPath(binDir)+ setFakeCliPath(binDir)process.env.CUMORA_BYOA_ALLOW_UNSANDBOXED = '1'const signal = new AbortController().signal@@ -887,7 +945,7 @@ require('node:readline').createInterface({ input: process.stdin }).on('line', li}})`)- useFakeCliPath(binDir)+ setFakeCliPath(binDir)for (const nativeFastMode of [true, false]) {for (const resumeSessionId of [null, 'prior-thread', 'missing-thread']) {const logs: string[] = []@@ -1298,7 +1356,7 @@ if (argv.includes('--input-format')) {? capture() : JSON.stringify({type:'result', subtype:'success', result:'OK'})) + '\\n')}`)- useFakeCliPath(binDir)+ setFakeCliPath(binDir)const adapter = getAdapter('claude')const profiles: ProviderProfile[] = ['alpha', 'beta'].map((id, index) => ({id, label: id, baseUrl: `https://${id}.example.test`, model: `${id}/big`, fastModel: `${id}/small`,diff --git a/server/src/__tests__/agents-computer-prompt-surface.test.ts b/server/src/__tests__/agents-computer-prompt-surface.test.tsindex d733531..8d03485 100644--- a/server/src/__tests__/agents-computer-prompt-surface.test.ts+++ b/server/src/__tests__/agents-computer-prompt-surface.test.ts@@ -1,15 +1,6 @@/**- * The standing prompt has to describe the surface the agent actually has (#145).- *- * Secure mode removes the shell CLI on purpose — `<home>/bin` is never written,- * `node` is not in the tool environment, no runtime URL or token crosses into- * the model process — and gives the agent one MCP tool instead. Both secure- * engines are shaped that way: Codex through `mcp_servers.cumora`, Claude- * through `--tools …,mcp__cumora__cli` with Bash disallowed.- *- * Told to run `cumora` on its PATH, a secure agent spends the turn looking for- * a binary that was deliberately withheld. The report describes exactly that:- * it could reason and draft a reply, and could not publish it.+ * The standing prompt must expose sandboxed development commands while keeping+ * Cumora actions on the fixed MCP bridge (#145).** Run: node --import tsx --test server/src/__tests__/agents-computer-prompt-surface.test.ts*/@@ -26,15 +17,18 @@ test('secure mode gets the MCP tool, compatibility mode keeps the CLI', () => {assert.equal(actionSurfaceFor(true), 'cli')})-test('the secure prompt names the tool and forbids the hunt', () => {+test('the secure prompt allows local development and routes Cumora actions through MCP', () => {const text = actionSurfaceText('mcp')assert.match(text, /mcp__cumora__cli/)assert.match(text, /argv/)- // The report's actual failure was the agent probing for these, one after- // another, instead of using the tool it had.assert.match(text, /no `cumora` on\s+PATH/)- assert.match(text, /no `node`/)assert.match(text, /no runtime URL or token/)+ assert.match(text, /sandboxed shell/)+ assert.match(text, /scripts, tests and builds/)+ assert.match(text, /`workspace\/`/)+ assert.match(text, /build caches there/)+ assert.match(text, /Cumora actions still go through the MCP tool/)+ assert.doesNotMatch(text, /NO shell|no `node`|try to run a command line|whole surface/)assert.doesNotMatch(text, /CLI on your PATH/)})diff --git a/server/src/agents/computer/engine.ts b/server/src/agents/computer/engine.tsindex 8ea3060..413496e 100644--- a/server/src/agents/computer/engine.ts+++ b/server/src/agents/computer/engine.ts@@ -1541,7 +1541,7 @@ const TOOL_ENV_ALLOWLIST = new Set(['SYSTEMROOT', 'COMSPEC', 'PATHEXT', 'WINDIR',])-function claudeSecureSettings(agentHome: string, env: NodeJS.ProcessEnv, nativeFastMode = false): string {+function claudeSecureSettings(agentHome: string, env: NodeJS.ProcessEnv, nativeFastMode = false) {const deniedEnv = Object.keys(env).filter((name) => !TOOL_ENV_ALLOWLIST.has(name.toUpperCase()) && !name.toUpperCase().startsWith('LC_')).sort()@@ -1558,7 +1558,9 @@ function claudeSecureSettings(agentHome: string, env: NodeJS.ProcessEnv, nativeF.filter(Boolean)pathDirs.push(dirname(process.execPath))const allowRead = [...new Set([agentHome, ...pathDirs])]- return JSON.stringify({+ // Claude permission rules use // for absolute paths; / is source-relative.+ const fileScope = `/${agentHome.replaceAll('\\', '/').replace(/\/$/, '')}`+ return {...readClaudeUserSettings(env).turnSettings,fastMode: nativeFastMode,permissions: {@@ -1566,15 +1568,16 @@ function claudeSecureSettings(agentHome: string, env: NodeJS.ProcessEnv, nativeF// Restricted mode confines file tools to the working directory. Keep the// permission rules scoped too, so this JSON remains fail-closed if a// future Claude release changes a restricted-mode default.- allow: ['Read(/**)', 'Edit(/**)', 'mcp__cumora__cli'],+ allow: [`Read(${fileScope}/**)`, `Edit(${fileScope}/**)`, 'Bash', 'mcp__cumora__cli'],// The MCP bridge runs as a trusted daemon helper outside the command// sandbox. The model must never rewrite either helper executable.- deny: ['Read(/bin/**)', 'Edit(/bin/**)', 'Bash', 'PowerShell', 'WebFetch', 'WebSearch'],+ deny: [`Read(${fileScope}/bin/**)`, `Edit(${fileScope}/bin/**)`, 'PowerShell', 'WebFetch', 'WebSearch'],},sandbox: {enabled: true,failIfUnavailable: true,allowUnsandboxedCommands: false,+ excludedCommands: [],autoAllowBashIfSandboxed: true,filesystem: {denyRead,@@ -1583,7 +1586,7 @@ function claudeSecureSettings(agentHome: string, env: NodeJS.ProcessEnv, nativeFnetwork: { allowedDomains: [], strictAllowlist: true },credentials: { envVars: deniedEnv },},- })+ }}function claudeSecureMcpConfig(env: NodeJS.ProcessEnv): string {@@ -1602,13 +1605,16 @@ function claudeSecureMcpConfig(env: NodeJS.ProcessEnv): string {})}-function claudeSecureFlags(agentHome: string, env: NodeJS.ProcessEnv, nativeFastMode = false): string[] {+export function claudeSecureFlags(agentHome: string, env: NodeJS.ProcessEnv, nativeFastMode = false): string[] {+ const settings = claudeSecureSettings(agentHome, env, nativeFastMode)return ['--restricted','--permission-mode', 'dontAsk',- '--tools', 'Read,Write,Edit,Glob,Grep,mcp__cumora__cli',- '--disallowedTools', 'Bash,PowerShell,WebFetch,WebSearch',- '--settings', claudeSecureSettings(agentHome, env, nativeFastMode),+ '--tools', 'Read,Write,Edit,Glob,Grep,Bash,mcp__cumora__cli',+ // Subprocess credential scrubbing requires an explicit CLI approval list.+ '--allowedTools', ...settings.permissions.allow,+ '--disallowedTools', 'PowerShell,WebFetch,WebSearch',+ '--settings', JSON.stringify(settings),'--mcp-config', claudeSecureMcpConfig(env),'--strict-mcp-config',]diff --git a/server/src/agents/computer/prompt-surface.ts b/server/src/agents/computer/prompt-surface.tsindex 4926c52..9cb88f3 100644--- a/server/src/agents/computer/prompt-surface.ts+++ b/server/src/agents/computer/prompt-surface.ts@@ -1,27 +1,8 @@/**- * How a BYOA agent is told to reach Cumora — which is not the same in the two- * modes, and used to be described as if it were.- *- * Secure mode deliberately makes the shell CLI unreachable: `<home>/bin` is- * never written, it is not on PATH, `node` is absent from the permitted tool- * environment, and no runtime URL or bearer token crosses into the model- * process. Both secure engines are shaped that way — Codex gets- * `mcp_servers.cumora` with `enabled_tools=["cli"]`, Claude gets- * `--tools …,mcp__cumora__cli` with Bash disallowed outright.- *- * The standing prompt nevertheless told every agent to run `cumora` on its- * PATH, so a secure agent spent its turn hunting for a binary, for `node`, and- * for a runtime URL that had all been removed on purpose. It could read and- * reason; it could not act (#145).- *- * Its posting advice was wrong in a second, sharper way: it said to write long- * bodies to a file and post them with `--file`, and the MCP bridge REFUSES that- * flag ("local file/stdin flags are unavailable; pass body text directly in- * argv"). An agent that found the tool and followed the prompt still hit a- * guaranteed error.- *- * Extracted here as pure functions so the wording of both modes can be pinned- * without booting the daemon — the same reason cli-parse.ts is split out.+ * Secure engines use MCP for Cumora actions and a sandboxed shell for local+ * development. Only compatibility mode exposes the historical Cumora PATH shim.+ * The prompt must distinguish these capabilities and match the bridge's argv+ * interface, which deliberately refuses local --file / --stdin flags.*//** Whether the legacy shell CLI is on the model's PATH for this run. Compat@@ -40,9 +21,10 @@ export function actionSurfaceText(surface: ActionSurface): string {return ('You act on Cumora through the `mcp__cumora__cli` tool. Pass the command words as `argv` — ' +'`{"argv":["reply","<conversationId>","your text"]}` is the shape; every `cumora <cmd> …` ' +- 'below is the same words without the leading `cumora`. There is NO shell, no `cumora` on ' +- 'PATH, no `node`, and no runtime URL or token — those are withheld deliberately, so do not ' +- 'go looking for them or try to run a command line. The tool is the whole surface.\n\n'+ 'below is the same words without the leading `cumora`. There is no `cumora` on PATH ' ++ 'and no runtime URL or token to look for. Use the sandboxed shell for local scripts, ' ++ 'tests and builds under `workspace/`; keep project files and build caches there. ' ++ 'Cumora actions still go through the MCP tool, not the shell.\n\n')}