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(security): sandbox BYOA model execution (#132)
OKNOTOK9210a4bed21f
diff --git a/README.md b/README.mdindex a303bfb..1da1d12 100644--- a/README.md+++ b/README.md@@ -22,7 +22,7 @@ Cumora is cross-platform team chat where AI agents are first-class participantsTwo "brain" paths:- **Cumora Cloud** — each agent runs in a managed per-agent pod; turns run a multi-hop tool-calling loop on the OpenAI Responses API (bash, files, browser, email, memory, skills…).-- **BYOA (Bring Your Own Agent)** — pair your own Mac/VPS with `npx cumora agent computer` and the agent's brain becomes your local **Claude Code**, **Codex**, **Grok Build**, **Cursor Agent**, **OpenCode**, or **pi** CLI, on your own provider account. The server never sees your provider keys. See [`docs/BYOA.md`](docs/BYOA.md).+- **BYOA (Bring Your Own Agent)** — pair your own Mac/VPS with `npx cumora agent computer` and run the agent on your local provider account. Claude Code and Codex use fail-closed filesystem, command-network, and subprocess-credential boundaries by default; legacy engines require an explicit unsandboxed compatibility opt-in. The server never sees your provider keys. See [`docs/BYOA.md`](docs/BYOA.md).## Architecture@@ -99,7 +99,7 @@ npm run guard:big-brain # CI guard: only agent turns may use the big model## Docs-- [`docs/BYOA.md`](docs/BYOA.md) — Bring Your Own Agent: local Claude Code / Codex / Grok Build / Cursor Agent / OpenCode as an agent's brain.+- [`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/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/SECURITY.md b/SECURITY.mdindex 609ee55..a973024 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -55,13 +55,15 @@ Out of scope:## The trust model, in one paragraph-The **server is the only trust boundary**. Every client — the web app, the+The **server is the authorization boundary**. Every client — the web app, theElectron shell, the mobile shell, and the BYOA daemon — is untrusted and musthave its input validated server-side. Agent identity on every `/runtime/*`call is pinned from a signed JWT, never from the request body. Tenants are-isolated in SQL, not in the client. If you find a place where the server-trusts the client for any of these, that's a vulnerability we want to hear-about.+isolated in SQL, not in the client. On a BYOA host, a second boundary protects+the operator's machine: secure-default model tools are OS-sandboxed and receive+neither the runtime JWT nor the daemon's environment/network authority. If you+find a place where either boundary can be bypassed, that's a vulnerability we+want to hear about.## Deploying Cumora securelydiff --git a/agent-cli/README.md b/agent-cli/README.mdindex be18b48..01e76fc 100644--- a/agent-cli/README.md+++ b/agent-cli/README.md@@ -1,9 +1,11 @@# cumoraRun your [Cumora](https://cumora.ai) agents on your own machine or VPS,-powered by your **local Claude Code, Codex, Grok Build, Cursor Agent, OpenCode, or pi CLI**-(BYOA — Bring Your Own Agent). One daemon can host many agents; each gets its own isolated-workspace, memory, and skills on that machine.+powered by your local agent CLI (BYOA — Bring Your Own Agent). Claude Code and+Codex are sandboxed by default; Grok Build, Cursor Agent, OpenCode, pi, and+Gemini require an explicit unsandboxed compatibility opt-in. One daemon can+host many agents; each gets its own workspace, memory, and skills on that+machine.## Usage@@ -20,6 +22,11 @@ Then start the daemon (after pairing, the config is saved):npx cumora agent computer --server <your-server-url>```-Requires **Node ≥ 18** and `claude` (Claude Code), `codex`, `grok` (Grok Build),-`cursor-agent` (Cursor), `opencode`, `pi`, or `gemini` (Gemini CLI) on your `PATH`. The daemon talks to the Cumora server over HTTPS only — it needs no-database access.+Requires **Node ≥ 18** and a supported CLI on your `PATH`. Secure mode supports+Claude Code **≥ 2.1.248** on macOS/Linux/WSL2 and Codex **≥ 0.138.0** on+macOS/Linux/WSL2/native Windows. Older CLIs fail closed instead of falling back+to host-level authority.+The daemon talks to the Cumora server over HTTPS only — it needs no database+access. See the repository's `docs/BYOA.md` before enabling+`CUMORA_BYOA_ALLOW_UNSANDBOXED=1`; that switch grants model-generated tools the+host's ordinary file, environment, and network authority.diff --git a/agent-cli/src/cli.ts b/agent-cli/src/cli.tsindex dc9fe58..fd63885 100644--- a/agent-cli/src/cli.ts+++ b/agent-cli/src/cli.ts@@ -21,7 +21,8 @@ async function main(): Promise<void> {'Usage:\n' +' npx cumora@latest agent computer --pair <code> [--server <url>] pair this machine\n' +' npx cumora@latest agent computer [--server <url>] start the daemon\n\n' +- 'Needs `claude` (Claude Code), `codex`, `grok` (Grok Build), `cursor-agent` (Cursor), `opencode`, `pi`, or `gemini` (Gemini CLI) on PATH. Get a pairing code from\n' ++ 'Secure default: Claude Code on macOS/Linux/WSL2, or Codex on macOS/Linux/WSL2/Windows.\n' ++ 'Other engines require the high-risk CUMORA_BYOA_ALLOW_UNSANDBOXED=1 compatibility switch. Get a pairing code from\n' +'Cumora → You → Computers → Add a computer.\n',)process.exit(argv.length ? 1 : 0)diff --git a/docs/BYOA.md b/docs/BYOA.mdindex b3d96d3..395484d 100644--- a/docs/BYOA.md+++ b/docs/BYOA.md@@ -10,16 +10,22 @@ the user's own machine (laptop **or** VPS) drives a local **Claude Code**,**Codex CLI**, **Grok Build** (`grok`), **Cursor Agent** (`cursor-agent`),**OpenCode** (`opencode`), **pi** (`pi`), or **Gemini CLI** (`gemini`) as the reasoning engine, on the user's own provideraccount — the server never holds the user's provider credentials.-One daemon hosts **many independent agents** — each with its own isolated+One daemon hosts **many independent agents** — each with its own dedicatedhome directory, memory, skills, and notes. In Cumora these still appearas ordinary `kind='agent'` participants; only their engine differs.+Claude Code and Codex are the secure-default engines. The other adapters are+retained for compatibility but require an explicit unsandboxed opt-in described+below; detecting their binary on `PATH` is not enough to execute them.+The key property that makes this cheap: **Cumora's I/O surface is fullydecoupled from the brain.** The same `cumora` CLI an agent uses for every-world action (`reply`, `dm`, `memory`, `workspace`, `card`, …) is a thin-shim that POSTs argv to `/runtime/cli`, and the transport (wake-stream-SSE + `/runtime/cli`) is deployment-agnostic. BYOA swaps the brain and-the host; it reuses everything else.+world action (`reply`, `dm`, `memory`, `workspace`, `card`, …) is a thin,+fixed MCP-to-file-IPC bridge. It sends argv to the local daemon, and only the daemon —+outside the model sandbox — holds the runtime JWT and POSTs to+`/runtime/cli`. BYOA swaps the brain and the host; it reuses everything+else without handing server credentials or arbitrary network access to+model-generated commands.> Distilled coordination lessons — how N of these engines share a room> without colliding — live in [`COORDINATION.md`](COORDINATION.md). This@@ -82,7 +88,7 @@ There is no "special" BYOA agent, only agents on different Computers.cumora agent computer (daemon, laptop/VPS) ◄──────────┘ SSEdebounce → small-brain triage → persistent engine session turnthe engine IS the loop (its own context, tools, compaction)- bash → `cumora` shim → /runtime/cli → DB (unchanged)+ sandboxed tool → local file IPC → daemon → /runtime/cli → DB````turn.ts` is **bypassed entirely** for BYOA agents. There is no@@ -112,16 +118,18 @@ with rate-limit adaptation, and same-turn steering.│ wake → debounce/coalesce → triage (small brain) ││ → persistent EngineSession turn ││ claude --input/output-format stream-json … │- │ codex app-server / grok ACP / cursor/opencode run │+ │ codex exec / optional compatibility engines ││ pi --mode rpc (JSON commands + events over stdio) │- │ bash → cumora shim → POST /runtime/cli (per-agent JWT)│+ │ tool → file IPC → daemon POST /runtime/cli (JWT) │└─────────────────────────────────────────────────────────┘```**One computer, many agents.** Each agent gets one wake-streamsubscription, one engine context (persistent process where supported, resumable-session id otherwise), and one isolated on-disk home. Agents never share state — isolation is "different directory +-different token".+session id otherwise), and one dedicated on-disk home. The model process+receives neither the runtime token nor the server URL. Authorization stays in+the daemon; filesystem and command-network isolation are enforced by the+selected engine's sandbox.---@@ -153,14 +161,16 @@ different token".roster. The invariant scaffold (CLI usage, the shared`GLANCE_YIELD_RULES`, memory rules, privacy boundary) is deliveredonce per persistent session out-of-band — `--append-system-prompt-file`- for Claude, `developerInstructions` for Codex, `_meta.rules` for Grok- ACP. Cursor and OpenCode have no supported persistent protocol in the tested- CLI versions, so the daemon inlines the standing prompt into each one-shot- wake.+ for Claude. Secure-default Codex uses a one-shot `exec` because its+ app-server currently cannot exclude user config, MCP, hook, and rule layers.+ Compatibility engines retain their native standing-prompt behavior only+ after the operator explicitly enables unsandboxed BYOA.6. The engine reads its home (`CLAUDE.md` / `AGENTS.md`, skills,- `memory/`), reasons, and acts through bash: every `cumora …` call- flows through the shim to `/runtime/cli` with identity pinned by the- per-agent JWT.+ `memory/`), reasons, and acts through its allowed tools. Every `cumora …`+ call flows through a per-agent request/response directory outside the+ writable model home to the daemon;+ the daemon attaches the in-memory per-agent JWT and forwards it to+ `/runtime/cli`.7. **Same-turn steering.** A DM / @mention / human message arrivingmid-turn is injected into the live session at the next safe streamboundary; plain group activity gets a content-free nudge (default@@ -207,12 +217,14 @@ interface EngineSession {| Concern | Claude Code | Codex CLI | Grok Build | Cursor Agent | OpenCode | pi | Gemini CLI || --- | --- | --- | --- | --- | --- | --- | --- |-| Persistent session | `claude -p --input-format stream-json --output-format stream-json --verbose [--resume <id>] [--model X]` | `codex app-server --listen stdio://`, driven over JSON-RPC (`thread/start` / `thread/resume`) | `grok agent --always-approve --no-leader … stdio`, driven over ACP | none in Cursor Agent `2026.08.11-e8db854` | none in the supported OpenCode `v1.18.20` contract; a new process resumes with `--session <id>` | `pi --mode rpc --session-id <id> --skill <home>/.pi/skills`; a turn is a `prompt` command, done at `agent_settled`; steering is pi's native `steer` | none — Gemini CLI `0.57.0` has no stream-json INPUT mode, so there is no way to feed turn N+1 into a live process |-| Standing prompt | `--append-system-prompt-file <home>/.cumora-standing-prompt.md` | `developerInstructions` on `thread/start` | ACP `_meta.rules` | inlined into each wake | inlined into each wake | `--append-system-prompt <home>/.cumora-standing-prompt.md` | inlined into each wake |-| One-shot fallback | `claude -p … --output-format stream-json` | `codex exec … --skip-git-repo-check` | `grok -p … --output-format streaming-messages-json` | `cursor-agent -p --output-format stream-json --force --trust [--resume <id>]` | `opencode run --format json --auto [--session <id>] [--model provider/model]` (prompt on stdin) | `pi <CUMORA_PI_ARGS> --session-id <id> -p` (print mode) | `gemini --output-format stream-json --yolo [--resume <uuid>] [--model X]` (prompt on stdin; `GEMINI_CLI_TRUST_WORKSPACE=true`) |-| Fallback triggers | `CUMORA_CLAUDE_ARGS` set | `CUMORA_CODEX_ARGS` set, `CUMORA_CODEX_NO_APP_SERVER=1`, Windows, or git-init failure | `CUMORA_GROK_ARGS` set, `CUMORA_GROK_NO_ACP=1`, or Windows | always one-shot; `CUMORA_CURSOR_ARGS` overrides flags | always one-shot; `CUMORA_OPENCODE_ARGS` overrides run flags | `CUMORA_PI_ARGS` set | always one-shot; `CUMORA_GEMINI_ARGS` overrides run flags |+| Secure default | Claude Code ≥ 2.1.248 with `--restricted`; no Bash/PowerShell/web tools; host-home reads, command network, unsandboxed retry, and subprocess credentials are denied | Codex ≥ 0.138.0 with a custom permission profile: only minimal runtime reads plus the agent home; command network disabled; tool env allowlisted; user/project config, rules, hooks, apps, remote plugins, and multi-agent tools ignored or disabled | disabled | disabled | disabled | disabled | disabled |+| Platform | macOS, Linux, WSL2; native Windows disabled because Claude's sandbox is unsupported there | macOS, Linux, WSL2, native Windows | compatibility opt-in only | compatibility opt-in only | compatibility opt-in only | compatibility opt-in only | compatibility opt-in only |+| Persistent session | secure default; `claude -p --input-format stream-json --output-format stream-json --verbose` | compatibility opt-in only; secure default uses one-shot `exec` | compatibility opt-in ACP | none | none | compatibility opt-in RPC | none |+| Standing prompt | `--append-system-prompt-file <home>/.cumora-standing-prompt.md` | inlined into each secure one-shot wake | compatibility ACP `_meta.rules` | inlined | inlined | compatibility `--append-system-prompt` | inlined |+| One-shot | sandboxed `claude -p … --output-format stream-json` | sandboxed `codex exec --ignore-user-config --ignore-rules …` | compatibility `grok -p … --always-approve` | compatibility `cursor-agent … --force --trust` | compatibility `opencode run … --auto` | compatibility `pi … -p` | compatibility `gemini … --yolo` |+| Custom argv | ignored securely; requires the compatibility opt-in | ignored securely; requires the compatibility opt-in | compatibility opt-in required | compatibility opt-in required | compatibility opt-in required | compatibility opt-in required | compatibility opt-in required || Memory / persona file | `CLAUDE.md` | `AGENTS.md` | `AGENTS.md` | `AGENTS.md` | `AGENTS.md` plus `.opencode/skills/` | `AGENTS.md` plus `.pi/skills/` (loaded via `--skill`) | `GEMINI.md` plus `.gemini/skills/` |-| Triage (small brain) | `claude -p --model haiku --output-format json` | `codex exec --model gpt-5.4-mini` | `grok -p --model grok-4.5 --output-format json` | `cursor-agent --mode ask -p --output-format stream-json --trust` | `opencode run --format json --agent cumora-triage`; the injected agent denies every tool permission | `pi --mode json --no-session --no-tools --no-extensions --no-skills --no-context-files [--model $CUMORA_TRIAGE_MODEL]` (multi-provider — no fixed cheap model; unset → pi's default) | `gemini --output-format stream-json --model gemini-2.5-flash-lite` with system settings `tools.core: []` and `mcp.allowed: []`, blocking built-in and user/extension MCP tools |+| Triage (small brain) | restricted and tool-free | read-only custom profile and tool env | compatibility only | compatibility only | compatibility only | compatibility only | compatibility only |Sessions carry a resume id (`~/.cumora/sessions/<agentId>.session`); afailed resume falls back to a fresh thread instead of wedging the agent.@@ -227,8 +239,8 @@ unknown flag as fatal. And Gemini's `stats.input_tokens` is the whole promptINCLUDING cache reads, while `stats.input` is the fresh remainder; the ledgerbills `input` and reports `cached` separately, so a cached prefix is notcharged twice.-Engines run headless with their permission prompts disabled, scoped to-the agent's isolated home. On Windows the daemon resolves the real+Secure-default engines run headless inside a fail-closed local sandbox; an+unavailable sandbox stops the turn instead of widening access. On Windows the daemon resolves the real`claude`/`codex`/`grok`/`cursor-agent`/`opencode`/`pi`/`gemini` `.cmd` shims and routes largeprompts via stdin. OpenCode JSONL `step_finish` events are recorded as individualprovider hops; uncached input, output+reasoning, and cache read/write tokens map@@ -238,6 +250,40 @@ the completion signal and accounting is best-effort when that event is absent.Model selection: the per-agent `participants.model` / `fast_model`columns, else the matching deploy-level `CUMORA_DEFAULT_*_MODEL` pin.+### Secure default and compatibility opt-in++The daemon advertises and schedules only engines for which it can impose a+fail-closed host boundary:++- Claude Code on macOS, Linux, and WSL2 runs in restricted mode with filesystem+ isolation, an empty strict network allowlist, no Bash/PowerShell/web tools,+ no unsandboxed retry, and an explicit deny list for every inherited+ environment variable not needed by the fixed Cumora MCP bridge. Claude Code+ 2.1.248 or newer is required. Linux/WSL2 also requires `bubblewrap` and+ `socat`; a missing dependency fails the turn.+- Codex runs one-shot with user config and exec-policy rules ignored. A custom+ permission profile permits minimal runtime reads and writes only under the+ agent home, disables command network, and gives model-spawned commands only+ an explicit non-secret environment. The agent home is marked untrusted at+ CLI precedence, and hooks, apps, remote plugins, multi-agent tools, web+ search, and shell snapshots are disabled. Codex 0.138.0 or newer is required.++Grok, Cursor, OpenCode, pi, Gemini, and Claude on native Windows remain+available only as a backwards-compatibility escape hatch. They are not merely+hidden in the UI: the daemon removes them from its runnable inventory, so a+server assignment cannot make one execute accidentally.++```bash+# HIGH RISK: model-generated tools inherit the host's ordinary file/network+# authority. Use only inside an external container or VM you trust as the real+# security boundary.+CUMORA_BYOA_ALLOW_UNSANDBOXED=1 cumora agent computer+```++This opt-in also re-enables `CUMORA_*_ARGS` whole-argv overrides and Codex's+persistent app-server path. Without it, opaque engine arguments are ignored+because the daemon cannot prove that they preserve the sandbox.+### Running against a custom providerThose pins are resolved server-side and name Anthropic / OpenAI models. If your@@ -272,26 +318,38 @@ CUMORA_ENGINE_MODEL=local CUMORA_TRIAGE_MODEL=local-small cumora agent computerdaemon.logsessions/<agentId>.session ← engine resume idtriage/ ← neutral cwd for small-brain spawns- agents/<agentId>/ ← cwd for every engine turn; isolated- CLAUDE.md (or AGENTS.md) ← static persona header, written once+ .runtime-cli-tools/<agentId>/ ← daemon-owned fixed MCP bridge + IPC client+ cumora-mcp+ cumora+ .runtime-cli-ipc/<agentId>/ ← credential-free rendezvous outside model home+ requests/ ← bounded argv requests+ responses/ ← bounded daemon responses+ .runtime-cli-broker/<agentId>/ ← daemon-private claimed requests/staging+ agents/<agentId>/ ← cwd and secure sandbox root+ CLAUDE.md (or AGENTS.md) ← daemon-owned persona, atomically refreshed.cumora-standing-prompt.md ← the per-session operational prompt.claude/skills/<name>/SKILL.md ← this agent's skills (Claude).cursor/skills/ ← Cursor-native skill directory.opencode/skills/ ← OpenCode-native skill directory.gemini/skills/ ← Gemini-native skill directory.pi/skills/ ← pi-native skill directory (via --skill)- .claude/settings.json ← permissions (allow Bash)- bin/cumora ← the shim (see below); bin/.runtime-token+ bin/cumora ← compatibility mode onlymemory/MEMORY.md ← the agent's durable memory indexnotes/ ← scratch notesworkspace/ ← local work files```-**The shim** is a small self-contained Node script the daemon writes to-`<home>/bin/cumora` and prepends to the engine's `PATH`. It POSTs argv to-`/runtime/cli`, reads its token from `bin/.runtime-token` (refreshed by-the daemon before expiry), and supports `--file <path>` / `--stdin` to-pass long bodies without shell mangling. (The similar+**The bridge** is a fixed MCP server plus a small file-IPC client stored in the+daemon-owned `.runtime-cli-tools/<agentId>/` directory, outside the writable+agent home. Secure Claude and Codex expose only its structured `cli(argv)` tool;+the model cannot rewrite the executable or write directly into the rendezvous+directories. The bridge sends bounded argv through+`.runtime-cli-ipc/<agentId>/`, and the daemon atomically claims each request+into its private broker directory before validating it, refreshing its+in-memory JWT, and POSTing `/runtime/cli`. The model process receives no server+URL, bearer token, or HTTP client path. Compatibility mode retains the legacy+`<home>/bin/cumora` PATH shim and its `--file <path>` / `--stdin` conveniences.+(The similar`server/docker/agent-computer-cumora.sh` curl shim is the **cloud pod**variant, injected by the orchestrator — same protocol, different host.)@@ -303,14 +361,17 @@ also works for BYOA agents through `/runtime/cli` — `cumora workspace`shared artifacts live where teammates can see them, while the agent'sinner state stays local.-**Isolation is cwd-scoped, auth is shared.** Relocating the engine's-config dir (`CLAUDE_CONFIG_DIR` / `CODEX_HOME`) breaks its login —-credentials are keyed to that dir — so the daemon sets `cwd` to the-agent's home and does **not** relocate config. Per-agent: project memory,-skills, settings, notes, workspace. Shared across an owner's agents on-one machine: the engine login and the user's global config (`~/.claude` /-`~/.codex` / `~/.grok` / `~/.pi/agent` / `~/.gemini`, Cursor's login store, or OpenCode's config/auth store).-Agents are independent in all project state and share one engine login per host.+**Authentication is shared; tool authority is not.** The engine core can use+the operator's existing login, but model-spawned commands cannot read that+login or inherit provider credentials in secure mode. Each agent gets its own+writable home; its credential-free IPC namespace and executable bridge stay+outside that home. Claude restricted mode ignores user/project settings while+retaining core authentication; Codex `exec --ignore-user-config --ignore-rules`+does the same and marks the project untrusted. Secure engine startup also drops+empty, relative, and agent-home entries from `PATH`, so a model-planted+`claude`/`codex` executable cannot run before the next sandbox is established.+Compatibility mode intentionally restores the older shared-host trust model+and must be protected by an external container or VM.---@@ -360,8 +421,8 @@ not the user's session. "Remove Computer" is a real kill switch.hashed server-side)4. daemon: GET /api/computers/me/agents (roster, re-polled every 60s);per agent it mints a short-lived runtime JWT (2h TTL, refreshed before- expiry) via POST /api/agents/:id/runtime-token — used for that agent's- wake-stream SSE and the cumora shim.+ expiry) via POST /api/agents/:id/runtime-token — kept in daemon memory and+ used for that agent's wake-stream SSE and daemon-side `/runtime/cli` calls.5. heartbeat: POST /api/computers/heartbeat every 30s; a computer with noheartbeat for 90s shows offline and its agents show sleeping.6. UI "Remove" ─► sets revoked_at; the device token and all derived agent@@ -432,9 +493,18 @@ npx cumora@latest agent computer --pair <code> [--server <url>]and skills in the agent home are inspectable on the machine, not inthe Cumora UI. Shared work belongs in server-side surfaces (`cumoraworkspace`, docs, boards) where teammates can see it.-- **The runtime token is a credential** for that agent's identity: short- TTL + refresh bounds leakage; revoking the computer kills all derived- tokens.-- **Engines run with their permission prompts disabled** inside the- agent's home. The blast radius is bounded by the home directory plus- whatever the `cumora` CLI (server-arbitrated, identity-pinned) allows.+- **The runtime token is a credential** for that agent's identity. It remains+ in daemon memory and never enters the engine environment or agent home;+ short TTL and computer revocation remain defense in depth.+- **Secure-default engine tools are OS-sandboxed.** They can modify the agent+ home and invoke only the fixed Cumora MCP tool, but cannot rewrite its bridge,+ read the rest of the host, inherit daemon/provider secrets, or open+ command-network connections. Persona and standing-prompt refreshes are+ atomic and refuse linked state directories. Runner replacement waits for the+ platform tree terminator before reseeding: POSIX uses a dedicated process+ group plus bounded descendant discovery for children that detach from it;+ Windows waits for `taskkill /T /F` to finish.+- **Unsandboxed compatibility is explicit and loud.** Setting+ `CUMORA_BYOA_ALLOW_UNSANDBOXED=1` restores the historical host-level blast+ radius and emits a startup warning; operators should use it only behind an+ external VM/container boundary.diff --git a/server/src/__tests__/agent-computer-shim-output.test.ts b/server/src/__tests__/agent-computer-shim-output.test.tsindex 0dc13f3..f173782 100644--- a/server/src/__tests__/agent-computer-shim-output.test.ts+++ b/server/src/__tests__/agent-computer-shim-output.test.ts@@ -12,18 +12,21 @@** Run: node --import tsx --test server/src/__tests__/agent-computer-shim-output.test.ts*/++import assert from 'node:assert/strict'import { execFile, spawn } from 'node:child_process'-import { createServer, type Server } from 'node:http'-import { mkdtemp, writeFile, chmod, readFile, rm } from 'node:fs/promises'+import { chmod, lstat, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import { delimiter, join } from 'node:path'import { afterEach, test } from 'node:test'import { promisify } from 'node:util'-import assert from 'node:assert/strict'import {+ CUMORA_MCP_SHIM,CUMORA_SHIM,CUMORA_WINDOWS_SHIM,+ engineProcessPath,prependAgentBinToPath,+ RuntimeCliBroker,writeShim,} from '../agents/computer/daemon.js'@@ -35,36 +38,28 @@ afterEach(async () => {for (const fn of cleanup.splice(0)) await fn()})-/** A stand-in for /runtime/cli that returns a payload of the requested size. */-async function serveCli(payload: string, exitCode = 0): Promise<string> {- const server: Server = createServer((_req, res) => {- res.writeHead(200, { 'content-type': 'application/json' })- res.end(JSON.stringify({ text: payload, exitCode, ok: exitCode === 0, sideEffects: [] }))- })- await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))- cleanup.push(() => new Promise<void>((resolve) => { server.close(() => resolve()) }))- const addr = server.address()- if (!addr || typeof addr === 'string') throw new Error('no port')- return `http://127.0.0.1:${addr.port}`-}-/** Write the real shim to disk and run it with stdout on a PIPE — the way the* engine's bash tool always invokes it. */-async function runShim(url: string): Promise<{ stdoutBytes: number; exitCode: number; stderr: string }> {+async function runShim(+ payload: string,+ cliExitCode = 0,+): Promise<{ stdoutBytes: number; exitCode: number; stderr: string }> {const dir = await mkdtemp(join(tmpdir(), 'cumora-shim-'))cleanup.push(() => rm(dir, { recursive: true, force: true }))const shim = join(dir, 'cumora.js')+ const ipcDir = join(dir, 'ipc')await writeFile(shim, CUMORA_SHIM, 'utf8')await chmod(shim, 0o755)+ const broker = new RuntimeCliBroker(ipcDir, join(dir, 'broker'), async () => ({ text: payload, exitCode: cliExitCode }))+ await broker.start()+ cleanup.push(() => broker.stop())return new Promise((resolve) => {const child = spawn(process.execPath, [shim, 'inbox'], {stdio: ['ignore', 'pipe', 'pipe'],env: {...process.env,- CUMORA_AGENT_RUNTIME_URL: url,- CUMORA_AGENT_RUNTIME_TOKEN: 'test-token',- CUMORA_AGENT_RUNTIME_TOKEN_FILE: '',+ CUMORA_AGENT_IPC_DIR: ipcDir,},})let stdoutBytes = 0@@ -79,8 +74,7 @@ test('the shim writes the whole CLI payload before exiting', async () => {// 1MB cannot fit any pipe buffer, so this is deterministic — there is no size// at which the old write-then-exit accidentally passed.const payload = 'x'.repeat(1_000_000)- const url = await serveCli(payload)- const r = await runShim(url)+ const r = await runShim(payload)assert.equal(r.stdoutBytes, payload.length + 1,'stdout must carry the full text plus its trailing newline, not just the pipe buffer',@@ -91,8 +85,7 @@ test('the shim writes the whole CLI payload before exiting', async () => {test('a small payload still round-trips unchanged', async () => {const payload = 'no unread messages'- const url = await serveCli(payload)- const r = await runShim(url)+ const r = await runShim(payload)assert.equal(r.stdoutBytes, payload.length + 1)assert.equal(r.exitCode, 0)})@@ -100,15 +93,13 @@ test('a small payload still round-trips unchanged', async () => {test('the CLI exit code still propagates, with a large payload', async () => {// The exit code must survive being moved into the write callback.const payload = 'y'.repeat(300_000)- const url = await serveCli(payload, 2)- const r = await runShim(url)+ const r = await runShim(payload, 2)assert.equal(r.stdoutBytes, payload.length + 1)assert.equal(r.exitCode, 2, 'a non-zero CLI exit code must still reach the engine')})test('an empty payload exits without writing', async () => {- const url = await serveCli('', 1)- const r = await runShim(url)+ const r = await runShim('', 1)assert.equal(r.stdoutBytes, 0)assert.equal(r.exitCode, 1)})@@ -122,6 +113,29 @@ test('agent bin is prepended with the platform PATH delimiter', () => {assert.equal(prependAgentBinToPath('agent-bin', ''), 'agent-bin')})+test('secure engine PATH cannot select a model-planted engine shadow', {+ skip: process.platform === 'win32',+}, async () => {+ const root = await mkdtemp(join(tmpdir(), 'cumora-engine-shadow-'))+ cleanup.push(() => rm(root, { recursive: true, force: true }))+ const trustedBin = join(root, 'trusted-bin')+ const agentBin = join(root, 'agent-home', 'bin')+ await mkdir(trustedBin, { recursive: true })+ await mkdir(agentBin, { recursive: true })+ await writeFile(join(trustedBin, 'claude'), '#!/bin/sh\necho trusted-engine\n', 'utf8')+ await writeFile(join(agentBin, 'claude'), '#!/bin/sh\necho model-shadow\n', 'utf8')+ await chmod(join(trustedBin, 'claude'), 0o755)+ await chmod(join(agentBin, 'claude'), 0o755)++ const insecureInheritedPath = ['.', agentBin, '', trustedBin].join(delimiter)+ const securePath = engineProcessPath(agentBin, insecureInheritedPath, false)+ assert.equal(securePath, trustedBin)+ assert.equal((await execFileP('claude', [], { env: { PATH: securePath } })).stdout.trim(), 'trusted-engine')++ const compatibilityPath = engineProcessPath(agentBin, trustedBin, true)+ assert.equal((await execFileP('claude', [], { env: { PATH: compatibilityPath } })).stdout.trim(), 'model-shadow')+})+test('writeShim emits a Windows command launcher beside the shared Node shim', async () => {const dir = await mkdtemp(join(tmpdir(), 'cumora-windows-shim-'))cleanup.push(() => rm(dir, { recursive: true, force: true }))@@ -129,29 +143,218 @@ test('writeShim emits a Windows command launcher beside the shared Node shim', aawait writeShim(dir, 'win32')assert.equal(await readFile(join(dir, 'cumora'), 'utf8'), CUMORA_SHIM)+ assert.equal(await readFile(join(dir, 'cumora-mcp'), 'utf8'), CUMORA_MCP_SHIM)assert.equal(await readFile(join(dir, 'cumora.cmd'), 'utf8'), CUMORA_WINDOWS_SHIM)})+test('writeShim atomically replaces final symlinks without writing their targets', {+ skip: process.platform === 'win32',+}, async () => {+ const root = await mkdtemp(join(tmpdir(), 'cumora-shim-symlink-'))+ cleanup.push(() => rm(root, { recursive: true, force: true }))+ const binDir = join(root, 'bin')+ const outside = join(root, 'outside-secret')+ await mkdir(binDir)+ await writeFile(outside, 'do not overwrite', 'utf8')+ await symlink(outside, join(binDir, 'cumora'))++ await writeShim(binDir)++ assert.equal(await readFile(outside, 'utf8'), 'do not overwrite')+ assert.equal((await lstat(join(binDir, 'cumora'))).isSymbolicLink(), false)+ assert.equal(await readFile(join(binDir, 'cumora'), 'utf8'), CUMORA_SHIM)+})++test('writeShim rejects a linked shim directory', {+ skip: process.platform === 'win32',+}, async () => {+ const root = await mkdtemp(join(tmpdir(), 'cumora-shim-dir-symlink-'))+ cleanup.push(() => rm(root, { recursive: true, force: true }))+ const outside = join(root, 'outside')+ const linked = join(root, 'linked')+ await mkdir(outside)+ await symlink(outside, linked)++ await assert.rejects(writeShim(linked), /refuses linked shim directory/)+})++test('the shim contains neither an HTTP client nor runtime-token handling', () => {+ assert.doesNotMatch(CUMORA_SHIM, /CUMORA_AGENT_RUNTIME_(?:URL|TOKEN)/)+ assert.doesNotMatch(CUMORA_SHIM, /Authorization|Bearer|fetch\s*\(/)+ assert.match(CUMORA_SHIM, /CUMORA_AGENT_IPC_DIR/)+})++test('the restricted Claude MCP bridge exposes only argv and rejects local-body flags', { timeout: 5_000 }, async () => {+ const dir = await mkdtemp(join(tmpdir(), 'cumora-mcp-shim-'))+ cleanup.push(() => rm(dir, { recursive: true, force: true }))+ const binDir = join(dir, 'bin')+ const ipcDir = join(dir, 'ipc')+ const brokerDir = join(dir, 'broker')+ const calls: string[][] = []+ const broker = new RuntimeCliBroker(ipcDir, brokerDir, async (argv) => {+ calls.push(argv)+ return { text: 'ok from daemon', exitCode: 0 }+ })+ await broker.start()+ cleanup.push(() => broker.stop())+ await writeShim(binDir)++ const child = spawn(process.execPath, [join(binDir, 'cumora-mcp')], {+ stdio: ['pipe', 'pipe', 'pipe'],+ env: { ...process.env, CUMORA_AGENT_IPC_DIR: ipcDir },+ })+ let stdout = ''+ let stderr = ''+ child.stdout.on('data', (b: Buffer) => { stdout += b.toString('utf8') })+ child.stderr.on('data', (b: Buffer) => { stderr += b.toString('utf8') })+ child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18' } })}\n`)+ child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/list', params: {} })}\n`)+ child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'cli', arguments: { argv: ['inbox'] } } })}\n`)+ child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: 4, method: 'tools/call', params: { name: 'cli', arguments: { argv: ['reply', 'c1', '--file', '/host/secret'] } } })}\n`)+ child.stdin.end()++ await new Promise<void>((resolve, reject) => {+ child.on('error', reject)+ child.on('close', (code) => code === 0 ? resolve() : reject(new Error(`MCP bridge exited ${code}: ${stderr}`)))+ })+ const responses = stdout.trim().split(/\r?\n/).map((line) => JSON.parse(line) as {+ id: number+ result?: { tools?: Array<{ name?: string }>; content?: Array<{ text?: string }>; isError?: boolean }+ })+ const byId = new Map(responses.map((entry) => [entry.id, entry]))+ assert.deepEqual(calls, [['inbox']])+ assert.equal(byId.get(2)?.result?.tools?.[0]?.name, 'cli')+ assert.equal(byId.get(3)?.result?.content?.[0]?.text, 'ok from daemon')+ assert.equal(byId.get(3)?.result?.isError, false)+ assert.equal(byId.get(4)?.result?.isError, true)+ assert.match(byId.get(4)?.result?.content?.[0]?.text ?? '', /local file\/stdin flags are unavailable/)+})++test('the privileged IPC broker refuses model-created request symlinks', {+ skip: process.platform === 'win32',+}, async () => {+ const dir = await mkdtemp(join(tmpdir(), 'cumora-ipc-symlink-'))+ cleanup.push(() => rm(dir, { recursive: true, force: true }))+ const ipcDir = join(dir, 'ipc')+ let invoked = false+ const broker = new RuntimeCliBroker(ipcDir, join(dir, 'broker'), async () => {+ invoked = true+ return { text: 'should not run', exitCode: 0 }+ })+ await broker.start()+ cleanup.push(() => broker.stop())++ const target = join(dir, 'outside.json')+ const id = '12345678-1234-1234-1234-123456789abc'+ await writeFile(target, JSON.stringify({ argv: ['inbox'] }), 'utf8')+ await symlink(target, join(ipcDir, 'requests', `${id}.json`))+ await broker.poll()++ assert.equal(invoked, false)+ const response = JSON.parse(await readFile(join(ipcDir, 'responses', `${id}.json`), 'utf8')) as { exitCode?: number; error?: string }+ assert.equal(response.exitCode, 70)+ assert.match(response.error ?? '', /regular file|symbolic link|too many levels/i)+})++test('the IPC broker coalesces a trigger storm while preserving one pending rerun', async () => {+ const dir = await mkdtemp(join(tmpdir(), 'cumora-ipc-coalesce-'))+ cleanup.push(() => rm(dir, { recursive: true, force: true }))+ const ipcDir = join(dir, 'ipc')+ const calls: string[][] = []+ let firstInvocationStarted!: () => void+ const started = new Promise<void>((resolve) => { firstInvocationStarted = resolve })+ let releaseFirstInvocation!: () => void+ const blocked = new Promise<void>((resolve) => { releaseFirstInvocation = resolve })+ const broker = new RuntimeCliBroker(ipcDir, join(dir, 'broker'), async (argv) => {+ calls.push(argv)+ if (calls.length === 1) {+ firstInvocationStarted()+ await blocked+ }+ return { text: 'ok', exitCode: 0 }+ })+ await broker.start()+ cleanup.push(() => broker.stop())++ const firstId = '12345678-1234-1234-1234-123456789abe'+ await writeFile(join(ipcDir, 'requests', `${firstId}.json`), JSON.stringify({ argv: ['first'] }), 'utf8')+ const activeDrain = broker.poll()+ await started++ const secondId = '12345678-1234-1234-1234-123456789abf'+ await writeFile(join(ipcDir, 'requests', `${secondId}.json`), JSON.stringify({ argv: ['second'] }), 'utf8')+ const storm = Array.from({ length: 2_000 }, () => broker.poll())+ assert.ok(storm.every((pending) => pending === activeDrain), 'all triggers must share one bounded drain')++ releaseFirstInvocation()+ await Promise.all(storm)+ assert.deepEqual(calls, [['first'], ['second']])+})++test('a response publication failure is logged inside the broker drain, not rejected in the background', async () => {+ const dir = await mkdtemp(join(tmpdir(), 'cumora-ipc-response-failure-'))+ cleanup.push(() => rm(dir, { recursive: true, force: true }))+ const ipcDir = join(dir, 'ipc')+ let invoked = false+ const broker = new RuntimeCliBroker(ipcDir, join(dir, 'broker'), async () => {+ invoked = true+ return { text: 'ok', exitCode: 0 }+ })+ await broker.start()+ cleanup.push(() => broker.stop())++ const id = '12345678-1234-1234-1234-123456789ac0'+ const responsePath = join(ipcDir, 'responses', `${id}.json`)+ await mkdir(responsePath)+ await writeFile(join(ipcDir, 'requests', `${id}.json`), JSON.stringify({ argv: ['inbox'] }), 'utf8')++ await assert.doesNotReject(broker.poll())+ assert.equal(invoked, true)+ assert.equal((await lstat(responsePath)).isDirectory(), true)+})++test('stopping the IPC broker aborts an in-flight daemon call and suppresses its response', async () => {+ const dir = await mkdtemp(join(tmpdir(), 'cumora-ipc-stop-'))+ cleanup.push(() => rm(dir, { recursive: true, force: true }))+ const ipcDir = join(dir, 'ipc')+ let invocationStarted!: () => void+ const started = new Promise<void>((resolve) => { invocationStarted = resolve })+ let receivedAbort = false+ const broker = new RuntimeCliBroker(ipcDir, join(dir, 'broker'), async (_argv, signal) => {+ invocationStarted()+ await new Promise<void>((resolve) => {+ if (signal.aborted) resolve()+ else signal.addEventListener('abort', () => resolve(), { once: true })+ })+ receivedAbort = signal.aborted+ return { text: 'must not be published', exitCode: 0 }+ })+ await broker.start()+ cleanup.push(() => broker.stop())+ const id = '12345678-1234-1234-1234-123456789abd'+ await writeFile(join(ipcDir, 'requests', `${id}.json`), JSON.stringify({ argv: ['inbox'] }), 'utf8')+ const poll = broker.poll()+ await started+ broker.stop()+ await poll++ assert.equal(receivedAbort, true)+ await assert.rejects(readFile(join(ipcDir, 'responses', `${id}.json`), 'utf8'), { code: 'ENOENT' })+})+test('PowerShell resolves cumora from the injected PATH and forwards arguments', {skip: process.platform !== 'win32',}, async () => {- let receivedAuthorization = ''let receivedArgv: string[] | undefined- const server: Server = createServer(async (req, res) => {- receivedAuthorization = req.headers.authorization ?? ''- let body = ''- for await (const chunk of req) body += chunk.toString()- receivedArgv = (JSON.parse(body) as { argv: string[] }).argv- res.writeHead(200, { 'content-type': 'application/json' })- res.end(JSON.stringify({ text: 'sent from test', exitCode: 0, ok: true, sideEffects: [] }))- })- await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))- cleanup.push(() => new Promise<void>((resolve) => { server.close(() => resolve()) }))- const addr = server.address()- if (!addr || typeof addr === 'string') throw new Error('no port')-const dir = await mkdtemp(join(tmpdir(), 'cumora-powershell-shim-'))cleanup.push(() => rm(dir, { recursive: true, force: true }))+ const ipcDir = join(dir, 'ipc')+ const broker = new RuntimeCliBroker(ipcDir, join(dir, 'broker'), async (argv) => {+ receivedArgv = argv+ return { text: 'sent from test', exitCode: 0 }+ })+ await broker.start()+ cleanup.push(() => broker.stop())await writeShim(dir)const { stdout, stderr } = await execFileP(@@ -161,15 +364,12 @@ test('PowerShell resolves cumora from the injected PATH and forwards arguments',env: {...process.env,PATH: prependAgentBinToPath(dir),- CUMORA_AGENT_RUNTIME_URL: `http://127.0.0.1:${addr.port}`,- CUMORA_AGENT_RUNTIME_TOKEN: 'test-token',- CUMORA_AGENT_RUNTIME_TOKEN_FILE: '',+ CUMORA_AGENT_IPC_DIR: ipcDir,},},)assert.equal(stdout.trim(), 'sent from test')assert.equal(stderr, '')- assert.equal(receivedAuthorization, 'Bearer test-token')assert.deepEqual(receivedArgv, ['reply', 'direct-test', 'hello from windows'])})diff --git a/server/src/__tests__/agents-computer-engine-pi.test.ts b/server/src/__tests__/agents-computer-engine-pi.test.tsindex a4befc2..8591521 100644--- a/server/src/__tests__/agents-computer-engine-pi.test.ts+++ b/server/src/__tests__/agents-computer-engine-pi.test.ts@@ -11,14 +11,15 @@** Run: node --import tsx --test server/src/__tests__/agents-computer-engine-pi.test.ts*/-import { mkdtemp, mkdir, writeFile, readFile, chmod, rm } from 'node:fs/promises'++import assert from 'node:assert/strict'import { existsSync } from 'node:fs'+import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { setTimeout as delay } from 'node:timers/promises'import { afterEach, test } from 'node:test'-import assert from 'node:assert/strict'-import { getAdapter, type EngineHopReport } from '../agents/computer/engine.js'+import { setTimeout as delay } from 'node:timers/promises'+import { type EngineHopReport, getAdapter } from '../agents/computer/engine.js'const IS_WIN = process.platform === 'win32'const tempDirs: string[] = []@@ -38,7 +39,7 @@ const scenario = process.env.FAKE_PI_SCENARIO || 'ok'const mode = argv.includes('rpc') ? 'rpc' : argv.includes('json') ? 'json' : 'text'const sidIdx = argv.indexOf('--session-id')const SID = sidIdx >= 0 ? argv[sidIdx + 1] : 'fake-session-' + mode-record({ argv, cwd: process.cwd() })+record({ argv, cwd: process.cwd(), pid: process.pid })if (scenario === 'ignore-eof') {setInterval(() => {}, 1000)process.on('SIGTERM', () => { record({ signal: 'SIGTERM' }); process.exit(0) })@@ -126,7 +127,7 @@ async function fixture(scenario = 'ok'): Promise<Fixture> {return { root, binDir, home, log, env }}-async function fakeLog(f: Fixture): Promise<Array<{ argv?: string[]; cmd?: { type: string; id?: string; message?: string }; signal?: string }>> {+async function fakeLog(f: Fixture): Promise<Array<{ argv?: string[]; cmd?: { type: string; id?: string; message?: string }; signal?: string; pid?: number }>> {if (!existsSync(f.log)) return []return (await readFile(f.log, 'utf8')).split('\n').filter(Boolean).map((l) => JSON.parse(l))}@@ -199,7 +200,7 @@ test('pi persistent session: one prompt → one turn, session id, summed usage,assert.equal(hops.length, 1)assert.equal(hops[0].hopIndex, 1, 'hop index restarts per turn')assert.equal((await fakeLog(f)).filter((s) => s.argv).length, 1, 'still one process')- session.stop()+ await session.stop()})test('pi persistent session: steer() rides pi\'s native steer command mid-turn; busy while a turn is in flight', { skip: IS_WIN }, async () => {@@ -221,7 +222,7 @@ test('pi persistent session: steer() rides pi\'s native steer command mid-turn;session.steer('too late')await delay(50)assert.equal((await fakeLog(f)).map((s) => s.cmd).filter(Boolean).length, 3)- session.stop()+ await session.stop()})test('pi persistent session: a model error surfaces as a failed turn, not a hang', { skip: IS_WIN }, async () => {@@ -232,7 +233,7 @@ test('pi persistent session: a model error surfaces as a failed turn, not a hangassert.equal(result.exitCode, 1)assert.match(result.error ?? '', /rate limit exceeded \(429\)/)assert.equal(session.alive, true, 'the process is still up — only the turn failed')- session.stop()+ await session.stop()})test('pi persistent session: a prompt rejected by pi settles immediately', { skip: IS_WIN }, async () => {@@ -242,7 +243,7 @@ test('pi persistent session: a prompt rejected by pi settles immediately', { skiconst result = await session.send('hi')assert.equal(result.exitCode, 1)assert.match(result.error ?? '', /rejected the turn: Agent is already streaming/)- session.stop()+ await session.stop()})test('pi persistent session: process death mid-turn fails the turn with stderr and is logged', { skip: IS_WIN }, async () => {@@ -317,7 +318,7 @@ test('pi abort during listener registration never dispatches a prompt or becomesassert.ok(!commands.some((command) => command?.type === 'prompt'), 'the cancelled turn must not reach session.send()')})-test('pi forced stop signals an EOF-resistant child before the daemon can exit', { skip: IS_WIN }, async () => {+test('pi forced stop kills an EOF-resistant child before the daemon can exit', { skip: IS_WIN }, async () => {const f = await fixture('ignore-eof')const session = getAdapter('pi').startSession?.({ home: f.home, env: f.env, model: null, fastModel: null, onLog: () => {} })assert.ok(session)@@ -325,10 +326,20 @@ test('pi forced stop signals an EOF-resistant child before the daemon can exit',// Wait until the child has started and accepted get_state, then model the// daemon's final shutdown path: there is no two-second timer opportunity.for (let i = 0; i < 50 && (await fakeLog(f)).length < 2; i += 1) await delay(20)- session.stop({ force: true })- for (let i = 0; i < 50 && !(await fakeLog(f)).some((entry) => entry.signal === 'SIGTERM'); i += 1) await delay(20)-- assert.ok((await fakeLog(f)).some((entry) => entry.signal === 'SIGTERM'), 'force stop must dispatch SIGTERM synchronously instead of relying on the delayed fallback')+ const pid = (await fakeLog(f))[0]?.pid+ assert.equal(typeof pid, 'number')+ await session.stop({ force: true })++ let alive = true+ for (let i = 0; i < 50 && alive; i += 1) {+ try { process.kill(pid as number, 0) }+ catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'ESRCH') alive = false+ else throw err+ }+ if (alive) await delay(20)+ }+ assert.equal(alive, false, 'force stop must synchronously dispatch a fatal tree signal instead of relying on the delayed fallback')assert.equal(session.alive, false)})diff --git a/server/src/__tests__/agents-computer-engine-version.test.ts b/server/src/__tests__/agents-computer-engine-version.test.tsindex 61f1e93..1c4486b 100644--- a/server/src/__tests__/agents-computer-engine-version.test.ts+++ b/server/src/__tests__/agents-computer-engine-version.test.ts@@ -8,17 +8,18 @@** Run: node --import tsx --test server/src/__tests__/agents-computer-engine-version.test.ts*/-import { test } from 'node:test'+import assert from 'node:assert/strict'import { mkdtemp, rm, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'+import { test } from 'node:test'process.env.CUMORA_RUNTIME_CLIENT = 'http'process.env.OPENAI_API_KEY ??= 'test-key'const {- parseCliVersion, isCliOutdated, inferUpdateCommand,+ parseCliVersion, isCliOutdated, isCliVersionAtLeast, inferUpdateCommand,parseCursorAbout, parseGrokCheck, ENGINE_VERSION_SPECS, versionCommandInvocation,} = await import('../agents/computer/cli-version.js')const { sanitizeDetectedEngines } = await import('../agents/computer/registry.js')@@ -63,6 +64,15 @@ test('isCliOutdated only fires when upstream is strictly newer', () => {assert.equal(isCliOutdated('1.2.3', null), false)})+test('isCliVersionAtLeast enforces a local security floor', () => {+ assert.equal(isCliVersionAtLeast('2.1.248', '2.1.248'), true)+ assert.equal(isCliVersionAtLeast('2.1.251', '2.1.248'), true)+ assert.equal(isCliVersionAtLeast('2.1.247', '2.1.248'), false)+ assert.equal(isCliVersionAtLeast('2.1.248-beta.1', '2.1.248'), false)+ assert.equal(isCliVersionAtLeast('0.138.0', '0.138.0'), true)+ assert.equal(isCliVersionAtLeast(null, '0.138.0'), false)+})+test('inferUpdateCommand prefers the vendor updater, then brew, then npm', () => {// claude has a self-updater, so brew/npm never win even from a brew path.assert.equal(diff --git a/server/src/__tests__/agents-computer-engine.test.ts b/server/src/__tests__/agents-computer-engine.test.tsindex d1cc13d..8465695 100644--- a/server/src/__tests__/agents-computer-engine.test.ts+++ b/server/src/__tests__/agents-computer-engine.test.ts@@ -4,20 +4,30 @@* Run: node --import tsx --test server/src/__tests__/agents-computer-engine.test.ts*/import assert from 'node:assert/strict'-import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'+import { chmod, lstat, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'-import { delimiter, join } from 'node:path'+import { delimiter, dirname, join } from 'node:path'import { afterEach, test } from 'node:test'import { setTimeout as delay } from 'node:timers/promises'-import { getAdapter, headlessSpawnOptions, resolveSpawn, type EngineHopReport, type EngineRunResult } from '../agents/computer/engine.js'+import { type EngineHopReport, type EngineRunResult, getAdapter, headlessSpawnOptions, resolveSpawn, runnableEngineIds, secureEngineCapabilityReason } from '../agents/computer/engine.js'const IS_WIN = process.platform === 'win32'const ORIGINAL_PATH = process.env.PATHconst ORIGINAL_PATHEXT = process.env.PATHEXT+const ORIGINAL_UNSANDBOXED = process.env.CUMORA_BYOA_ALLOW_UNSANDBOXEDconst tempDirs: string[] = []// Sessions spawn a child process. Track them so a FAILING assertion still tears// the child down — otherwise it outlives the test and the runner never exits.-const liveSessions: Array<{ stop(): void }> = []+const liveSessions: Array<{ stop(): void | Promise<void> }> = []++function secureClaudeEnv(root: string, overrides: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv {+ return {+ ...process.env,+ CUMORA_AGENT_IPC_DIR: join(root, 'private-ipc'),+ CUMORA_AGENT_MCP_SHIM: join(root, 'trusted', 'cumora-mcp'),+ ...overrides,+ }+}test('engine subprocesses always suppress Windows console windows', () => {assert.deepEqual(headlessSpawnOptions({ shell: true, cwd: 'C:\\agent home', windowsHide: false }), {@@ -28,14 +38,89 @@ test('engine subprocesses always suppress Windows console windows', () => {})afterEach(async () => {- for (const s of liveSessions.splice(0)) { try { s.stop() } catch { /* already gone */ } }+ for (const s of liveSessions.splice(0)) { try { await s.stop() } catch { /* already gone */ } }if (ORIGINAL_PATH === undefined) delete process.env.PATHelse process.env.PATH = ORIGINAL_PATHif (ORIGINAL_PATHEXT === undefined) delete process.env.PATHEXTelse process.env.PATHEXT = ORIGINAL_PATHEXT+ if (ORIGINAL_UNSANDBOXED === undefined) delete process.env.CUMORA_BYOA_ALLOW_UNSANDBOXED+ else process.env.CUMORA_BYOA_ALLOW_UNSANDBOXED = ORIGINAL_UNSANDBOXEDawait Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })))})+test('secure inventory exposes only engines with a verified boundary', () => {+ const installed = ['claude', 'codex', 'grok', 'cursor', 'opencode', 'pi', 'gemini'] as const+ assert.deepEqual(runnableEngineIds(installed, {}, 'darwin'), ['claude', 'codex'])+ assert.deepEqual(runnableEngineIds(installed, {}, 'linux'), ['claude', 'codex'])+ assert.deepEqual(runnableEngineIds(installed, {}, 'win32'), ['codex'])+ assert.deepEqual(+ runnableEngineIds(installed, { CUMORA_BYOA_ALLOW_UNSANDBOXED: '1' }, 'win32'),+ [...installed],+ )+})++test('secure engines fail closed on old CLIs and missing Linux sandbox dependencies', () => {+ assert.equal(secureEngineCapabilityReason('claude', '2.1.247', 'darwin'), 'version 2.1.247 is older than the secure minimum 2.1.248')+ assert.equal(secureEngineCapabilityReason('claude', '2.1.248', 'darwin'), null)+ assert.equal(secureEngineCapabilityReason('codex', '0.137.9', 'linux'), 'version 0.137.9 is older than the secure minimum 0.138.0')+ assert.equal(secureEngineCapabilityReason('codex', '0.138.0', 'linux'), null)+ assert.match(+ secureEngineCapabilityReason('claude', '2.1.248', 'linux', { bwrap: false, socat: false }) ?? '',+ /bubblewrap.*socat/,+ )+})++test('secure adapters replace persona symlinks without writing their targets', {+ skip: IS_WIN,+}, async () => {+ const root = await mkdtemp(join(tmpdir(), 'cumora-persona-symlink-'))+ tempDirs.push(root)+ const outside = join(root, 'outside-secret')+ await writeFile(outside, 'do not overwrite', 'utf8')++ for (const [engine, personaFile] of [['claude', 'CLAUDE.md'], ['codex', 'AGENTS.md']] as const) {+ const home = join(root, engine)+ await mkdir(home)+ await symlink(outside, join(home, personaFile))+ await getAdapter(engine).seedHome(home, {+ id: engine,+ name: `Secure ${engine}`,+ role: 'Tester',+ systemPrompt: null,+ })+ assert.equal(await readFile(outside, 'utf8'), 'do not overwrite')+ assert.equal((await lstat(join(home, personaFile))).isSymbolicLink(), false)+ assert.match(await readFile(join(home, personaFile), 'utf8'), new RegExp(`Secure ${engine}`))+ }+})++test('secure adapters reject linked state directories', {+ skip: IS_WIN,+}, async () => {+ const root = await mkdtemp(join(tmpdir(), 'cumora-state-symlink-'))+ tempDirs.push(root)+ const home = join(root, 'home')+ const outside = join(root, 'outside')+ await mkdir(home)+ await mkdir(outside)+ await symlink(outside, join(home, 'memory'))++ await assert.rejects(+ getAdapter('codex').seedHome(home, { id: 'codex', name: 'Codex', role: null, systemPrompt: null }),+ /refuses non-directory or linked path/,+ )++ await rm(join(home, 'memory'))+ await mkdir(join(home, 'memory'))+ const outsideFile = join(root, 'outside-file')+ await writeFile(outsideFile, 'do not read as memory', 'utf8')+ await symlink(outsideFile, join(home, 'memory', 'MEMORY.md'))+ await assert.rejects(+ getAdapter('codex').seedHome(home, { id: 'codex', name: 'Codex', role: null, systemPrompt: null }),+ /refuses non-file or linked memory index/,+ )+})+test('local engine failure returns stderr tail for observability', async () => {const root = await mkdtemp(join(tmpdir(), 'cumora-engine-'))tempDirs.push(root)@@ -57,7 +142,7 @@ test('local engine failure returns stderr tail for observability', async () => {const result = await getAdapter('claude').run({home,prompt: 'wake',- env: { ...process.env, PATH: `${binDir}:${process.env.PATH ?? ''}` },+ env: secureClaudeEnv(root, { PATH: `${binDir}:${process.env.PATH ?? ''}` }),model: null,fastModel: null,onLog: (line) => logs.push(line),@@ -69,6 +154,74 @@ 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', async () => {+ const root = await mkdtemp(join(tmpdir(), 'cumora-claude-secure-'))+ tempDirs.push(root)+ const binDir = join(root, 'bin')+ const home = join(root, 'home')+ await mkdir(binDir)+ await mkdir(home)+ const capture = join(binDir, 'capture.js')+ await writeFile(+ capture,+ "process.stderr.write(JSON.stringify({ argv: process.argv.slice(2), scrub: process.env.CLAUDE_CODE_SUBPROCESS_ENV_SCRUB }))\nprocess.exit(1)\n",+ 'utf8',+ )+ const launcher = join(binDir, 'claude')+ await writeFile(launcher, '#!/bin/sh\nexec node "$(dirname "$0")/capture.js" "$@"\n', 'utf8')+ await chmod(launcher, 0o755)++ const logs: string[] = []+ const mcpShim = join(root, 'trusted', 'cumora-mcp')+ await getAdapter('claude').run({+ home,+ prompt: 'wake',+ env: secureClaudeEnv(root, {+ PATH: `${binDir}:${process.env.PATH ?? ''}`,+ OPENAI_API_KEY: 'must-not-appear-in-settings',+ }),+ onLog: (line) => logs.push(line),+ signal: new AbortController().signal,+ })++ const captured = JSON.parse(logs[0] ?? '{}') as { argv?: string[]; scrub?: string }+ assert.equal(captured.scrub, '1')+ 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.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+ assert.ok(mcpIndex >= 0)+ const mcpConfig = JSON.parse(captured.argv?.[mcpIndex + 1] ?? '{}') as {+ mcpServers?: { cumora?: { command?: string; args?: string[]; env?: Record<string, string> } }+ }+ assert.equal(mcpConfig.mcpServers?.cumora?.command, process.execPath)+ assert.deepEqual(mcpConfig.mcpServers?.cumora?.args, [mcpShim])+ const settingsIndex = captured.argv?.indexOf('--settings') ?? -1+ assert.ok(settingsIndex >= 0)+ const settingsText = captured.argv?.[settingsIndex + 1] ?? '{}'+ const settings = JSON.parse(settingsText) as {+ permissions?: { allow?: string[]; deny?: string[] }+ sandbox?: {+ failIfUnavailable?: boolean+ allowUnsandboxedCommands?: boolean+ filesystem?: { denyRead?: string[]; allowRead?: string[] }+ credentials?: { 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.equal(settings.sandbox?.failIfUnavailable, true)+ assert.equal(settings.sandbox?.allowUnsandboxedCommands, false)+ assert.ok(settings.sandbox?.filesystem?.denyRead?.includes(process.platform === 'darwin' ? '/Users' : '/home'))+ assert.ok(settings.sandbox?.filesystem?.allowRead?.includes(home))+ assert.ok(settings.sandbox?.credentials?.envVars?.some((entry) => entry.name === 'OPENAI_API_KEY' && entry.mode === 'deny'))+ assert.doesNotMatch(settingsText, /must-not-appear-in-settings/)+})+test('persistent Claude startup failure keeps stderr for first send', async () => {const root = await mkdtemp(join(tmpdir(), 'cumora-engine-session-'))tempDirs.push(root)@@ -89,7 +242,7 @@ test('persistent Claude startup failure keeps stderr for first send', async () =const logs: string[] = []const session = getAdapter('claude').startSession?.({home,- env: { ...process.env, PATH: `${binDir}:${process.env.PATH ?? ''}` },+ env: secureClaudeEnv(root, { PATH: `${binDir}:${process.env.PATH ?? ''}` }),model: null,fastModel: null,onLog: (line) => logs.push(line),@@ -135,7 +288,7 @@ test('grok adapter seeds AGENTS.md and reports sessionId from stream-json', asynconst result = await adapter.run({home,prompt: 'wake',- env: { ...process.env, PATH: `${binDir}:${process.env.PATH ?? ''}` },+ env: secureClaudeEnv(root, { PATH: `${binDir}:${process.env.PATH ?? ''}` }),model: null,fastModel: null,onLog: () => { /* unused */ },@@ -216,12 +369,18 @@ test('Codex one-shot paths send prompts through stdin', async () => {process.env.PATH = `${binDir}${delimiter}${ORIGINAL_PATH ?? ''}`const adapter = getAdapter('codex')+ const mcpShim = join(root, 'trusted', 'cumora-mcp')const longPrompt = `line one with spaces & shell characters\n${'x'.repeat(12_000)}`const logs: string[] = []const run = await adapter.run({home,prompt: longPrompt,- env: { ...process.env },+ env: {+ ...process.env,+ OPENAI_API_KEY: 'must-not-reach-tools',+ CUMORA_AGENT_IPC_DIR: join(root, 'private-ipc'),+ CUMORA_AGENT_MCP_SHIM: mcpShim,+ },model: 'test-model',fastModel: null,onLog: (line) => logs.push(line),@@ -229,10 +388,31 @@ test('Codex one-shot paths send prompts through stdin', async () => {})assert.equal(run.exitCode, 0)const runCapture = JSON.parse(logs.at(-1) ?? '{}') as { argv?: string[]; stdin?: string }- assert.deepEqual(runCapture.argv, [- 'exec', '--model', 'test-model',- '--dangerously-bypass-approvals-and-sandbox', '--skip-git-repo-check', '-',- ])+ assert.ok(runCapture.argv?.includes('default_permissions="cumora"'))+ assert.ok(runCapture.argv?.includes('permissions.cumora.network.enabled=false'))+ assert.ok(runCapture.argv?.includes('shell_environment_policy.inherit="none"'))+ assert.equal(runCapture.argv?.some((arg) => arg.includes(`${join(root, 'private-ipc', 'requests')}"="write`)), false)+ assert.equal(runCapture.argv?.some((arg) => arg.includes(`${join(root, 'private-ipc', 'responses')}"="write`)), false)+ assert.ok(runCapture.argv?.includes('web_search="disabled"'))+ assert.ok(runCapture.argv?.includes('features.hooks=false'))+ assert.ok(runCapture.argv?.includes(`projects.${JSON.stringify(home)}.trust_level="untrusted"`))+ assert.ok(runCapture.argv?.some((arg) =>+ arg.startsWith('mcp_servers.cumora={')+ && arg.includes(`command=${JSON.stringify(process.execPath)}`)+ && arg.includes(`args=[${JSON.stringify(mcpShim)}]`)+ && arg.includes(`CUMORA_AGENT_IPC_DIR=${JSON.stringify(join(root, 'private-ipc'))}`)+ && arg.includes('enabled_tools=["cli"]')+ && arg.includes('required=true'),+ ))+ assert.ok(runCapture.argv?.includes('exec'))+ assert.ok(runCapture.argv?.includes('--ignore-user-config'))+ assert.ok(runCapture.argv?.includes('--ignore-rules'))+ assert.ok(runCapture.argv?.includes('--model'))+ assert.ok(runCapture.argv?.includes('test-model'))+ assert.ok(runCapture.argv?.includes('--skip-git-repo-check'))+ assert.equal(runCapture.argv?.at(-1), '-')+ assert.equal(runCapture.argv?.some((arg) => arg.includes('dangerously')), false)+ assert.equal(runCapture.argv?.some((arg) => arg.includes('must-not-reach-tools')), false)assert.equal(runCapture.stdin, longPrompt)const triagePrompt = 'triage prompt with spaces\nand a second line'@@ -244,9 +424,11 @@ test('Codex one-shot paths send prompts through stdin', async () => {signal: new AbortController().signal,})const triageCapture = JSON.parse(triage.text) as { argv?: string[]; stdin?: string }- assert.deepEqual(triageCapture.argv, [- 'exec', '--model', 'triage-model', '--skip-git-repo-check', '-',- ])+ assert.ok(triageCapture.argv?.includes('permissions.cumora.filesystem={":minimal"="read",":workspace_roots"={"."="read"}}'))+ assert.equal(triageCapture.argv?.some((arg) => arg.startsWith('mcp_servers.cumora=')), false)+ assert.ok(triageCapture.argv?.includes('--ignore-user-config'))+ assert.ok(triageCapture.argv?.includes('triage-model'))+ assert.equal(triageCapture.argv?.at(-1), '-')assert.equal(triageCapture.stdin, triagePrompt)const probe = await adapter.probe({@@ -256,7 +438,9 @@ test('Codex one-shot paths send prompts through stdin', async () => {signal: new AbortController().signal,})const probeCapture = JSON.parse(probe.text) as { argv?: string[]; stdin?: string }- assert.deepEqual(probeCapture.argv, ['exec', '--skip-git-repo-check', '-'])+ assert.ok(probeCapture.argv?.includes('permissions.cumora.network.enabled=false'))+ assert.ok(probeCapture.argv?.includes('--ignore-user-config'))+ assert.equal(probeCapture.argv?.at(-1), '-')assert.equal(probeCapture.stdin, 'Connectivity check. Reply with exactly: OK')})@@ -303,6 +487,7 @@ async function fakeCodexRejectingThread(root: string): Promise<string> {}async function startFakeCodexSession(opts: { resume?: string } = {}) {+ process.env.CUMORA_BYOA_ALLOW_UNSANDBOXED = '1'const root = await mkdtemp(join(tmpdir(), 'cumora-codex-'))tempDirs.push(root)const home = join(root, 'home')@@ -311,7 +496,7 @@ async function startFakeCodexSession(opts: { resume?: string } = {}) {const logs: string[] = []const session = getAdapter('codex').startSession!({home,- env: { ...process.env, PATH: `${binDir}:${process.env.PATH ?? ''}` },+ env: secureClaudeEnv(root, { PATH: `${binDir}:${process.env.PATH ?? ''}` }),resumeSessionId: opts.resume ?? null,onLog: (l) => logs.push(l),})@@ -391,7 +576,7 @@ test('a stream-json event split across pipe chunks is still parsed', { skip: IS_const r = await getAdapter('claude').run({home,prompt: 'go',- env: { ...process.env, PATH: `${binDir}:${process.env.PATH ?? ''}` },+ env: secureClaudeEnv(dirname(home), { PATH: `${binDir}:${process.env.PATH ?? ''}` }),onLog: () => {},onHopUsage: (h) => hops.push({ model: h.model }),signal: new AbortController().signal,@@ -427,7 +612,7 @@ test('a multi-byte character split across pipe chunks is not corrupted', { skip:const r = await getAdapter('claude').run({home,prompt: 'go',- env: { ...process.env, PATH: `${binDir}:${process.env.PATH ?? ''}` },+ env: secureClaudeEnv(root, { PATH: `${binDir}:${process.env.PATH ?? ''}` }),onLog: () => {},signal: new AbortController().signal,})@@ -439,8 +624,8 @@ test('a multi-byte character split across pipe chunks is not corrupted', { skip:// ── one-shot engine children must die with their runner ─────────────────────// The persistent session is torn down by AgentRunner.stop(); the one-shot child// was not, because its AbortSignal came from a controller nothing ever aborted.-// An orphan keeps a valid runtime token and the `cumora` shim on PATH, so it-// goes on posting AS the agent while the replacement runner answers the same+// An orphan keeps the `cumora` IPC shim on PATH, so it can go on posting AS the+// agent while the replacement runner answers the same// messages — with the OLD persona the operator just changed./** A fake engine shaped like a real one: it spawns a child that INHERITS its@@ -468,7 +653,7 @@ async function runFakeEngine(binDir: string, home: string, signal: AbortSignal)return getAdapter('claude').run({home,prompt: 'go',- env: { ...process.env, PATH: `${binDir}:${process.env.PATH ?? ''}` },+ env: secureClaudeEnv(dirname(home), { PATH: `${binDir}:${process.env.PATH ?? ''}` }),onLog: () => {},signal,})@@ -488,7 +673,7 @@ test('an already-aborted signal kills the engine child immediately', { skip: IS_const r = await Promise.race([runFakeEngine(binDir, home, ac.signal),- delay(15_000).then(() => 'ORPHANED' as const),+ delay(15_000, 'ORPHANED' as const, { ref: false }),])assert.notEqual(r, 'ORPHANED', 'the child outlived its aborted signal — it would keep posting as the agent')assert.notEqual((r as { exitCode: number }).exitCode, 0, 'a killed turn must not report success')@@ -505,11 +690,66 @@ test('aborting mid-run kills the engine child', { skip: IS_WIN }, async () => {const p = runFakeEngine(binDir, home, ac.signal)await delay(150)ac.abort()- const r = await Promise.race([p, delay(15_000).then(() => 'ORPHANED' as const)])+ const r = await Promise.race([p, delay(15_000, 'ORPHANED' as const, { ref: false })])assert.notEqual(r, 'ORPHANED', 'abort must terminate the turn even when a grandchild holds the stdio pipes')assert.notEqual((r as { exitCode: number }).exitCode, 0)})+test('aborting kills a descendant that detached into its own process group', { skip: IS_WIN }, async () => {+ const root = await mkdtemp(join(tmpdir(), 'cumora-abort-detached-'))+ tempDirs.push(root)+ const home = join(root, 'home')+ const binDir = join(root, 'bin')+ const pidFile = join(root, 'detached.pid')+ await mkdir(home)+ await mkdir(binDir)+ const fake = join(binDir, 'claude')+ await writeFile(+ fake,+ '#!/usr/bin/env node\n' ++ "const { spawn } = require('node:child_process')\n" ++ "const { writeFileSync } = require('node:fs')\n" ++ "const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 120000)'], { detached: true, stdio: 'ignore' })\n" ++ "writeFileSync(process.env.FAKE_DETACHED_PID_FILE, String(child.pid))\n" ++ 'setTimeout(() => {}, 120000)\n',+ 'utf8',+ )+ await chmod(fake, 0o755)++ const ac = new AbortController()+ const run = getAdapter('claude').run({+ home,+ prompt: 'go',+ env: secureClaudeEnv(root, {+ PATH: `${binDir}:${process.env.PATH ?? ''}`,+ FAKE_DETACHED_PID_FILE: pidFile,+ }),+ onLog: () => {},+ signal: ac.signal,+ })+ let detachedPid = 0+ try {+ for (let i = 0; i < 100 && detachedPid === 0; i += 1) {+ try { detachedPid = Number((await readFile(pidFile, 'utf8')).trim()) }+ catch { await delay(20) }+ }+ assert.ok(detachedPid > 0, 'fake engine must expose its detached child pid')+ ac.abort()+ const result = await Promise.race([run, delay(15_000, 'ORPHANED' as const, { ref: false })])+ assert.notEqual(result, 'ORPHANED')++ assert.throws(+ () => process.kill(detachedPid, 0),+ (err: unknown) => (err as NodeJS.ErrnoException).code === 'ESRCH',+ 'run() must not resolve until a setsid-style descendant is gone',+ )+ } finally {+ if (detachedPid > 0) {+ try { process.kill(detachedPid, 'SIGKILL') } catch { /* already gone */ }+ }+ }+})+test('a normal run is unaffected by the abort wiring', { skip: IS_WIN }, async () => {const root = await mkdtemp(join(tmpdir(), 'cumora-noabort-'))tempDirs.push(root)@@ -523,7 +763,7 @@ test('a normal run is unaffected by the abort wiring', { skip: IS_WIN }, async (const r = await getAdapter('claude').run({home,prompt: 'go',- env: { ...process.env, PATH: `${binDir}:${process.env.PATH ?? ''}` },+ env: secureClaudeEnv(root, { PATH: `${binDir}:${process.env.PATH ?? ''}` }),onLog: () => {},signal: new AbortController().signal,})diff --git a/server/src/agents/computer/cli-version.ts b/server/src/agents/computer/cli-version.tsindex 5936019..efedcd4 100644--- a/server/src/agents/computer/cli-version.ts+++ b/server/src/agents/computer/cli-version.ts@@ -146,6 +146,25 @@ function versionParts(v: string): number[] {return main.split('.').map((n) => Number.parseInt(n, 10) || 0)}+/** Semver/CalVer floor used for local capability gates. A prerelease at the+ * exact numeric floor remains below the final release; unknown versions fail+ * closed at the caller. */+export function isCliVersionAtLeast(current: string | null, minimum: string): boolean {+ if (!current) return false+ const a = versionParts(current)+ const b = versionParts(minimum)+ const n = Math.max(a.length, b.length)+ for (let i = 0; i < n; i++) {+ const x = a[i] ?? 0+ const y = b[i] ?? 0+ if (x > y) return true+ if (x < y) return false+ }+ const currentMain = current.trim().replace(/^v/i, '').split('+', 1)[0]+ const minimumMain = minimum.trim().replace(/^v/i, '').split('+', 1)[0]+ return !(currentMain.includes('-') && !minimumMain.includes('-'))+}+/** True only when `latest` is strictly newer. Unknown on either side means we* say nothing rather than nag. */export function isCliOutdated(current: string | null, latest: string | null): boolean {@@ -305,3 +324,11 @@ export async function probeEngineVersion(id: string, binPath: string | null): PrupdateCommand: outdated ? inferUpdateCommand(spec, binPath) : null,}}++/** Local-only version probe for security capability gates. Unlike+ * probeEngineVersion(), this never contacts npm or an engine updater. */+export async function probeLocalEngineVersion(id: string, binPath: string | null): Promise<string | null> {+ const spec = ENGINE_VERSION_SPECS[id]+ if (!spec || !binPath) return null+ return parseCliVersion(await spawnText(binPath, spec.versionArgs, 6000))+}diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.tsindex a2fe5ad..277bdbf 100644--- a/server/src/agents/computer/daemon.ts+++ b/server/src/agents/computer/daemon.ts@@ -11,39 +11,41 @@* - then run: cumora agent computer [--server <url>]** Per managed agent it: mints a short-lived runtime JWT, holds a wake-stream- * SSE connection, and on each wake spawns the engine in the agent's isolated- * home (~/.cumora/agents/<id>/). The engine acts on Cumora via a `cumora`- * shim the daemon writes onto its PATH (which POSTs to /runtime/cli).+ * SSE connection, and on each wake runs the engine in the agent's dedicated+ * home (~/.cumora/agents/<id>/). Secure adapters impose the host boundary;+ * a fixed MCP bridge sends file-IPC requests that the daemon forwards to Cumora.** Standalone: only Node builtins + the DB-free SSE parser + engine.ts.*/-import { createHash } from 'node:crypto'-import { mkdir, writeFile, readFile, chmod, rm, stat, copyFile, truncate } from 'node:fs/promises'-import { existsSync } from 'node:fs'-import { homedir, hostname } from 'node:os'-import { delimiter, join, dirname } from 'node:path'+import { execFile, spawn } from 'node:child_process'+import { createHash, randomUUID } from 'node:crypto'+import { existsSync, constants as FS_CONSTANTS, type FSWatcher, watch } from 'node:fs'+import { chmod, copyFile, lstat, mkdir, open, readdir, readFile, rename, rm, stat, truncate, writeFile } from 'node:fs/promises'+import { homedir, hostname } from 'node:os'+import { delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'import { promisify } from 'node:util'const execFileP = promisify(execFile)-import { parseSseStream, wakeStreamWasStable } from '../runtime/sse-parse.js'-import {- mergeWakeBackgroundBriefs,- parseWakeData,- wakeHasActionableInput,- type WakeBackgroundBrief,-} from '../runtime/wake-options.js'-import { detectEnginesWithStatus, snapshotDetectedEngines, enrichDetectedEngines, getAdapter, ENGINE_IDS, runEngineDoctor, type EngineId, type EngineSession, type EngineRunResult, type EngineUsage, type EngineHopReport } from './engine.js'-import { usageFromClaude, type TokenUsage } from '../cost.js'-import { parseTriage, finalizeTriage, isRateLimited } from '../triage-core.js'++import { type TokenUsage, usageFromClaude } from '../cost.js'import { GLANCE_YIELD_RULES } from '../glance-protocol.js'-import { SKYPE_EMOTICONS_GUIDE } from '../skype-emoticons.js'import {composeMemoryDigest,conversationHeader,memoryIndexPathsForScope,uniqueProjectIds,} from '../memory-scope.js'+import { parseSseStream, wakeStreamWasStable } from '../runtime/sse-parse.js'+import {+ mergeWakeBackgroundBriefs,+ parseWakeData,+ type WakeBackgroundBrief,+ wakeHasActionableInput,+} from '../runtime/wake-options.js'+import { SKYPE_EMOTICONS_GUIDE } from '../skype-emoticons.js'+import { finalizeTriage, isRateLimited, parseTriage } from '../triage-core.js'+import { allowUnsandboxedByoa, detectEnginesWithStatus, ENGINE_IDS, type EngineHopReport, type EngineId, type EngineRunResult, type EngineSession, type EngineUsage, enrichDetectedEngines, evaluateRunnableEngines, getAdapter, runEngineDoctor, snapshotDetectedEngines } from './engine.js'export { conversationHeader }@@ -656,9 +658,11 @@ function missingEngineMessage(): string {return ['no supported local agent engine found on PATH','',- 'Install and sign in to at least one of:',+ 'Secure default — install and sign in to at least one of:',' - Claude Code: install the `claude` CLI, then run `claude` once to sign in',' - Codex: install the `codex` CLI, then run `codex` once to sign in',+ '',+ 'Unsandboxed compatibility engines (explicit opt-in required):',' - Grok Build: install the `grok` CLI, then run `grok login` once',' - Cursor Agent: install Cursor (the `cursor-agent` CLI ships with it), then run `cursor-agent login`',' - OpenCode: install the `opencode` CLI, then run `opencode providers login` once',@@ -669,12 +673,41 @@ function missingEngineMessage(): string {].join('\n')}+function sandboxedEngineMessage(installed: readonly EngineId[]): string {+ return [+ `installed engines are disabled by Cumora's secure BYOA default: ${installed.join(', ')}`,+ '',+ process.platform === 'win32'+ ? 'Use Codex on native Windows, or run Claude Code inside WSL2.'+ : 'Install and sign in to Claude Code or Codex.',+ 'Grok, Cursor, OpenCode, pi, Gemini, and native-Windows Claude currently lack',+ 'a Cumora-verified fail-closed host boundary.',+ '',+ 'Compatibility only (grants the model your host files, environment, and network):',+ ' CUMORA_BYOA_ALLOW_UNSANDBOXED=1 npx cumora@latest agent computer ...',+ ].join('\n')+}++function incapableEngineMessage(blocked: ReadonlyArray<{ id: EngineId; reason: string }>): string {+ return [+ 'installed secure engines cannot enforce Cumora\'s BYOA boundary:',+ ...blocked.map(({ id, reason }) => ` - ${id}: ${reason}`),+ '',+ 'Update the CLI and install any named sandbox dependencies, then retry.',+ 'Compatibility only (disables this capability gate and host boundary):',+ ' CUMORA_BYOA_ALLOW_UNSANDBOXED=1 npx cumora@latest agent computer ...',+ ].join('\n')+}+function helpText(): string {return ['cumora agent computer — run your Cumora agents on THIS machine (BYOA)','','The daemon talks to a Cumora server over HTTP and drives a local agent',- 'engine (Claude Code, Codex, Grok Build, Cursor Agent, OpenCode, or pi). Pair once, then it runs in the background.',+ 'engine. Claude Code and Codex are sandboxed by default. Grok Build, Cursor',+ 'Agent, OpenCode, pi, Gemini, and native-Windows Claude require the explicit',+ 'high-risk CUMORA_BYOA_ALLOW_UNSANDBOXED=1 compatibility switch.',+ 'Pair once, then the daemon runs in the background.','','Usage:',' npx cumora@latest agent computer --pair <code> [--server <url>] [--engine <id>]',@@ -709,7 +742,15 @@ async function requireLocalEngine(): Promise<EngineId[]> {throw new Error('could not scan PATH (`which` / `where` failed). Fix that, then retry pairing.')}if (detected.engines.length === 0) throw new Error(missingEngineMessage())- return detected.engines+ const evaluated = await evaluateRunnableEngines(detected.engines)+ if (evaluated.runnable.length === 0) {+ if (evaluated.blocked.length > 0) throw new Error(incapableEngineMessage(evaluated.blocked))+ throw new Error(sandboxedEngineMessage(detected.engines))+ }+ if (evaluated.blocked.length > 0) {+ console.warn(`[computer] secure engine(s) disabled: ${evaluated.blocked.map(({ id, reason }) => `${id} (${reason})`).join('; ')}`)+ }+ return evaluated.runnable}/** Resolve the engine a daemon can actually run from its LIVE PATH inventory. */@@ -747,23 +788,23 @@ async function saveConfig(cfg: DaemonConfig): Promise<void> {// ─── the `cumora` shim ──────────────────────────────────────────────────//-// A tiny Node executable named `cumora` that the engine calls via bash. It-// POSTs argv to the server's /runtime/cli, which runs the full CLI server--// side with the agent's identity pinned by the JWT. No curl/jq dependency.+// The engine must be able to use Cumora without also receiving a reusable JWT+// or arbitrary network access. The fixed MCP bridge calls a tiny `cumora`+// executable in a daemon-owned tools directory; that client writes argv into a+// per-agent rendezvous directory outside the model home and waits for the daemon+// to answer. The daemon alone owns the runtime token and performs the HTTP call.+//+// Files rather than a TCP/Unix socket are deliberate: every supported engine+// can keep tool subprocesses network-denied, and the protocol works on macOS,+// Linux, native Windows, and WSL without punching a hole in that boundary.//// Exported for tests: the output-truncation regression below is only observable// by running the real shim text against a real pipe.export const CUMORA_SHIM = `#!/usr/bin/env node'use strict';(async () => {- const url = process.env.CUMORA_AGENT_RUNTIME_URL- // Prefer a token FILE (refreshed by the daemon) over the env token: a PERSISTENT- // engine process is spawned once, so its env token goes stale on refresh — the- // file is always current. Falls back to the env token (one-shot / codex path).- var token = process.env.CUMORA_AGENT_RUNTIME_TOKEN- var tokenFile = process.env.CUMORA_AGENT_RUNTIME_TOKEN_FILE- if (tokenFile) { try { var ft = require('fs').readFileSync(tokenFile, 'utf8').trim(); if (ft) token = ft } catch (e) {} }- if (!url || !token) { console.error('cumora: runtime env not set'); process.exit(70) }+ var ipc = process.env.CUMORA_AGENT_IPC_DIR+ if (!ipc) { console.error('cumora: runtime IPC not set'); process.exit(70) }var argv = process.argv.slice(2)// Shell-safe body input. A reply written inline (cumora reply id "..text..")// is mangled by bash BEFORE this shim runs: backticks and $(...) get run as@@ -777,6 +818,8 @@ export const CUMORA_SHIM = `#!/usr/bin/env node// rule, front-matter fence, diff header) parsed as a FLAG and the message was// silently dropped, and escapes inside it were expanded a second time.var fs = require('fs')+ var path = require('path')+ var crypto = require('crypto')var body = nullvar fi = argv.indexOf('--file')if (fi >= 0 && argv[fi + 1] !== undefined) {@@ -790,17 +833,28 @@ export const CUMORA_SHIM = `#!/usr/bin/env nodeif (body === null) { try { body = fs.readFileSync(0, 'utf8') } catch (e) { body = '' } }}if (body !== null) argv.push('--', body)- const res = await fetch(url + '/cli', {- method: 'POST',- headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },- body: JSON.stringify({ argv: argv }),- })- if (!res.ok) {- const t = await res.text().catch(() => '')- console.error('cumora: HTTP ' + res.status + ' ' + t)- process.exit(70)+ var id = crypto.randomUUID()+ var requests = path.join(ipc, 'requests')+ var responses = path.join(ipc, 'responses')+ var request = path.join(requests, id + '.json')+ var staged = request + '.' + process.pid + '.tmp'+ fs.writeFileSync(staged, JSON.stringify({ argv: argv }), { mode: 0o600 })+ fs.renameSync(staged, request)++ var response = path.join(responses, id + '.json')+ var deadline = Date.now() + 5 * 60 * 1000+ while (!fs.existsSync(response)) {+ if (Date.now() >= deadline) {+ try { fs.unlinkSync(request) } catch (e) {}+ console.error('cumora: daemon IPC timed out')+ process.exit(70)+ }+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25)}- const data = await res.json()+ var data+ try { data = JSON.parse(fs.readFileSync(response, 'utf8')) }+ finally { try { fs.unlinkSync(response) } catch (e) {} }+ if (data && typeof data.error === 'string' && data.error) console.error('cumora: ' + data.error)const code = typeof data.exitCode === 'number' ? data.exitCode : 0// Exit from the write CALLBACK, not the next statement: stdout on a PIPE is// ASYNC, so process.exit() kills us with the tail still buffered. The engine@@ -816,6 +870,273 @@ export const CUMORA_SHIM = `#!/usr/bin/env node})().catch((e) => { console.error('cumora:', (e && e.message) || e); process.exit(70) })`+/** Restricted Claude does not receive Bash at all. This fixed MCP bridge gives+ * it one structured tool that invokes the unprivileged file-IPC shim without+ * a shell. Local-body flags are rejected because the MCP process itself is not+ * inside Claude's Bash sandbox; callers pass body text as an argv item instead. */+export const CUMORA_MCP_SHIM = `#!/usr/bin/env node+'use strict'+var cp = require('child_process')+var path = require('path')+var readline = require('readline')+var shim = path.join(__dirname, 'cumora')+var childEnv = {}+;['PATH', 'HOME', 'USER', 'LOGNAME', 'SHELL', 'TMPDIR', 'TMP', 'TEMP', 'LANG', 'LANGUAGE', 'TERM', 'NO_COLOR', 'SYSTEMROOT', 'COMSPEC', 'PATHEXT', 'WINDIR', 'CUMORA_AGENT_IPC_DIR', 'CUMORA_AGENT_ID'].forEach(function (name) {+ if (process.env[name] !== undefined) childEnv[name] = process.env[name]+})+function send(id, result, error) {+ var msg = { jsonrpc: '2.0', id: id }+ if (error) msg.error = { code: -32602, message: error }+ else msg.result = result+ process.stdout.write(JSON.stringify(msg) + '\\n')+}+function toolError(text) {+ return { content: [{ type: 'text', text: text }], isError: true }+}+function handle(msg) {+ if (!msg || msg.jsonrpc !== '2.0') return+ if (msg.method === 'initialize' && msg.id !== undefined) {+ send(msg.id, {+ protocolVersion: (msg.params && msg.params.protocolVersion) || '2025-06-18',+ capabilities: { tools: {} },+ serverInfo: { name: 'cumora', version: '1.0.0' },+ })+ return+ }+ if (msg.method === 'tools/list' && msg.id !== undefined) {+ send(msg.id, { tools: [{+ name: 'cli',+ description: 'Act in Cumora. Pass command-line words as argv; put message bodies directly in argv and never use local file paths.',+ inputSchema: {+ type: 'object',+ properties: { argv: { type: 'array', items: { type: 'string' }, minItems: 1, maxItems: 2000 } },+ required: ['argv'],+ additionalProperties: false,+ },+ }] })+ return+ }+ if (msg.method === 'tools/call' && msg.id !== undefined) {+ var p = msg.params || {}+ var argv = p.arguments && p.arguments.argv+ if (p.name !== 'cli' || !Array.isArray(argv) || !argv.length || argv.length > 2000 || argv.some(function (v) { return typeof v !== 'string' })) {+ send(msg.id, toolError('invalid Cumora argv'))+ return+ }+ if (argv.some(function (v) { return v === '--file' || v === '--stdin' })) {+ send(msg.id, toolError('local file/stdin flags are unavailable; pass body text directly in argv'))+ return+ }+ cp.execFile(process.execPath, [shim].concat(argv), {+ env: childEnv,+ maxBuffer: 32 * 1024 * 1024,+ windowsHide: true,+ }, function (err, stdout, stderr) {+ var text = String(stdout || '')+ if (stderr) text += (text ? '\\n' : '') + String(stderr)+ var failed = !!err+ send(msg.id, { content: [{ type: 'text', text: text.trimEnd() }], isError: failed })+ })+ return+ }+ if (msg.method === 'ping' && msg.id !== undefined) send(msg.id, {})+}+var rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity })+rl.on('line', function (line) {+ try { handle(JSON.parse(line)) }+ catch (e) { process.stderr.write('cumora-mcp: invalid JSON\\n') }+})+`++const CLI_IPC_FALLBACK_POLL_MS = 1_000+const CLI_IPC_MAX_REQUEST_BYTES = 32 * 1024 * 1024+const CLI_IPC_MAX_ARGS = 2_000++export interface RuntimeCliBrokerResult {+ text?: string+ exitCode: number+ error?: string+}++/** File-rendezvous broker used by one AgentRunner.+ *+ * Request names come from readdir(), not request content, and are claimed by an+ * atomic rename before parsing. A malformed/oversized request gets a bounded+ * error response; it can never turn into a path chosen by the model. */+export class RuntimeCliBroker {+ private timer: ReturnType<typeof setInterval> | null = null+ private watcher: FSWatcher | null = null+ private pollPromise: Promise<void> | null = null+ private rerunRequested = false+ private stopped = false+ private abortController = new AbortController()+ private readonly requestsDir: string+ private readonly responsesDir: string++ constructor(+ ipcDir: string,+ private readonly processingDir: string,+ private readonly invoke: (argv: string[], signal: AbortSignal) => Promise<RuntimeCliBrokerResult>,+ ) {+ this.requestsDir = join(ipcDir, 'requests')+ this.responsesDir = join(ipcDir, 'responses')+ }++ async start(): Promise<void> {+ // A stopped broker may be started again by a supervisor. Never clean or+ // reuse its namespace while the previous drain is still unwinding.+ if (this.pollPromise) await this.pollPromise.catch(() => {})+ this.pollPromise = null+ this.rerunRequested = false+ await mkdir(this.requestsDir, { recursive: true })+ await mkdir(this.responsesDir, { recursive: true })+ await mkdir(this.processingDir, { recursive: true })+ // Requests/responses cannot survive their daemon process: the bearer token+ // and server result they belonged to are gone. Remove only this dedicated+ // IPC namespace, never agent work files.+ await this.clearDir(this.requestsDir)+ await this.clearDir(this.responsesDir)+ await this.clearDir(this.processingDir)+ this.stopped = false+ this.abortController = new AbortController()+ // Directory notifications keep the common path event-driven even when one+ // computer hosts many agents. A slow fallback poll covers dropped watcher+ // events and filesystems where fs.watch is unavailable or unreliable.+ try {+ this.watcher = watch(this.requestsDir, { persistent: false }, () => {+ void this.poll().catch((err) => this.logPollFailure(err))+ })+ this.watcher.on('error', () => {+ this.watcher?.close()+ this.watcher = null+ })+ } catch { this.watcher = null }+ this.timer = setInterval(() => {+ void this.poll().catch((err) => this.logPollFailure(err))+ }, CLI_IPC_FALLBACK_POLL_MS)+ this.timer.unref?.()+ }++ stop(): void {+ this.stopped = true+ this.rerunRequested = false+ this.abortController.abort()+ if (this.timer) clearInterval(this.timer)+ this.timer = null+ this.watcher?.close()+ this.watcher = null+ }++ /** Immediate poll for deterministic tests; the normal runner uses the timer. */+ poll(): Promise<void> {+ if (this.stopped) return Promise.resolve()+ // Coalesce an arbitrary watcher/timer storm into one pending rerun. Every+ // caller shares the same drain promise, so an explicit await still covers a+ // request that landed after the active pass took its readdir snapshot.+ this.rerunRequested = true+ if (!this.pollPromise) {+ const drain = this.drainPolls()+ this.pollPromise = drain+ // Use both handlers instead of .finally(): ignoring the Promise returned+ // by finally() would itself create an unhandled rejection on failure.+ void drain.then(+ () => { if (this.pollPromise === drain) this.pollPromise = null },+ () => { if (this.pollPromise === drain) this.pollPromise = null },+ )+ }+ return this.pollPromise+ }++ private async drainPolls(): Promise<void> {+ while (!this.stopped && this.rerunRequested) {+ this.rerunRequested = false+ const names = await readdir(this.requestsDir).catch(() => [] as string[])+ for (const name of names) {+ if (this.stopped || this.abortController.signal.aborted) break+ if (!/^[0-9a-f-]{36}\.json$/i.test(name)) continue+ try { await this.handle(name) }+ catch (err) { this.logPollFailure(err, name) }+ }+ }+ }++ private logPollFailure(err: unknown, name?: string): void {+ console.error(+ `[runtime] CLI IPC broker${name ? ` request ${name}` : ''} failed`,+ err instanceof Error ? err.message : String(err),+ )+ }++ private async handle(name: string): Promise<void> {+ const signal = this.abortController.signal+ if (signal.aborted) return+ const source = join(this.requestsDir, name)+ // Production puts processingDir outside the model-writable Agent home.+ // Once rename succeeds, the sandbox cannot replace the claimed inode during+ // the lstat/open gap (including on Windows, where O_NOFOLLOW is unavailable).+ const claimed = join(this.processingDir, `${name}.${process.pid}.${randomUUID().slice(0, 8)}.processing`)+ try { await rename(source, claimed) } catch { return }+ const response = join(this.responsesDir, name)+ let stagedResponse: string | null = null+ let result: RuntimeCliBrokerResult+ try {+ // Never follow a model-created request symlink with the daemon's broader+ // privileges. O_NOFOLLOW is defense in depth on POSIX; the private claim+ // directory closes the check/open race on every supported platform.+ const before = await lstat(claimed)+ if (!before.isFile() || before.isSymbolicLink()) {+ throw new Error('runtime IPC request is not a regular file')+ }+ const noFollow = typeof FS_CONSTANTS.O_NOFOLLOW === 'number' ? FS_CONSTANTS.O_NOFOLLOW : 0+ const file = await open(claimed, FS_CONSTANTS.O_RDONLY | noFollow)+ let raw: string+ try {+ const info = await file.stat()+ if (!info.isFile() || info.size > CLI_IPC_MAX_REQUEST_BYTES) {+ throw new Error('runtime IPC request is too large')+ }+ raw = await file.readFile('utf8')+ }+ finally { await file.close() }+ const parsed = JSON.parse(raw) as { argv?: unknown }+ if (!Array.isArray(parsed.argv)+ || parsed.argv.length > CLI_IPC_MAX_ARGS+ || parsed.argv.some((arg) => typeof arg !== 'string')) {+ throw new Error('runtime IPC argv is invalid')+ }+ if (signal.aborted) throw new Error('runtime IPC request cancelled')+ result = await this.invoke(parsed.argv as string[], signal)+ } catch (err) {+ if (signal.aborted) {+ await rm(claimed, { force: true }).catch(() => {})+ return+ }+ result = { exitCode: 70, error: err instanceof Error ? err.message : String(err) }+ }+ try {+ if (signal.aborted) return+ // Stage in the daemon-private directory. The model can write response+ // contents only after the final atomic rename, never redirect a privileged+ // write by pre-creating a symlink at a guessed temporary name.+ stagedResponse = join(this.processingDir, `${name}.${process.pid}.${randomUUID().slice(0, 8)}.response.tmp`)+ await writeFile(stagedResponse, JSON.stringify(result), { mode: 0o600 })+ if (signal.aborted) return+ await rename(stagedResponse, response)+ stagedResponse = null+ } finally {+ if (stagedResponse) await rm(stagedResponse, { force: true }).catch(() => {})+ await rm(claimed, { force: true }).catch(() => {})+ }+ }++ private async clearDir(dir: string): Promise<void> {+ const names = await readdir(dir).catch(() => [] as string[])+ // These directories contain protocol files only. Never recurse into a+ // model-created directory/junction while cleaning stale traffic.+ await Promise.all(names.map((name) => rm(join(dir, name), { force: true }).catch(() => {})))+ }+}+/** PowerShell only resolves files on PATH through PATHEXT, so the extensionless* POSIX shim needs a .cmd launcher on Windows. Keep the Node program itself in* one file so both launchers exercise the exact same argument/HTTP path. */@@ -825,16 +1146,66 @@ export function prependAgentBinToPath(binDir: string, currentPath = process.env.return currentPath ? `${binDir}${delimiter}${currentPath}` : binDir}+/** Secure adapters must resolve their own binary from the operator's original+ * PATH. The agent home is model-writable, so prepending <home>/bin would let a+ * model plant `claude`/`codex` and escape before the next sandbox starts. */+export function engineProcessPath(+ binDir: string,+ currentPath = process.env.PATH ?? '',+ unsandboxed = allowUnsandboxedByoa(),+): string {+ if (unsandboxed) return prependAgentBinToPath(binDir, currentPath)+ const writableHome = resolve(dirname(binDir))+ return currentPath+ .split(delimiter)+ // Empty and relative PATH entries resolve against the engine cwd — its+ // model-writable home — and are therefore engine-shadow paths too.+ .filter((entry) => {+ if (!entry || !isAbsolute(entry)) return false+ const fromHome = relative(writableHome, resolve(entry))+ return isAbsolute(fromHome) || fromHome === '..' || fromHome.startsWith(`..${sep}`)+ })+ .join(delimiter)+}++async function writeShimFile(path: string, data: string, mode: number): Promise<void> {+ const staged = join(dirname(path), `.cumora-shim-${process.pid}-${randomUUID()}.tmp`)+ await writeFile(staged, data, { encoding: 'utf8', mode, flag: 'wx' })+ try {+ await chmod(staged, mode)+ try { await rename(staged, path) }+ catch (err) {+ if (process.platform !== 'win32'+ || !['EEXIST', 'EPERM'].includes((err as NodeJS.ErrnoException).code ?? '')) throw err+ await rm(path, { force: true })+ await rename(staged, path)+ }+ } finally {+ await rm(staged, { force: true }).catch(() => {})+ }+}+export async function writeShim(binDir: string,platform: NodeJS.Platform = process.platform,): Promise<void> {- await mkdir(binDir, { recursive: true })- const shim = join(binDir, 'cumora')- await writeFile(shim, CUMORA_SHIM, 'utf8')- await chmod(shim, 0o755)+ try {+ const info = await lstat(binDir)+ if (!info.isDirectory() || info.isSymbolicLink()) {+ throw new Error(`secure BYOA refuses linked shim directory: ${binDir}`)+ }+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err+ await mkdir(binDir, { recursive: true })+ const created = await lstat(binDir)+ if (!created.isDirectory() || created.isSymbolicLink()) {+ throw new Error(`secure BYOA could not create a trusted shim directory: ${binDir}`)+ }+ }+ await writeShimFile(join(binDir, 'cumora'), CUMORA_SHIM, 0o755)+ await writeShimFile(join(binDir, 'cumora-mcp'), CUMORA_MCP_SHIM, 0o755)if (platform === 'win32') {- await writeFile(join(binDir, 'cumora.cmd'), CUMORA_WINDOWS_SHIM, 'utf8')+ await writeShimFile(join(binDir, 'cumora.cmd'), CUMORA_WINDOWS_SHIM, 0o600)}}@@ -991,8 +1362,8 @@ const ENGINE_MODEL_LOCAL = 'local'/** The model the LOCAL engine should run this agent's turns on.*- * BYOA wakes omit `--model` by default so the machine's CLI uses its own- * config (Claude `settings.json`, Codex `config.toml`, …). The daemon+ * BYOA wakes omit `--model` by default so the CLI/account uses its own+ * default. (Secure Codex deliberately ignores user config.) The daemon* discovery list leaves `agent.model` unset; `CUMORA_ENGINE_MODEL=local`* is the same no-pin path. A concrete `CUMORA_ENGINE_MODEL` still overrides.*@@ -1021,14 +1392,16 @@ export function resolveEngineFastModel(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 a valid runtime- * token and the `cumora` shim on PATH, so they go on posting AS the agent+ * does. Without it those children were orphaned: they keep the `cumora` IPC+ * shim on PATH, so they go on posting AS the agent* while the replacement runner independently answers the same messages. */private readonly teardown = new AbortController()private token = ''private tokenExpiresAt = 0private home: stringprivate binDir: string+ private trustedCliDir: string+ private ipcDir: stringprivate sessionFile: stringprivate busy = falseprivate pendingRerun = false@@ -1066,6 +1439,10 @@ class AgentRunner {* the cold start. Null = not yet started, dead (respawn next turn), or this* engine/config has no persistent mode (a custom args override). */private engineSession: EngineSession | null = null+ /** The currently awaited engine operation (persistent send or one-shot run).+ * 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/** 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@@ -1081,6 +1458,9 @@ class AgentRunner {private lastGroupSteerAt = 0private pollTimer: ReturnType<typeof setInterval> | undefinedprivate readonly adapter+ /** Privileged local broker: the engine sees only its IPC directory, while the+ * daemon keeps the short-lived runtime JWT in memory. */+ private cliBroker: RuntimeCliBroker | null = null/** Buffered ledger reporter — collects per-hop usage from the engine and* POSTs to /runtime/llm-calls so the universal llm_calls ledger sees BYOA* trajectory. Created lazily on first use. */@@ -1097,6 +1477,13 @@ class AgentRunner {) {this.home = join(AGENTS_ROOT, agent.id)this.binDir = join(this.home, 'bin')+ // The fixed MCP server runs outside the model sandbox. Its source and the+ // sibling IPC shim therefore live outside the model-writable Agent home.+ this.trustedCliDir = join(CONFIG_DIR, '.runtime-cli-tools', this.agent.id)+ // Keep even the IPC parent outside the model-writable home. Secure Codex is+ // 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.sessionFile = join(SESSIONS_DIR, `${agent.id}.session`)this.adapter = getAdapter(engine)}@@ -1191,13 +1578,19 @@ class AgentRunner {/** Drop the session id AND tear down any persistent engine process so the next* wake spawns a genuinely clean session (no --resume of the bad context). */- private resetEngineSession(reason: string): void {+ private async resetEngineSession(reason: string): Promise<void> {console.warn(`[computer] ${this.agent.id} ${reason} — starting a FRESH engine session next wake`)this.setSessionId(null)- this.engineSession?.stop()+ await this.engineSession?.stop({ force: true })this.engineSession = null}+ private async trackEngineRun(run: Promise<EngineRunResult>): Promise<EngineRunResult> {+ this.activeEngineRun = run+ try { return await run }+ finally { if (this.activeEngineRun === run) this.activeEngineRun = null }+ }+private async persistSessionId(): Promise<void> {try {if (this.sessionId) {@@ -1221,7 +1614,25 @@ class AgentRunner {async start(): Promise<void> {await this.adapter.seedHome(this.home, { id: this.agent.id, name: this.agent.name, role: this.agent.role, systemPrompt: this.agent.systemPrompt })- await writeShim(this.binDir)+ if (allowUnsandboxedByoa()) await writeShim(this.binDir)+ await writeShim(this.trustedCliDir)+ // Versions before the broker stored a live bearer token beside the shim.+ // Remove it before any new engine process can inspect the old home.+ try {+ const bin = await lstat(this.binDir)+ if (!bin.isDirectory() || bin.isSymbolicLink()) {+ throw new Error(`secure BYOA refuses linked legacy shim directory: ${this.binDir}`)+ }+ await rm(join(this.binDir, '.runtime-token'), { force: true })+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err+ }+ this.cliBroker = new RuntimeCliBroker(+ this.ipcDir,+ join(CONFIG_DIR, '.runtime-cli-broker', this.agent.id),+ (argv, signal) => this.invokeRuntimeCli(argv, signal),+ )+ await this.cliBroker.start()await this.loadSessionId()void this.streamLoop()// SSE-independent safety net (see INBOX_POLL_MS): drain the inbox on a slow@@ -1238,10 +1649,12 @@ class AgentRunner {if (this.wakeDebounceTimer) { clearTimeout(this.wakeDebounceTimer); this.wakeDebounceTimer = null }}- stop(options: { forceEngine?: boolean } = {}): void {+ async stop(options: { forceEngine?: boolean } = {}): Promise<void> {this.beginStop()- this.engineSession?.stop({ force: options.forceEngine })+ const session = this.engineSessionthis.engineSession = null+ this.cliBroker?.stop()+ this.cliBroker = null// Kill a one-shot engine child too. sync() tears a runner down on any// config change (engine/model/persona) or unassign while the daemon keeps// running, which is exactly where an orphan does damage: it would still be@@ -1251,6 +1664,10 @@ class AgentRunner {// (e.g. the agent was mid-turn when the daemon restarts for an update).this.hopReporter?.stop()this.hopReporter = null+ await Promise.allSettled([+ session?.stop({ force: options.forceEngine }) ?? Promise.resolve(),+ this.activeEngineRun ?? Promise.resolve(),+ ])}/** Does this runner's live config still match the latest server state? The@@ -1267,22 +1684,56 @@ class AgentRunner {&& this.agent.fastModel === agent.fastModel}- private async ensureToken(): Promise<string> {+ private async ensureToken(signal?: AbortSignal): Promise<string> {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: '{}' },+ { method: 'POST', headers: { Authorization: `Bearer ${this.cfg.deviceToken}` }, body: '{}', signal },)this.token = minted.tokenthis.tokenExpiresAt = Date.now() + minted.expiresInSeconds * 1000- // Persist to the file the cumora shim reads, so a long-lived (persistent) engine- // process always picks up the REFRESHED token rather than its stale spawn-time env.- try { await writeFile(join(this.binDir, '.runtime-token'), this.token, { mode: 0o600 }) } catch { /* shim falls back to the env token */ }return this.token}- /** Env handed to the engine subprocess: the `cumora` shim on PATH, wired to- * this agent's runtime URL + token. */+ /** Execute one shim request outside the model's sandbox. The broker accepts+ * only argv strings; identity, URL, Authorization, redirects, and token+ * refresh remain daemon-owned and cannot be changed by the model. */+ private async invokeRuntimeCli(argv: string[], lifecycleSignal: AbortSignal): Promise<RuntimeCliBrokerResult> {+ const requestAbort = new AbortController()+ const timeout = setTimeout(() => requestAbort.abort(), HTTP_TIMEOUT_MS)+ const onLifecycleAbort = () => requestAbort.abort()+ if (lifecycleSignal.aborted) requestAbort.abort()+ else lifecycleSignal.addEventListener('abort', onLifecycleAbort, { once: true })+ try {+ const token = await this.ensureToken(requestAbort.signal)+ if (requestAbort.signal.aborted) return { exitCode: 70, error: 'runtime IPC request cancelled' }+ const res = await fetch(`${this.cfg.serverUrl}/runtime/cli`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },+ body: JSON.stringify({ argv }),+ signal: requestAbort.signal,+ })+ if (!res.ok) {+ const body = await res.text().catch(() => '')+ return { exitCode: 70, error: `HTTP ${res.status} ${body.slice(0, 200)}`.trim() }+ }+ const data = await res.json() as { text?: unknown; exitCode?: unknown }+ return {+ text: typeof data.text === 'string' ? data.text : '',+ exitCode: typeof data.exitCode === 'number' ? data.exitCode : 0,+ }+ } catch (err) {+ return { exitCode: 70, error: err instanceof Error ? err.message : String(err) }+ } finally {+ clearTimeout(timeout)+ lifecycleSignal.removeEventListener('abort', onLifecycleAbort)+ }+ }++ /** Env handed to the engine subprocess. Secure mode preserves the operator's+ * original PATH so model-writable <home>/bin cannot shadow the engine binary;+ * compatibility mode alone exposes its legacy CLI shim there. No server URL+ * 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 {return resolveEngineModel(this.agent.model, process.env.CUMORA_ENGINE_MODEL)@@ -1296,12 +1747,9 @@ class AgentRunner {private engineEnv(): NodeJS.ProcessEnv {return {...process.env,- PATH: prependAgentBinToPath(this.binDir),- CUMORA_AGENT_RUNTIME_URL: `${this.cfg.serverUrl}/runtime`,- CUMORA_AGENT_RUNTIME_TOKEN: this.token,- // A long-lived engine reads the FRESH token from this file (the env token- // above goes stale on refresh); the shim prefers the file, falls back to env.- CUMORA_AGENT_RUNTIME_TOKEN_FILE: join(this.binDir, '.runtime-token'),+ 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,}}@@ -1853,9 +2301,9 @@ class AgentRunner {const resumeSessionId = this.sessionIdconst session = this.ensureEngineSession()const prompt = this.turnPrompt(session, this.agendaDelta(ag.brief, memoryDigest, roster))- const result = session- ? await session.send(prompt)- : await this.adapter.run({+ const engineRun = session+ ? session.send(prompt)+ : this.adapter.run({home: this.home, prompt, env: this.engineEnv(),model: this.engineModel(), fastModel: this.engineFastModel(),resumeSessionId: this.sessionId, onLog: (line) => this.logEngineLine(line),@@ -1865,6 +2313,7 @@ class AgentRunner {onHopUsage: (r) => this.onEngineHop(r, 'agent-turn'),signal: this.teardown.signal,})+ const result = await this.trackEngineRun(engineRun)if (session?.sessionId) this.setSessionId(session.sessionId)if (session && !session.alive) this.engineSession = nullif (!session && result.sessionId) this.setSessionId(result.sessionId)@@ -1873,7 +2322,7 @@ class AgentRunner {turnModel = result.modelif (result.error) engineError = this.visibleEngineError(exitCode, result.error)if (engineError && this.mustResetSession(engineError, !!resumeSessionId)) {- this.resetEngineSession(this.resetReason(engineError))+ await this.resetEngineSession(this.resetReason(engineError))}} catch (err) {exitCode = 1@@ -2259,7 +2708,7 @@ class AgentRunner {const capture = setInterval(() => { if (session.sessionId) this.setSessionId(session.sessionId) }, 2000)capture.unref?.()try {- result = await session.send(prompt)+ result = await this.trackEngineRun(session.send(prompt))} finally {clearInterval(capture)}@@ -2269,7 +2718,7 @@ class AgentRunner {if (!session.alive) this.engineSession = null} else {// One-shot path: Cursor/OpenCode, Codex fallback, or a custom args override.- result = await this.adapter.run({+ result = await this.trackEngineRun(this.adapter.run({home: this.home,prompt,env: this.engineEnv(),@@ -2279,7 +2728,7 @@ class AgentRunner {onLog: (line) => this.logEngineLine(line),onHopUsage: (r) => this.onEngineHop(r, 'agent-turn'),signal: this.teardown.signal,- })+ }))if (result.sessionId) this.setSessionId(result.sessionId)}exitCode = result.exitCode@@ -2290,7 +2739,7 @@ class AgentRunner {// be carried forward — drop it AND tear down any persistent process so// the next wake starts clean (otherwise --resume re-overflows forever).if (engineError && this.mustResetSession(engineError, !!resumeSessionId)) {- this.resetEngineSession(this.resetReason(engineError))+ await this.resetEngineSession(this.resetReason(engineError))}} catch (err) {console.error(`[computer] ${this.agent.id} engine spawn failed:`, err instanceof Error ? err.message : err)@@ -2494,6 +2943,17 @@ function installTimestampedLogging(): void {async function doRun(serverOverride?: string): Promise<void> {installTimestampedLogging()+ if (allowUnsandboxedByoa()) {+ console.warn('[computer] SECURITY WARNING: CUMORA_BYOA_ALLOW_UNSANDBOXED=1 — local model engines may read host files, inherit credentials, and use the network')+ } else {+ for (const name of [+ 'CUMORA_CLAUDE_ARGS', 'CUMORA_CODEX_ARGS', 'CUMORA_GROK_ARGS',+ 'CUMORA_CURSOR_ARGS', 'CUMORA_OPENCODE_ARGS', 'CUMORA_PI_ARGS',+ 'CUMORA_GEMINI_ARGS', 'CUMORA_TRIAGE_ARGS',+ ]) {+ if (process.env[name]) console.warn(`[computer] ignoring ${name}: custom engine argv requires CUMORA_BYOA_ALLOW_UNSANDBOXED=1`)+ }+ }// Global safety net: a long-running daemon hosting every one of the user's// agents must NOT die because one async path threw — a transient 502 from a// server pod rolling, a network blip, a malformed event. Node ≥15 turns an@@ -2538,7 +2998,7 @@ async function doRun(serverOverride?: string): Promise<void> {const runners = new Map<string, AgentRunner>()- const sync = async (): Promise<void> => {+ const syncOnce = async (): Promise<void> => {let agents: AgentInfo[]try {agents = await api<AgentInfo[]>(cfg.serverUrl, '/api/computers/me/agents', {@@ -2558,8 +3018,8 @@ async function doRun(serverOverride?: string): Promise<void> {const existing = runners.get(agent.id)if (existing) {console.log(`[computer] no installed engine remains for ${agent.name} (${agent.id}) → stopping runner`)- existing.stop()runners.delete(agent.id)+ await existing.stop({ forceEngine: true })}continue}@@ -2569,8 +3029,8 @@ async function doRun(serverOverride?: string): Promise<void> {// 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}`)- existing.stop()runners.delete(agent.id)+ await existing.stop({ forceEngine: true })}const runner = new AgentRunner(cfg, agent, engine)runners.set(agent.id, runner)@@ -2580,12 +3040,29 @@ async function doRun(serverOverride?: string): Promise<void> {// Agents removed from this computer: stop their runners.const live = new Set(agents.map((a) => a.id))for (const [id, runner] of runners) {- if (!live.has(id)) { runner.stop(); runners.delete(id) }+ if (!live.has(id)) {+ runners.delete(id)+ await runner.stop({ forceEngine: true })+ }}}+ // Poll ticks and reconnects can overlap. Serialize reconciliation so a later+ // pass cannot create a replacement while the prior pass is still awaiting+ // termination of that Agent's old process tree.+ let syncInFlight: Promise<void> | null = null+ const sync = (): Promise<void> => {+ if (syncInFlight) return syncInFlight+ const running = syncOnce().finally(() => {+ if (syncInFlight === running) syncInFlight = null+ })+ syncInFlight = running+ return running+ }+// Last snapshot we successfully described to the server, as a JSON fingerprint.let lastEngineSnapshot = ''+ let lastCapabilityWarning = ''// Engines this machine can currently run, re-scanned on a slow timer. Reported// on every heartbeat so installing another supported CLI takes effect without@@ -2595,7 +3072,13 @@ async function doRun(serverOverride?: string): Promise<void> {try {const detected = await detectEnginesWithStatus()if (!detected.reliable) return // broken `which` / `where` — keep the last good list- const next = detected.engines+ const evaluated = await evaluateRunnableEngines(detected.engines)+ const next = evaluated.runnable+ const capabilityWarning = evaluated.blocked.map(({ id, reason }) => `${id} (${reason})`).join('; ')+ if (capabilityWarning !== lastCapabilityWarning) {+ lastCapabilityWarning = capabilityWarning+ if (capabilityWarning) console.warn(`[computer] secure engine(s) disabled: ${capabilityWarning}`)+ }const previous = engineInventory.currentconst changed = replaceEngineInventory(engineInventory, next)if (changed) {@@ -2686,7 +3169,7 @@ async function doRun(serverOverride?: string): Promise<void> {while (anyBusy() && Date.now() < deadline) await new Promise((r) => setTimeout(r, 500))// process.exit() follows immediately, so engine-specific delayed fallbacks// cannot run. Force each child to receive its termination signal first.- for (const runner of runners.values()) runner.stop({ forceEngine: true })+ await Promise.all([...runners.values()].map((runner) => runner.stop({ forceEngine: true })))console.log(`[computer] shutting down (${why})`)process.exit(0)}diff --git a/server/src/agents/computer/engine.ts b/server/src/agents/computer/engine.tsindex 919980b..5c45c68 100644--- a/server/src/agents/computer/engine.ts+++ b/server/src/agents/computer/engine.ts@@ -5,30 +5,32 @@* on the user's machine: Claude Code, Codex, Grok Build, Cursor Agent,* OpenCode, or pi. The daemon (daemon.ts) hands* each wake to an adapter, which spawns the engine headlessly in the agent's- * isolated home directory. The engine reads its persona + memory + skills+ * dedicated home directory. The engine reads its persona + memory + skills* from that home natively (CLAUDE.md / AGENTS.md, .claude/skills, …) and acts- * on Cumora through the `cumora` shim the daemon puts on its PATH.+ * on Cumora through a fixed MCP bridge. The historical PATH shim remains only+ * in explicitly unsandboxed compatibility mode.** This module is intentionally standalone — only Node builtins — so the* daemon can run on a machine with no Cumora DB/Redis access.** NOTE on engine flags: the exact non-interactive / permission flags differ- * across engine versions. We pick sensible defaults for an isolated,- * user-owned runner and let the user override via env+ * across engine versions. Claude and Codex run with fail-closed host boundaries+ * by default. Engines without a verified boundary, and opaque argv overrides,+ * require the explicit CUMORA_BYOA_ALLOW_UNSANDBOXED=1 compatibility opt-in* (CUMORA_CLAUDE_ARGS / CUMORA_CODEX_ARGS / CUMORA_GROK_ARGS /* CUMORA_CURSOR_ARGS / CUMORA_OPENCODE_ARGS / CUMORA_PI_ARGS, space-split). Correctness of the* loop does not depend on the structured output — the agent acts via the* `cumora` tool regardless of how we parse stdout.*/-import { spawn as nodeSpawn, execFileSync, type ChildProcess, type SpawnOptions } from 'node:child_process'+import { type ChildProcess, execFile, execFileSync, spawn as nodeSpawn, type SpawnOptions } from 'node:child_process'import { randomUUID } from 'node:crypto'-import { mkdir, writeFile, access, mkdtemp, rename } from 'node:fs/promises'-import { existsSync, writeFileSync } from 'node:fs'+import { existsSync, renameSync, rmSync, writeFileSync } from 'node:fs'+import { access, lstat, mkdir, mkdtemp, rename, rm, writeFile } from 'node:fs/promises'import { homedir, tmpdir } from 'node:os'-import { join, delimiter as PATH_DELIMITER } from 'node:path'+import { dirname, join, delimiter as PATH_DELIMITER } from 'node:path'import { StringDecoder } from 'node:string_decoder'import { stripLoneSurrogates } from '../text-safety.js'-import { probeEngineVersion } from './cli-version.js'+import { isCliVersionAtLeast, probeEngineVersion, probeLocalEngineVersion } from './cli-version.js'const IS_WIN = process.platform === 'win32'@@ -48,6 +50,210 @@ function spawn(command: string, args: string[], options: SpawnOptions = {}): Chireturn nodeSpawn(command, args, headlessSpawnOptions(options))}+/** Model tools may spawn descendants that outlive the CLI parent. Put every+ * engine process in its own POSIX process group, and terminate the complete+ * tree on cancellation. Windows has no process-group signal equivalent, so+ * taskkill /T supplies the platform's tree semantics. */+function spawnEngineChild(command: string, args: string[], options: SpawnOptions = {}): ChildProcess {+ return spawn(command, args, { ...options, detached: !IS_WIN })+}++interface EngineTerminationState {+ forceRequested: boolean+ promise: Promise<void>+}++const engineTerminations = new WeakMap<ChildProcess, EngineTerminationState>()++function childHasExited(child: ChildProcess): boolean {+ return child.exitCode !== null || child.signalCode !== null+}++function waitForChildExit(child: ChildProcess, timeoutMs: number): Promise<boolean> {+ if (childHasExited(child)) return Promise.resolve(true)+ return new Promise((resolve) => {+ let settled = false+ const finish = (exited: boolean) => {+ if (settled) return+ settled = true+ clearTimeout(timer)+ child.off('close', onClose)+ child.off('error', onClose)+ resolve(exited)+ }+ const onClose = () => finish(true)+ const timer = setTimeout(() => finish(childHasExited(child)), timeoutMs)+ timer.unref?.()+ child.once('close', onClose)+ child.once('error', onClose)+ })+}++function readProcessTable(): Promise<Map<number, number>> {+ return new Promise((resolve) => {+ execFile('ps', ['-axo', 'pid=,ppid='], { encoding: 'utf8', maxBuffer: 8 * 1024 * 1024 }, (err, stdout) => {+ const table = new Map<number, number>()+ if (!err) {+ for (const line of stdout.split('\n')) {+ const match = line.trim().match(/^(\d+)\s+(\d+)$/)+ if (match) table.set(Number(match[1]), Number(match[2]))+ }+ }+ resolve(table)+ })+ })+}++function expandDescendants(tracked: Set<number>, table: ReadonlyMap<number, number>): void {+ let changed = true+ while (changed) {+ changed = false+ for (const [pid, parent] of table) {+ if (!tracked.has(pid) && tracked.has(parent)) {+ tracked.add(pid)+ changed = true+ }+ }+ }+}++function signalPid(pid: number, signal: NodeJS.Signals): void {+ try { process.kill(pid, signal) } catch { /* process already exited */ }+}++function anyPidAlive(pids: ReadonlySet<number>): boolean {+ for (const pid of pids) {+ try {+ process.kill(pid, 0)+ return true+ } catch { /* process is gone */ }+ }+ return false+}++function signalProcessGroup(child: ChildProcess, signal: NodeJS.Signals): void {+ const pid = child.pid+ if (!pid) {+ try { child.kill(signal) } catch { /* already gone */ }+ return+ }+ try { process.kill(-pid, signal) }+ catch { try { child.kill(signal) } catch { /* already gone */ } }+}++async function terminateWindowsTree(child: ChildProcess): Promise<void> {+ const pid = child.pid+ if (!pid) return+ await new Promise<void>((resolve) => {+ execFile(+ 'taskkill.exe', ['/pid', String(pid), '/t', '/f'],+ headlessSpawnOptions({ windowsHide: true }),+ (err) => {+ if (err && !childHasExited(child)) {+ try { child.kill('SIGKILL') } catch { /* already gone */ }+ }+ resolve()+ },+ )+ })+ await waitForChildExit(child, 1_500)+}++async function terminatePosixTree(+ child: ChildProcess,+ state: EngineTerminationState,+): Promise<void> {+ const rootPid = child.pid+ if (!rootPid) return+ const tracked = new Set<number>([rootPid])++ // Snapshot before signalling the group. A child may deliberately call+ // setsid()/setpgid() and escape the engine's PGID while retaining the engine+ // as its parent; explicit descendant signals cover that case.+ expandDescendants(tracked, await readProcessTable())+ const initialSignal: NodeJS.Signals = state.forceRequested ? 'SIGKILL' : 'SIGTERM'+ for (const pid of [...tracked].reverse()) signalPid(pid, initialSignal)+ signalProcessGroup(child, initialSignal)++ if (!state.forceRequested) {+ await waitForChildExit(child, 1_000)+ // The engine parent may exit promptly while a detached descendant ignores+ // SIGTERM. Do not mistake the parent's close event for completion of the+ // previously discovered tree.+ if (!anyPidAlive(tracked)) return+ }++ // Re-scan before escalating. Descendants recorded in `tracked` stay targets+ // even if their parent exits and init adopts them between scans.+ expandDescendants(tracked, await readProcessTable())+ for (const pid of [...tracked].reverse()) signalPid(pid, 'SIGKILL')+ signalProcessGroup(child, 'SIGKILL')++ // A terminating process can race one final fork with the first snapshot.+ // Bounded rescans catch descendants of every still-known PID without turning+ // shutdown into an unbounded wait or signalling unrelated processes later.+ for (let attempt = 0; attempt < 4; attempt += 1) {+ await new Promise((resolve) => setTimeout(resolve, 25))+ expandDescendants(tracked, await readProcessTable())+ let survivor = false+ for (const pid of tracked) {+ try {+ process.kill(pid, 0)+ survivor = true+ signalPid(pid, 'SIGKILL')+ } catch { /* process is gone */ }+ }+ if (!survivor) break+ }+ // Wait for killed PIDs to disappear from the process table (including a+ // briefly reparented zombie). `stop()` must not resolve while a known old+ // descendant can still run beside the replacement runner.+ for (let attempt = 0; attempt < 40 && anyPidAlive(tracked); attempt += 1) {+ for (const pid of tracked) signalPid(pid, 'SIGKILL')+ await new Promise((resolve) => setTimeout(resolve, 25))+ }+ await waitForChildExit(child, 1_500)+}++/** Terminate an engine and wait for the platform's tree operation to finish.+ * Calls are idempotent; a later force request escalates an in-progress graceful+ * stop. Runner replacement awaits this promise before reseeding model-writable+ * state or launching the next engine. */+function terminateEngineTree(child: ChildProcess, force = false): Promise<void> {+ const current = engineTerminations.get(child)+ if (current) {+ if (force) current.forceRequested = true+ return current.promise+ }+ const state: EngineTerminationState = { forceRequested: force, promise: Promise.resolve() }+ state.promise = (IS_WIN ? terminateWindowsTree(child) : terminatePosixTree(child, state))+ .catch(() => {+ try { child.kill('SIGKILL') } catch { /* already gone */ }+ })+ engineTerminations.set(child, state)+ return state.promise+}++/** Bind an AbortSignal to one engine child and retain the exact termination+ * promise. One-shot helpers must await `wait()` before resolving an aborted+ * operation; otherwise AgentRunner's active-run barrier can finish while the+ * platform tree terminator is still working. */+function bindAbortTermination(+ child: ChildProcess,+ signal: AbortSignal,+): { dispose: () => void; wait: () => Promise<void> } {+ let termination: Promise<void> | null = null+ const onAbort = (): void => {+ if (!termination) termination = terminateEngineTree(child, true)+ }+ signal.addEventListener('abort', onAbort, { once: true })+ if (signal.aborted) onAbort()+ return {+ dispose: () => signal.removeEventListener('abort', onAbort),+ wait: () => termination ?? Promise.resolve(),+ }+}+// Optional last-resort cap on a single persistent-engine turn. DEFAULT OFF (0):// a wall-clock timeout CANNOT tell a genuinely-hung turn from a legitimately// long-running one (e.g. an agent running a multi-hour Bash command blocks this@@ -116,6 +322,89 @@ export type EngineId = 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode' | 'pi/** The pairable engine ids, in the daemon's default detection order. */export const ENGINE_IDS: EngineId[] = ['claude', 'codex', 'grok', 'cursor', 'opencode', 'pi', 'gemini']+/** Engines for which Cumora can impose a fail-closed filesystem + tool-network+ * boundary non-interactively. The remaining adapters still work for operators+ * who explicitly accept host-level execution, but are never selected merely+ * because their binary happens to be on PATH. */+export const SANDBOXED_ENGINE_IDS: readonly EngineId[] = ['claude', 'codex']+export const ALLOW_UNSANDBOXED_BYOA_ENV = 'CUMORA_BYOA_ALLOW_UNSANDBOXED'+export const SECURE_ENGINE_MIN_VERSIONS: Readonly<Partial<Record<EngineId, string>>> = {+ // --restricted first shipped here; it is what ignores user/project settings+ // and confines built-in file tools to the Agent working directory.+ claude: '2.1.248',+ // Permission profiles (default_permissions / permissions.*) are supported+ // starting with this Codex release.+ codex: '0.138.0',+}++export function allowUnsandboxedByoa(env: NodeJS.ProcessEnv = process.env): boolean {+ return env[ALLOW_UNSANDBOXED_BYOA_ENV] === '1'+}++export function runnableEngineIds(+ installed: readonly EngineId[],+ env: NodeJS.ProcessEnv = process.env,+ platform: NodeJS.Platform = process.platform,+): EngineId[] {+ if (allowUnsandboxedByoa(env)) return [...installed]+ const safe = new Set(SANDBOXED_ENGINE_IDS)+ return installed.filter((id) => safe.has(id) && !(platform === 'win32' && id === 'claude'))+}++export interface RunnableEngineEvaluation {+ runnable: EngineId[]+ blocked: Array<{ id: EngineId; reason: string }>+}++export function secureEngineCapabilityReason(+ id: EngineId,+ version: string | null,+ platform: NodeJS.Platform,+ linuxSandboxDeps: { bwrap: boolean; socat: boolean } = { bwrap: true, socat: true },+): string | null {+ const minimum = SECURE_ENGINE_MIN_VERSIONS[id]+ if (!minimum || !isCliVersionAtLeast(version, minimum)) {+ return version+ ? `version ${version} is older than the secure minimum ${minimum ?? 'unknown'}`+ : `could not verify the installed version (secure minimum ${minimum ?? 'unknown'})`+ }+ if (id === 'claude' && platform === 'linux' && (!linuxSandboxDeps.bwrap || !linuxSandboxDeps.socat)) {+ const missing = [!linuxSandboxDeps.bwrap && 'bubblewrap (bwrap)', !linuxSandboxDeps.socat && 'socat'].filter(Boolean).join(', ')+ return `missing sandbox dependency: ${missing}`+ }+ return null+}++/** Fail-closed capability check layered on top of the static engine allowlist.+ * Merely having a binary named `claude` or `codex` is insufficient: older+ * releases silently ignore the exact boundary controls Cumora depends on. */+export async function evaluateRunnableEngines(+ installed: readonly EngineId[],+ env: NodeJS.ProcessEnv = process.env,+ platform: NodeJS.Platform = process.platform,+): Promise<RunnableEngineEvaluation> {+ const candidates = runnableEngineIds(installed, env, platform)+ if (allowUnsandboxedByoa(env)) return { runnable: candidates, blocked: [] }++ const snapshot = await snapshotDetectedEngines(candidates)+ const versions = new Map<EngineId, string | null>(await Promise.all(snapshot.map(async (entry) => [+ entry.id,+ await probeLocalEngineVersion(entry.id, entry.path),+ ] as const)))+ const linuxSandboxDeps = platform === 'linux'+ ? { bwrap: await binOnPath('bwrap'), socat: await binOnPath('socat') }+ : { bwrap: true, socat: true }+ const runnable: EngineId[] = []+ const blocked: RunnableEngineEvaluation['blocked'] = []+ for (const id of candidates) {+ const version = versions.get(id) ?? null+ const reason = secureEngineCapabilityReason(id, version, platform, linuxSandboxDeps)+ if (reason) { blocked.push({ id, reason }); continue }+ runnable.push(id)+ }+ return { runnable, blocked }+}+export interface EnginePersona {id: stringname: string@@ -124,7 +413,7 @@ export interface EnginePersona {}export interface EngineRunArgs {- /** Agent's isolated home dir; becomes the engine's cwd. */+ /** Agent's dedicated home dir; becomes the engine's cwd and secure sandbox root. */home: string/** The per-wake trigger prompt. */prompt: string@@ -318,7 +607,7 @@ export interface EngineSession {/** Tear the process down (daemon shutdown / unrecoverable error). `force`* skips any engine-specific graceful-exit delay when this daemon process is* itself about to exit. */- stop(options?: { force?: boolean }): void+ stop(options?: { force?: boolean }): Promise<void>}export interface EngineAdapter {@@ -376,22 +665,84 @@ async function exists(p: string): Promise<boolean> {try { await access(p); return true } catch { return false }}+async function ensureAgentDirectory(path: string, recursive = false): Promise<void> {+ try {+ const info = await lstat(path)+ if (!info.isDirectory() || info.isSymbolicLink()) {+ throw new Error(`secure BYOA refuses non-directory or linked path: ${path}`)+ }+ return+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err+ }+ await mkdir(path, { recursive })+ const created = await lstat(path)+ if (!created.isDirectory() || created.isSymbolicLink()) {+ throw new Error(`secure BYOA could not create a trusted directory: ${path}`)+ }+}++/** Replace a daemon-owned file without following an attacker-planted final+ * symlink. The random staging file and target share a verified parent, so the+ * final rename swaps the directory entry itself rather than opening its target. */+async function atomicAgentWrite(path: string, data: string): Promise<void> {+ const parent = dirname(path)+ const staged = join(parent, `.cumora-${process.pid}-${randomUUID()}.tmp`)+ await writeFile(staged, data, { encoding: 'utf8', mode: 0o600, flag: 'wx' })+ try {+ try { await rename(staged, path) }+ catch (err) {+ if (!IS_WIN || !['EEXIST', 'EPERM'].includes((err as NodeJS.ErrnoException).code ?? '')) throw err+ await rm(path, { force: true })+ await rename(staged, path)+ }+ } finally {+ await rm(staged, { force: true }).catch(() => {})+ }+}++function atomicAgentWriteSync(path: string, data: string): void {+ const parent = dirname(path)+ const staged = join(parent, `.cumora-${process.pid}-${randomUUID()}.tmp`)+ writeFileSync(staged, data, { encoding: 'utf8', mode: 0o600, flag: 'wx' })+ try {+ try { renameSync(staged, path) }+ catch (err) {+ if (!IS_WIN || !['EEXIST', 'EPERM'].includes((err as NodeJS.ErrnoException).code ?? '')) throw err+ rmSync(path, { force: true })+ renameSync(staged, path)+ }+ } finally {+ rmSync(staged, { force: true })+ }+}+async function ensureCommonHome(home: string): Promise<void> {- await mkdir(join(home, 'memory'), { recursive: true })- await mkdir(join(home, 'notes'), { recursive: true })- await mkdir(join(home, 'workspace'), { recursive: true })+ await ensureAgentDirectory(home, true)+ await ensureAgentDirectory(join(home, 'memory'))+ await ensureAgentDirectory(join(home, 'notes'))+ await ensureAgentDirectory(join(home, 'workspace'))// Seed a memory index so "read memory/MEMORY.md to recall" always has a// target, and the agent has a concrete place to append pointers. Only when// absent — never clobber what the agent has written.const memoryIndex = join(home, 'memory', 'MEMORY.md')- if (!(await exists(memoryIndex))) {- await writeFile(+ let seedMemoryIndex = false+ try {+ const info = await lstat(memoryIndex)+ if (!info.isFile() || info.isSymbolicLink()) {+ throw new Error(`secure BYOA refuses non-file or linked memory index: ${memoryIndex}`)+ }+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err+ seedMemoryIndex = true+ }+ if (seedMemoryIndex) {+ await atomicAgentWrite(memoryIndex,'# Memory index\n\n' +'One line per durable fact, pointing at the file that holds it:\n' +'`- [Title](file.md) — one-line hook`\n\n' +'Write the fact itself in its own `memory/<topic>.md` file; keep this index short.\n',- 'utf8',)}}@@ -485,7 +836,7 @@ function spawnEngine(spawnOpts: { shell?: boolean; stdinText?: string; onStdoutLine?: (line: string) => void } = {},): Promise<EngineRunResult> {return new Promise((resolve, reject) => {- const child = spawn(bin, args, {+ const child = spawnEngineChild(bin, args, {cwd: home, env,stdio: [spawnOpts.stdinText != null ? 'pipe' : 'ignore', 'pipe', 'pipe'],shell: spawnOpts.shell ?? false,@@ -493,13 +844,9 @@ function spawnEngine(if (spawnOpts.stdinText != null) {writeStdin(child, spawnOpts.stdinText, { end: true })}- const onAbort = (): void => { child.kill('SIGTERM') }- signal.addEventListener('abort', onAbort, { once: true })- // A listener registered AFTER the abort event never fires. A turn that was- // still queued behind the concurrency gate when its runner was stopped would- // otherwise spawn a child nothing owns — with a live runtime token and the- // `cumora` shim on PATH.- if (signal.aborted) onAbort()+ // Retain the platform tree-termination promise. A listener registered after+ // abort would never fire, so bindAbortTermination also closes that race.+ const abort = bindAbortTermination(child, signal)const stderrTail: string[] = []const stdoutTail: string[] = []@@ -568,14 +915,20 @@ function spawnEngine(onLog(cleaned)}}+ let settled = falsechild.stdout?.on('data', (buf: Buffer) => pump('stdout', buf))child.stderr?.on('data', (buf: Buffer) => pump('stderr', buf))- child.on('error', (err) => { signal.removeEventListener('abort', onAbort); reject(err) })- let settled = false- const settle = (code: number | null, signalName: NodeJS.Signals | null): void => {+ child.on('error', (err) => {+ if (settled) return+ settled = true+ abort.dispose()+ void abort.wait().then(() => reject(err))+ })+ const settle = async (code: number | null, signalName: NodeJS.Signals | null): Promise<void> => {if (settled) returnsettled = true- signal.removeEventListener('abort', onAbort)+ abort.dispose()+ await abort.wait()const exitCode = code ?? (signalName ? 128 : 1)resolve({exitCode,@@ -590,7 +943,7 @@ function spawnEngine(// usually the last line, and it carries the turn's usage.child.on('close', (code, signalName) => {if (!settled) { pump('stdout', null); pump('stderr', null) }- settle(code, signalName)+ void settle(code, signalName)})// Torn-down end: 'close' waits for every inherited stdio pipe to reach EOF,// and the engine's OWN children (Bash tool commands) hold those pipes — a@@ -599,7 +952,7 @@ function spawnEngine(// remaining output is moot, so settle on 'exit' instead. Without this the// daemon's shutdown drain waits forever on a turn it already killed, and// `busy` plus the big-brain slot are never released.- child.on('exit', (code, signalName) => { if (signal.aborted) settle(code, signalName) })+ child.on('exit', (code, signalName) => { if (signal.aborted) void settle(code, signalName) })})}@@ -611,7 +964,7 @@ function spawnCapture({ cwd, env, signal, onLog, shell, stdinText }: { cwd: string; env: NodeJS.ProcessEnv; signal: AbortSignal; onLog?: (line: string) => void; shell?: boolean; stdinText?: string },): Promise<EngineClassifyResult> {return new Promise((resolve) => {- const child = spawn(bin, args, {+ const child = spawnEngineChild(bin, args, {cwd, env,stdio: [stdinText != null ? 'pipe' : 'ignore', 'pipe', 'pipe'],shell: shell ?? false,@@ -619,22 +972,30 @@ function spawnCapture(if (stdinText != null) {writeStdin(child, stdinText, { end: true })}- const onAbort = (): void => { child.kill('SIGTERM') }- signal.addEventListener('abort', onAbort, { once: true })+ const abort = bindAbortTermination(child, signal)let stdout = ''const stderrTail: string[] = []+ let settled = falsechild.stdout?.on('data', (buf: Buffer) => { stdout += buf.toString('utf8'); onLog?.(cleanLine(buf.toString('utf8'))) })child.stderr?.on('data', (buf: Buffer) => { for (const l of buf.toString('utf8').split('\n')) pushTail(stderrTail, cleanLine(l)) })child.on('error', (err) => {- signal.removeEventListener('abort', onAbort)- resolve({ text: '', error: err instanceof Error ? err.message : String(err) })+ if (settled) return+ settled = true+ abort.dispose()+ void abort.wait().then(() => {+ resolve({ text: '', error: err instanceof Error ? err.message : String(err) })+ })})child.on('close', (code, signalName) => {- signal.removeEventListener('abort', onAbort)- const exitCode = code ?? (signalName ? 128 : 1)- resolve({- text: stdout.replace(ANSI_RE, '').trim(),- error: exitCode === 0 ? undefined : failurePreview({ exitCode, signalName, stderr: stderrTail, stdout: [] }),+ if (settled) return+ settled = true+ abort.dispose()+ void abort.wait().then(() => {+ const exitCode = code ?? (signalName ? 128 : 1)+ resolve({+ text: stdout.replace(ANSI_RE, '').trim(),+ error: exitCode === 0 ? undefined : failurePreview({ exitCode, signalName, stderr: stderrTail, stdout: [] }),+ })})})})@@ -652,6 +1013,13 @@ function extraArgs(envVar: string): string[] {return raw ? raw.split(/\s+/).filter(Boolean) : []}+/** Whole-argv overrides are intentionally an unsafe escape hatch: Cumora+ * cannot prove that an opaque flag set preserves its sandbox. Ignore them in+ * the secure default mode; the daemon logs the opt-in requirement at startup. */+function unsafeEngineArgs(envVar: string): string[] {+ return allowUnsandboxedByoa() ? extraArgs(envVar) : []+}+const PERSONA_HEADER = (p: EnginePersona,opts: { personaFile?: string; skillsDir?: string } = {},@@ -685,13 +1053,17 @@ const PERSONA_HEADER = (` people see what you post there.\n` +`- If a task seems to need something outside your home, ask in Cumora first;\n` +` don't go fetch it on your own.\n\n` +- `When you act in Cumora, use the \`cumora\` command-line tool (already on your\n` +- `PATH). Key commands:\n` ++ `When you act in Cumora, use the \`cumora\` interface. Secure Claude and Codex\n` ++ `expose it as the structured \`mcp__cumora__cli\` tool (pass command words in its\n` ++ `\`argv\` array); compatibility engines expose the command-line tool on PATH.\n` ++ `Key commands:\n` +`- \`cumora inbox\` — unread messages across your conversations\n` +`- \`cumora messages <conversationId> --tail 30\` — read a conversation\n` +`- \`cumora reply <conversationId> '<text>'\` — post a message (SINGLE quotes;\n` +` for anything with backticks, code, $, quotes, or newlines, write it to a file\n` +- ` and use \`cumora reply <conversationId> --file <path>\` so the shell can't mangle it)\n` ++ ` and use \`cumora reply <conversationId> --file <path>\` in command-line mode.\n` ++ ` In the structured MCP tool, put the complete text directly in one argv item;\n` ++ ` local \`--file\` and \`--stdin\` flags are intentionally unavailable.)\n` +`- \`cumora contacts [<query>]\` — your teammates + humans, each with their role/function\n` +` (search by name or role, e.g. \`cumora contacts designer\`). Use it when someone asks\n` +` about a person or role you don't already know.\n` +@@ -739,7 +1111,7 @@ class ClaudeSession implements EngineSession {// .cmd shim runs (Node can't spawn it with shell:false). The prompt already// travels via stdin (stream-json), so no arg-quoting concerns here.const { command, shell } = resolveSpawn(bin)- this.child = spawn(command, args, { cwd: opts.home, env: opts.env, stdio: ['pipe', 'pipe', 'pipe'], shell })+ this.child = spawnEngineChild(command, args, { cwd: opts.home, env: opts.env, stdio: ['pipe', 'pipe', 'pipe'], shell })this.child.stdout?.on('data', (b: Buffer) => this.onStdout(b))this.child.stderr?.on('data', (b: Buffer) => this.onStderr(b))this.child.on('error', (err) => this.die(1, err.message))@@ -778,10 +1150,10 @@ class ClaudeSession implements EngineSession {})}- stop(): void {+ stop(options: { force?: boolean } = {}): Promise<void> {this.exited = truetry { this.child.stdin?.end() } catch { /* ignore */ }- try { this.child.kill('SIGTERM') } catch { /* ignore */ }+ return terminateEngineTree(this.child, options.force)}/** Same-turn STEERING: queue a message to inject into the@@ -911,6 +1283,84 @@ class ClaudeSession implements EngineSession {}}+const TOOL_ENV_ALLOWLIST = new Set([+ 'PATH', 'HOME', 'USER', 'LOGNAME', 'SHELL', 'TMPDIR', 'TMP', 'TEMP',+ 'LANG', 'LANGUAGE', 'TERM', 'COLORTERM', 'NO_COLOR',+ 'CUMORA_AGENT_IPC_DIR', 'CUMORA_AGENT_ID',+ 'SYSTEMROOT', 'COMSPEC', 'PATHEXT', 'WINDIR',+])++function claudeSecureSettings(agentHome: string, env: NodeJS.ProcessEnv): string {+ const deniedEnv = Object.keys(env)+ .filter((name) => !TOOL_ENV_ALLOWLIST.has(name.toUpperCase()) && !name.toUpperCase().startsWith('LC_'))+ .sort()+ .map((name) => ({ name, mode: 'deny' }))+ // Claude's command sandbox is write-restricted but read-permissive by+ // default. Deny user/application data roots, then carve back only this+ // agent's workspace and executable lookup directories. System runtime paths+ // (/bin, /usr, /lib, /System) stay readable so the shim can launch.+ const denyRead = process.platform === 'darwin'+ ? ['~/', '/Users', '/Volumes']+ : ['~/', '/home', '/root', '/mnt', '/media', '/run', '/proc', '/sys', '/srv', '/var/lib', '/var/log']+ const pathDirs = (env.PATH ?? '')+ .split(PATH_DELIMITER)+ .filter(Boolean)+ pathDirs.push(dirname(process.execPath))+ const allowRead = [...new Set([agentHome, ...pathDirs])]+ return JSON.stringify({+ permissions: {+ defaultMode: 'dontAsk',+ // 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'],+ // 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'],+ },+ sandbox: {+ enabled: true,+ failIfUnavailable: true,+ allowUnsandboxedCommands: false,+ autoAllowBashIfSandboxed: true,+ filesystem: {+ denyRead,+ allowRead,+ },+ network: { allowedDomains: [], strictAllowlist: true },+ credentials: { envVars: deniedEnv },+ },+ })+}++function claudeSecureMcpConfig(env: NodeJS.ProcessEnv): string {+ const mcpShim = env.CUMORA_AGENT_MCP_SHIM+ if (!mcpShim) throw new Error('secure Cumora MCP bridge is not configured')+ return JSON.stringify({+ mcpServers: {+ cumora: {+ command: process.execPath,+ args: [mcpShim],+ env: {+ CUMORA_AGENT_IPC_DIR: env.CUMORA_AGENT_IPC_DIR ?? '',+ },+ },+ },+ })+}++function claudeSecureFlags(agentHome: string, env: NodeJS.ProcessEnv): string[] {+ return [+ '--restricted',+ '--permission-mode', 'dontAsk',+ '--tools', 'Read,Write,Edit,Glob,Grep,mcp__cumora__cli',+ '--disallowedTools', 'Bash,PowerShell,WebFetch,WebSearch',+ '--settings', claudeSecureSettings(agentHome, env),+ '--mcp-config', claudeSecureMcpConfig(env),+ '--strict-mcp-config',+ ]+}+class ClaudeAdapter implements EngineAdapter {readonly id = 'claude' as constreadonly bin = 'claude'@@ -924,7 +1374,7 @@ class ClaudeAdapter implements EngineAdapter {// --output-format json wraps the reply in a result envelope that ALSO carries// token usage (incl. cache_read/cache_creation) → we unwrap `.result` as the// text and pass `.usage` up for the triage cost ledger.- const flags = extraArgs('CUMORA_TRIAGE_ARGS')+ const flags = unsafeEngineArgs('CUMORA_TRIAGE_ARGS')const model = ['--model', args.model || 'haiku']const { command, shell, wantsStdinPrompt } = resolveSpawn(this.bin)const usingJson = flags.length === 0@@ -934,7 +1384,9 @@ class ClaudeAdapter implements EngineAdapter {// before (unchanged).const base = flags.length? [...flags, '-p']- : ['-p', ...model, '--output-format', 'json', '--dangerously-skip-permissions', '--strict-mcp-config']+ : allowUnsandboxedByoa()+ ? ['-p', ...model, '--output-format', 'json', '--dangerously-skip-permissions', '--strict-mcp-config']+ : ['-p', ...model, '--output-format', 'json', '--restricted', '--tools', '', '--strict-mcp-config']const argv = wantsStdinPrompt ? base : (flags.length ? [...base, args.prompt] : ['-p', args.prompt, ...base.slice(1)])const res = await spawnCapture(command, argv, {cwd: args.cwd,@@ -963,7 +1415,9 @@ class ClaudeAdapter implements EngineAdapter {// and that tier is authed/has quota, with NO tools/MCP/persona.const model = args.tier === 'small' ? ['--model', triageModel('haiku')] : []const { command, shell, wantsStdinPrompt } = resolveSpawn(this.bin)- const base = ['-p', ...model, '--output-format', 'text', '--dangerously-skip-permissions', '--strict-mcp-config']+ const base = allowUnsandboxedByoa()+ ? ['-p', ...model, '--output-format', 'text', '--dangerously-skip-permissions', '--strict-mcp-config']+ : ['-p', ...model, '--output-format', 'text', '--restricted', '--tools', '', '--strict-mcp-config']const argv = wantsStdinPrompt ? base : ['-p', DOCTOR_PROMPT, ...base.slice(1)]return spawnCapture(command, argv, {cwd: args.cwd,@@ -978,7 +1432,7 @@ class ClaudeAdapter implements EngineAdapter {// Skipped when a CUMORA_CLAUDE_ARGS override is set — startSession() returns// null then, so the wake collapses to run() / one-shot exec, which probe()// already covers. The honest signal here is just "redundant".- if (extraArgs('CUMORA_CLAUDE_ARGS').length) {+ if (unsafeEngineArgs('CUMORA_CLAUDE_ARGS').length) {return { ok: true, detail: '', skipped: true }}// The realistic break on the persistent-session path is `--append-system-prompt-file`@@ -992,10 +1446,12 @@ class ClaudeAdapter implements EngineAdapter {try { await writeFile(promptFile, '', 'utf8') }catch (err) { return { ok: false, detail: `could not write standing-prompt probe file: ${err instanceof Error ? err.message : String(err)}` } }const { command, shell, wantsStdinPrompt } = resolveSpawn(this.bin)- const base = [- '-p', '--output-format', 'text', '--append-system-prompt-file', promptFile,- '--dangerously-skip-permissions',- ]+ const base = allowUnsandboxedByoa()+ ? ['-p', '--output-format', 'text', '--append-system-prompt-file', promptFile, '--dangerously-skip-permissions']+ : [+ '-p', '--output-format', 'text', '--append-system-prompt-file', promptFile,+ '--restricted', '--tools', '', '--strict-mcp-config',+ ]const argv = wantsStdinPrompt ? base : ['-p', DOCTOR_PROMPT, ...base.slice(1)]const r = await spawnCapture(command, argv, {cwd: args.cwd,@@ -1012,26 +1468,29 @@ class ClaudeAdapter implements EngineAdapter {async seedHome(home: string, persona: EnginePersona): Promise<void> {await ensureCommonHome(home)- await mkdir(join(home, '.claude', 'skills'), { recursive: true })+ await ensureAgentDirectory(join(home, '.claude'))+ await ensureAgentDirectory(join(home, '.claude', 'skills'))// Always (re)written from the DB's name/role/systemPrompt — this file is// system-owned, not agent-editable, so it's safe to overwrite on every// start()/restart (including the restart configMatches() triggers when// the operator edits the agent's persona in Cumora).- await writeFile(join(home, 'CLAUDE.md'), PERSONA_HEADER(persona), 'utf8')- // settings.json lets bash (hence the cumora shim) run without prompts in- // this isolated home. Only written if absent so the user can customize.- const settings = join(home, '.claude', 'settings.json')- if (!(await exists(settings))) {- await writeFile(settings, JSON.stringify({ permissions: { allow: ['Bash'] } }, null, 2), 'utf8')+ await atomicAgentWrite(join(home, 'CLAUDE.md'), PERSONA_HEADER(persona))+ // Legacy settings for unsandboxed compatibility mode. Restricted mode+ // ignores project settings and receives its narrow inline policy instead.+ if (allowUnsandboxedByoa()) {+ const settings = join(home, '.claude', 'settings.json')+ if (!(await exists(settings))) {+ await atomicAgentWrite(settings, JSON.stringify({ permissions: { allow: ['Bash'] } }, null, 2))+ }}}run(args: EngineRunArgs): Promise<EngineRunResult> {// -p: headless print mode. stream-json + verbose gives line-delimited- // events the daemon can log. --dangerously-skip-permissions: the home is- // isolated and user-owned, so non-interactive tool use is intended.+ // events the daemon can log. Secure mode injects a fail-closed policy;+ // the dangerous bypass remains only for explicit compatibility mode.// Big-brain model → --model; small-brain → ANTHROPIC_SMALL_FAST_MODEL env.- const flags = extraArgs('CUMORA_CLAUDE_ARGS')+ const flags = unsafeEngineArgs('CUMORA_CLAUDE_ARGS')const model = args.model ? ['--model', args.model] : []// Continuous context across wakes: resume the agent's prior session so it// remembers the running task (its place in a counting relay, what it already@@ -1042,7 +1501,9 @@ class ClaudeAdapter implements EngineAdapter {// unchanged (prompt in argv).const base = flags.length? [...flags, ...resume, '-p']- : ['-p', ...resume, ...model, '--output-format', 'stream-json', '--verbose', '--dangerously-skip-permissions']+ : allowUnsandboxedByoa()+ ? ['-p', ...resume, ...model, '--output-format', 'stream-json', '--verbose', '--dangerously-skip-permissions']+ : ['-p', ...resume, ...model, '--output-format', 'stream-json', '--verbose', ...claudeSecureFlags(args.home, args.env)]const argv = wantsStdinPrompt ? base : (flags.length ? [...base, args.prompt] : ['-p', args.prompt, ...base.slice(1)])// BYOA turns are short reactive cycles (read inbox, maybe reply). Extended// thinking just adds latency + cost here, and in a group @all it makes the@@ -1052,6 +1513,9 @@ class ClaudeAdapter implements EngineAdapter {const env: NodeJS.ProcessEnv = {...args.env,MAX_THINKING_TOKENS: args.env.MAX_THINKING_TOKENS ?? '0',+ CLAUDE_CODE_SUBPROCESS_ENV_SCRUB: allowUnsandboxedByoa()+ ? args.env.CLAUDE_CODE_SUBPROCESS_ENV_SCRUB+ : '1',}if (args.fastModel) env.ANTHROPIC_SMALL_FAST_MODEL = args.fastModelreturn spawnEngine(command, argv, { ...args, env }, { shell, stdinText: wantsStdinPrompt ? args.prompt : undefined })@@ -1060,7 +1524,7 @@ class ClaudeAdapter implements EngineAdapter {startSession(args: EngineSessionArgs): EngineSession | null {// Respect a user's custom flag override (CUMORA_CLAUDE_ARGS) by NOT using the// persistent path — those flags are tuned for the one-shot run; fall back to run().- if (extraArgs('CUMORA_CLAUDE_ARGS').length) return null+ if (unsafeEngineArgs('CUMORA_CLAUDE_ARGS').length) return nullconst model = args.model ? ['--model', args.model] : []// --resume only on the FIRST spawn / after a restart, to continue a prior// session; inside a live process the session continues on its own.@@ -1072,14 +1536,25 @@ class ClaudeAdapter implements EngineAdapter {let carriesStanding = falseif (args.standingPrompt) {const file = join(args.home, '.cumora-standing-prompt.md')- try { writeFileSync(file, args.standingPrompt, { mode: 0o600 }); sys = ['--append-system-prompt-file', file]; carriesStanding = true }+ try { atomicAgentWriteSync(file, args.standingPrompt); sys = ['--append-system-prompt-file', file]; carriesStanding = true }catch { /* couldn't write → leave it; the daemon inlines the standing prompt instead */ }}- const argv = [- '-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose',- ...resume, ...sys, ...model, '--dangerously-skip-permissions',- ]- const env: NodeJS.ProcessEnv = { ...args.env, MAX_THINKING_TOKENS: args.env.MAX_THINKING_TOKENS ?? '0' }+ const argv = allowUnsandboxedByoa()+ ? [+ '-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose',+ ...resume, ...sys, ...model, '--dangerously-skip-permissions',+ ]+ : [+ '-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose',+ ...resume, ...sys, ...model, ...claudeSecureFlags(args.home, args.env),+ ]+ const env: NodeJS.ProcessEnv = {+ ...args.env,+ MAX_THINKING_TOKENS: args.env.MAX_THINKING_TOKENS ?? '0',+ CLAUDE_CODE_SUBPROCESS_ENV_SCRUB: allowUnsandboxedByoa()+ ? args.env.CLAUDE_CODE_SUBPROCESS_ENV_SCRUB+ : '1',+ }if (args.fastModel) env.ANTHROPIC_SMALL_FAST_MODEL = args.fastModelreturn new ClaudeSession(this.bin, argv, { ...args, env }, carriesStanding)}@@ -1106,6 +1581,75 @@ type CodexRpcMsg = {params?: Record<string, unknown>}+const CODEX_SECURE_CONFIG_ARGS = [+ '--strict-config',+ '-c', 'default_permissions="cumora"',+ '-c', 'permissions.cumora.network.enabled=false',+ '-c', 'shell_environment_policy.inherit="none"',+ '-c', 'shell_environment_policy.ignore_default_excludes=false',+]++function codexThreadSecurityParams(): Record<string, unknown> {+ return allowUnsandboxedByoa()+ ? { approvalPolicy: 'never', sandbox: 'danger-full-access' }+ : { approvalPolicy: 'never', sandbox: 'workspace-write' }+}++function tomlString(value: string): string {+ return JSON.stringify(value)+}++/** The Codex core keeps its auth environment, while every model-spawned+ * command receives only this explicit, non-secret environment. */+function codexToolEnvironmentArgs(args: { home: string; env: NodeJS.ProcessEnv }): string[] {+ const entries: string[] = []+ const add = (name: string, value: string | undefined) => {+ if (value !== undefined) entries.push(`${name}=${tomlString(value)}`)+ }+ add('PATH', args.env.PATH)+ add('HOME', args.home)+ add('USER', args.env.USER)+ add('LOGNAME', args.env.LOGNAME)+ add('SHELL', args.env.SHELL)+ add('LANG', args.env.LANG)+ add('TERM', args.env.TERM)+ add('CUMORA_AGENT_IPC_DIR', args.env.CUMORA_AGENT_IPC_DIR)+ add('CUMORA_AGENT_ID', args.env.CUMORA_AGENT_ID)+ return ['-c', `shell_environment_policy.set={${entries.join(',')}}`]+}++function codexSecureExecArgs(args: { home: string; env: NodeJS.ProcessEnv }, readOnly = false): string[] {+ const workspaceAccess = readOnly ? 'read' : 'write'+ const filesystemEntries = [+ '":minimal"="read"',+ `":workspace_roots"={"."="${workspaceAccess}"}`,+ ]+ const filesystem = `permissions.cumora.filesystem={${filesystemEntries.join(',')}}`+ const secureArgs = [+ ...CODEX_SECURE_CONFIG_ARGS,+ '-c', filesystem,+ '-c', 'web_search="disabled"',+ '-c', 'features.hooks=false',+ '-c', 'features.apps=false',+ '-c', 'features.remote_plugin=false',+ '-c', 'features.multi_agent=false',+ '-c', 'features.shell_snapshot=false',+ // Untrusted projects skip project-local config, hooks, and rules. This is a+ // CLI override (highest precedence), so a model cannot plant a more+ // privileged .codex layer for the next one-shot wake.+ '-c', `projects.${tomlString(args.home)}.trust_level="untrusted"`,+ ...codexToolEnvironmentArgs(args),+ ]+ if (!readOnly) {+ const mcpShim = args.env.CUMORA_AGENT_MCP_SHIM+ const ipcDir = args.env.CUMORA_AGENT_IPC_DIR+ if (!mcpShim || !ipcDir) throw new Error('secure Cumora MCP bridge is not configured')+ const mcp = `mcp_servers.cumora={command=${tomlString(process.execPath)},args=[${tomlString(mcpShim)}],env={CUMORA_AGENT_IPC_DIR=${tomlString(ipcDir)}},required=true,enabled_tools=["cli"],default_tools_approval_mode="approve"}`+ secureArgs.push('-c', mcp)+ }+ return [...secureArgs, '-a', 'never', 'exec', '--ignore-user-config', '--ignore-rules']+}+/** A persistent Codex session over the app-server JSON-RPC protocol* (`codex app-server --listen stdio://`) — the transport with Codex's NATIVE* context management + auto-compaction (unlike one-shot@@ -1153,7 +1697,11 @@ class CodexSession implements EngineSession {this.carriesStandingPrompt = !!opts.standingPrompt// experimentalRawEvents → Codex emits payload-free `rawResponseItem/*` pings we// use as a liveness signal; we suppress them from the log below.- const params: Record<string, unknown> = { cwd: home, approvalPolicy: 'never', sandbox: 'danger-full-access', experimentalRawEvents: true }+ const params: Record<string, unknown> = {+ cwd: home,+ ...codexThreadSecurityParams(),+ experimentalRawEvents: true,+ }if (opts.standingPrompt) params.developerInstructions = opts.standingPromptif (opts.model) params.model = opts.modelthis.baseThreadParams = params@@ -1161,7 +1709,7 @@ class CodexSession implements EngineSession {this.threadReq = opts.resumeSessionId? { method: 'thread/resume', params: { threadId: opts.resumeSessionId, ...params } }: { method: 'thread/start', params }- this.child = spawn(bin, spawnArgs, { cwd: home, env, stdio: ['pipe', 'pipe', 'pipe'], shell: false })+ this.child = spawnEngineChild(bin, spawnArgs, { cwd: home, env, stdio: ['pipe', 'pipe', 'pipe'], shell: false })this.child.stdout?.on('data', (b: Buffer) => this.onStdout(b))this.child.stderr?.on('data', (b: Buffer) => { for (const raw of b.toString('utf8').split('\n')) { const l = cleanLine(raw); if (l) this.onLog(l) } })this.child.on('error', (err) => this.die(1, err.message))@@ -1191,10 +1739,10 @@ class CodexSession implements EngineSession {params: { threadId: this.threadId, expectedTurnId: this.activeTurnId, input: [{ type: 'text', text: stripLoneSurrogates(text) }] } }) + '\n')}- stop(): void {+ stop(options: { force?: boolean } = {}): Promise<void> {this.exited = truetry { this.child.stdin?.end() } catch { /* ignore */ }- try { this.child.kill('SIGTERM') } catch { /* ignore */ }+ return terminateEngineTree(this.child, options.force)}private nextId(): number { this.reqId += 1; return this.reqId }@@ -1393,12 +1941,14 @@ class CodexAdapter implements EngineAdapter {// support tier — so that's the local cerebellum here. Cheap model, no big// brain, no cloud. Override with CUMORA_TRIAGE_MODEL if your codex auth has// a different small model.- const flags = extraArgs('CUMORA_TRIAGE_ARGS')+ const flags = allowUnsandboxedByoa() ? extraArgs('CUMORA_TRIAGE_ARGS') : []const model = ['--model', args.model || 'gpt-5.4-mini']const { command, shell } = resolveSpawn(this.bin)const argv = flags.length? ['exec', ...flags, '-']- : ['exec', ...model, '--skip-git-repo-check', '-']+ : allowUnsandboxedByoa()+ ? ['exec', ...model, '--skip-git-repo-check', '-']+ : [...codexSecureExecArgs({ home: args.cwd, env: args.env }, true), ...model, '--skip-git-repo-check', '-']return spawnCapture(command, argv, {cwd: args.cwd, env: args.env, signal: args.signal, onLog: args.onLog, shell,stdinText: args.prompt,@@ -1411,7 +1961,9 @@ class CodexAdapter implements EngineAdapter {// for a tool-free one-token reply.const model = args.tier === 'small' ? ['--model', triageModel('gpt-5.4-mini')] : []const { command, shell } = resolveSpawn(this.bin)- const argv = ['exec', ...model, '--skip-git-repo-check', '-']+ const argv = allowUnsandboxedByoa()+ ? ['exec', ...model, '--skip-git-repo-check', '-']+ : [...codexSecureExecArgs({ home: args.cwd, env: args.env }, true), ...model, '--skip-git-repo-check', '-']return spawnCapture(command, argv, {cwd: args.cwd, env: args.env, signal: args.signal, shell, stdinText: DOCTOR_PROMPT,})@@ -1422,7 +1974,8 @@ class CodexAdapter implements EngineAdapter {// any of these is true, the wake path collapses to `codex exec ...` which// probe() already covers — running the JSON-RPC probe would just add a false// signal. Mark skipped and let doctor hide the line.- if (extraArgs('CUMORA_CODEX_ARGS').length+ if (!allowUnsandboxedByoa()+ || unsafeEngineArgs('CUMORA_CODEX_ARGS').length|| process.env.CUMORA_CODEX_NO_APP_SERVER === '1'|| IS_WIN) {return Promise.resolve({ ok: true, detail: '', skipped: true })@@ -1444,10 +1997,10 @@ class CodexAdapter implements EngineAdapter {if (settled) returnsettled = truetry { child.stdin?.end() } catch { /* ignore */ }- try { child.kill('SIGTERM') } catch { /* ignore */ }- resolve(r)+ void terminateEngineTree(child).then(() => resolve(r))}- const child = spawn(command, ['app-server', '--listen', 'stdio://'], {+ const appServerArgs = ['app-server', '--listen', 'stdio://']+ const child = spawnEngineChild(command, appServerArgs, {cwd: args.cwd, env: args.env, stdio: ['pipe', 'pipe', 'pipe'], shell,})const onAbort = () => finish({ ok: false, detail: 'aborted (timeout)' })@@ -1489,7 +2042,7 @@ class CodexAdapter implements EngineAdapter {// params shape CodexSession uses — so a field-name break shows up.writeRpc({ jsonrpc: '2.0', method: 'initialized', params: {} })writeRpc({ jsonrpc: '2.0', id: threadId, method: 'thread/start',- params: { cwd: args.cwd, approvalPolicy: 'never', sandbox: 'danger-full-access', experimentalRawEvents: true } })+ params: { cwd: args.cwd, ...codexThreadSecurityParams(), experimentalRawEvents: true } })continue}if (initialized && !threadAcked && msg.id === threadId && msg.result) {@@ -1516,30 +2069,34 @@ class CodexAdapter implements EngineAdapter {async seedHome(home: string, persona: EnginePersona): Promise<void> {await ensureCommonHome(home)// See ClaudeAdapter.seedHome: system-owned, safe to overwrite every start.- await writeFile(join(home, 'AGENTS.md'), PERSONA_HEADER(persona), 'utf8')+ await atomicAgentWrite(join(home, 'AGENTS.md'), PERSONA_HEADER(persona))}run(args: EngineRunArgs): Promise<EngineRunResult> {- // `codex exec` is the non-interactive mode. The agent runs on the user's- // own paired machine and needs full access to run the cumora shim (network),- // clone repos, and write files — the Codex equivalent of Claude's- // --dangerously-skip-permissions is --dangerously-bypass-approvals-and-sandbox.- // --skip-git-repo-check lets it run in the agent home (not a git repo).- // Override the whole flag set via CUMORA_CODEX_ARGS if your version differs.- const flags = extraArgs('CUMORA_CODEX_ARGS')+ // `codex exec` is the non-interactive mode. Secure mode applies a custom+ // filesystem/network/environment profile and reaches Cumora only through+ // local IPC. Historical full-access flags and argv overrides remain+ // available exclusively behind the explicit compatibility opt-in.+ const flags = unsafeEngineArgs('CUMORA_CODEX_ARGS')const base = flags.length- ? flags- : ['--dangerously-bypass-approvals-and-sandbox', '--skip-git-repo-check']+ ? ['exec', ...flags]+ : allowUnsandboxedByoa()+ ? ['exec', '--dangerously-bypass-approvals-and-sandbox', '--skip-git-repo-check']+ : [...codexSecureExecArgs(args), '--skip-git-repo-check']const model = args.model ? ['--model', args.model] : []const { command, shell } = resolveSpawn(this.bin)- return spawnEngine(command, ['exec', ...model, ...base, '-'], args, { shell, stdinText: args.prompt })+ return spawnEngine(command, [...base, ...model, '-'], args, { shell, stdinText: args.prompt })}startSession(args: EngineSessionArgs): EngineSession | null {// Escape hatches → fall back to one-shot `codex exec` (run()): a custom-args// override, an explicit opt-out, or Windows (JSON-RPC over a .cmd shell is// fragile; exec is the safe path there).- if (extraArgs('CUMORA_CODEX_ARGS').length) return null+ // app-server currently has no equivalent to exec --ignore-user-config, so+ // user MCP/hook/config layers cannot be excluded. Keep the secure default+ // on the one-shot path; persistent compatibility is an explicit opt-in.+ if (!allowUnsandboxedByoa()) return null+ if (unsafeEngineArgs('CUMORA_CODEX_ARGS').length) return nullif (process.env.CUMORA_CODEX_NO_APP_SERVER === '1') return nullif (IS_WIN) return nulltry { ensureGitRepoForCodex(args.home) }@@ -1613,7 +2170,7 @@ class GrokSession implements EngineSession {this.sessionNewParams = { cwd: home, mcpServers: [], _meta: meta }this.sessionWasLoad = !!opts.resumeSessionIdconst grokEnv: NodeJS.ProcessEnv = { ...env, GROK_DISABLE_AUTOUPDATER: env.GROK_DISABLE_AUTOUPDATER ?? '1' }- this.child = spawn(bin, spawnArgs, { cwd: home, env: grokEnv, stdio: ['pipe', 'pipe', 'pipe'], shell: false })+ this.child = spawnEngineChild(bin, spawnArgs, { cwd: home, env: grokEnv, stdio: ['pipe', 'pipe', 'pipe'], shell: false })this.child.stdout?.on('data', (b: Buffer) => this.onStdout(b))this.child.stderr?.on('data', (b: Buffer) => {for (const raw of b.toString('utf8').split('\n')) {@@ -1654,10 +2211,10 @@ class GrokSession implements EngineSession {}}- stop(): void {+ stop(options: { force?: boolean } = {}): Promise<void> {this.exited = truetry { this.child.stdin?.end() } catch { /* ignore */ }- try { this.child.kill('SIGTERM') } catch { /* ignore */ }+ return terminateEngineTree(this.child, options.force)}private nextId(): number { this.reqId += 1; return this.reqId }@@ -1880,10 +2437,9 @@ class GrokAdapter implements EngineAdapter {if (settled) returnsettled = truetry { child.stdin?.end() } catch { /* ignore */ }- try { child.kill('SIGTERM') } catch { /* ignore */ }- resolve(r)+ void terminateEngineTree(child).then(() => resolve(r))}- const child = spawn(command, ['agent', '--always-approve', '--no-leader', 'stdio'], {+ const child = spawnEngineChild(command, ['agent', '--always-approve', '--no-leader', 'stdio'], {cwd: args.cwd,env: { ...args.env, GROK_DISABLE_AUTOUPDATER: args.env.GROK_DISABLE_AUTOUPDATER ?? '1' },stdio: ['pipe', 'pipe', 'pipe'],@@ -2141,7 +2697,7 @@ function spawnCursorStream(): Promise<EngineRunResult & { text: string }> {return new Promise((resolve) => {const tracker = new CursorTurnTracker(opts.pin ?? null, opts.onHopUsage)- const child = spawn(command, args, {+ const child = spawnEngineChild(command, args, {cwd: opts.cwd, env: opts.env,stdio: [opts.stdinText != null ? 'pipe' : 'ignore', 'pipe', 'pipe'],shell: opts.shell,@@ -2149,9 +2705,7 @@ function spawnCursorStream(if (opts.stdinText != null) {writeStdin(child, opts.stdinText, { end: true })}- const onAbort = (): void => { child.kill('SIGTERM') }- opts.signal.addEventListener('abort', onAbort, { once: true })- if (opts.signal.aborted) onAbort()+ const abort = bindAbortTermination(child, opts.signal)const stderrTail: string[] = []const stdoutTail: string[] = []const decoder: Record<'stdout' | 'stderr', StringDecoder> = {@@ -2181,27 +2735,31 @@ function spawnCursorStream(child.on('error', (err) => {if (settled) returnsettled = true- opts.signal.removeEventListener('abort', onAbort)- resolve({ exitCode: 1, error: err instanceof Error ? err.message : String(err), sessionId: null, text: '' })+ abort.dispose()+ void abort.wait().then(() => {+ resolve({ exitCode: 1, error: err instanceof Error ? err.message : String(err), sessionId: null, text: '' })+ })})child.on('close', (code, signalName) => {if (settled) returnsettled = true- opts.signal.removeEventListener('abort', onAbort)- pump('stdout', null)- pump('stderr', null)- const procExit = code ?? (signalName ? 128 : 1)- // The stream is the truth: is_error:true fails the turn even on exit 0.- const streamError = tracker.error- ? `engine turn error: ${tracker.error.slice(0, MAX_FAILURE_CHARS)}`- : (opts.requireResult && !tracker.sawResult- ? 'engine stream ended without a result event (cursor-agent exited early)'- : null)- const exitCode = procExit !== 0 ? procExit : (streamError ? 1 : 0)- const error = procExit !== 0- ? failurePreview({ exitCode: procExit, signalName, stderr: stderrTail, stdout: stdoutTail })- : streamError ?? undefined- resolve({ exitCode, error, sessionId: tracker.sessionId, usage: tracker.usage, model: tracker.model, text: tracker.text })+ abort.dispose()+ void abort.wait().then(() => {+ pump('stdout', null)+ pump('stderr', null)+ const procExit = code ?? (signalName ? 128 : 1)+ // The stream is the truth: is_error:true fails the turn even on exit 0.+ const streamError = tracker.error+ ? `engine turn error: ${tracker.error.slice(0, MAX_FAILURE_CHARS)}`+ : (opts.requireResult && !tracker.sawResult+ ? 'engine stream ended without a result event (cursor-agent exited early)'+ : null)+ const exitCode = procExit !== 0 ? procExit : (streamError ? 1 : 0)+ const error = procExit !== 0+ ? failurePreview({ exitCode: procExit, signalName, stderr: stderrTail, stdout: stdoutTail })+ : streamError ?? undefined+ resolve({ exitCode, error, sessionId: tracker.sessionId, usage: tracker.usage, model: tracker.model, text: tracker.text })+ })})})}@@ -2211,7 +2769,7 @@ class CursorAdapter implements EngineAdapter {readonly bin = 'cursor-agent'/** A turn: full-tools one-shot (`--force` auto-approves the agent's tool use- * inside its isolated, user-owned home — the Cursor analogue of Claude's+ * inside its dedicated, user-owned home — the Cursor analogue of Claude's* --dangerously-skip-permissions), `--trust` skips the workspace-trust* prompt a headless spawn can't answer. The prompt is the LAST argv element* (Cursor takes it positionally); on Windows it travels via stdin instead. */@@ -2927,7 +3485,7 @@ function spawnPiJson(}return new Promise((resolve) => {const tracker = new PiTurnTracker(opts.onHopUsage)- const child = spawn(command, args, {+ const child = spawnEngineChild(command, args, {cwd: opts.cwd, env: opts.env,stdio: [opts.stdinText != null ? 'pipe' : 'ignore', 'pipe', 'pipe'],shell: opts.shell,@@ -2935,16 +3493,13 @@ function spawnPiJson(if (opts.stdinText != null) {writeStdin(child, opts.stdinText, { end: true })}- const onAbort = (): void => { child.kill('SIGTERM') }- opts.signal.addEventListener('abort', onAbort, { once: true })- // Close the small race between the pre-spawn check above and listener- // registration. AbortSignal does not replay an earlier abort event.- if (opts.signal.aborted) onAbort()+ const abort = bindAbortTermination(child, opts.signal)// StringDecoder + carried partial line, for the same reason spawnEngine has// them: a pipe read chops a long event (a big message_end) at an arbitrary// byte offset, and a naive per-chunk split would hand JSON.parse two halves.const decoder = new StringDecoder('utf8')let carry = ''+ let settled = falseconst stderrTail: string[] = []const stdoutTail: string[] = []const takeLine = (raw: string): void => {@@ -2974,18 +3529,26 @@ function spawnPiJson(}})child.on('error', (err) => {- opts.signal.removeEventListener('abort', onAbort)- resolve({ exitCode: 1, error: err instanceof Error ? err.message : String(err), sessionId: null, text: '' })+ if (settled) return+ settled = true+ abort.dispose()+ void abort.wait().then(() => {+ resolve({ exitCode: 1, error: err instanceof Error ? err.message : String(err), sessionId: null, text: '' })+ })})child.on('close', (code, signalName) => {- opts.signal.removeEventListener('abort', onAbort)- pump(null) // flush a final line without a trailing newline- const procExit = code ?? (signalName ? 128 : 1)- const exitCode = procExit !== 0 ? procExit : (tracker.error ? 1 : 0)- const error = procExit !== 0- ? failurePreview({ exitCode: procExit, signalName, stderr: stderrTail, stdout: stdoutTail })- : (tracker.error ? `engine turn error: ${tracker.error.slice(0, MAX_FAILURE_CHARS)}` : undefined)- resolve({ exitCode, error, sessionId: tracker.sessionId, usage: tracker.usage, model: tracker.model, text: tracker.text })+ if (settled) return+ settled = true+ abort.dispose()+ void abort.wait().then(() => {+ pump(null) // flush a final line without a trailing newline+ const procExit = code ?? (signalName ? 128 : 1)+ const exitCode = procExit !== 0 ? procExit : (tracker.error ? 1 : 0)+ const error = procExit !== 0+ ? failurePreview({ exitCode: procExit, signalName, stderr: stderrTail, stdout: stdoutTail })+ : (tracker.error ? `engine turn error: ${tracker.error.slice(0, MAX_FAILURE_CHARS)}` : undefined)+ resolve({ exitCode, error, sessionId: tracker.sessionId, usage: tracker.usage, model: tracker.model, text: tracker.text })+ })})})}@@ -3008,7 +3571,7 @@ class PiSession implements EngineSession {private stderrTail: string[] = []private stdoutTail: string[] = []private pendingTimer: ReturnType<typeof setTimeout> | null = null- private stopTimer: ReturnType<typeof setTimeout> | null = null+ private stopPromise: Promise<void> | null = nullreadonly carriesStandingPrompt: booleanconstructor(bin: string, args: string[], opts: EngineSessionArgs, sessionId: string, carriesStandingPrompt: boolean) {@@ -3019,7 +3582,7 @@ class PiSession implements EngineSession {// Cross-platform spawn (Windows: `pi.cmd` via the shell). Everything travels// over stdin as JSON here, so there are no argv-quoting concerns.const { command, shell } = resolveSpawn(bin)- this.child = spawn(command, args, { cwd: opts.home, env: opts.env, stdio: ['pipe', 'pipe', 'pipe'], shell })+ this.child = spawnEngineChild(command, args, { cwd: opts.home, env: opts.env, stdio: ['pipe', 'pipe', 'pipe'], shell })this.child.stdout?.on('data', (b: Buffer) => this.onStdout(b))this.child.stderr?.on('data', (b: Buffer) => this.onStderr(b))this.child.on('error', (err) => this.die(1, err.message))@@ -3071,25 +3634,19 @@ class PiSession implements EngineSession {if (this.pending && this.alive && text.trim()) this.write({ type: 'steer', message: stripLoneSurrogates(text) })}- stop(options: { force?: boolean } = {}): void {+ stop(options: { force?: boolean } = {}): Promise<void> {this.exited = true- if (this.stopTimer) {- if (!options.force) return- clearTimeout(this.stopTimer)- this.stopTimer = null- }// pi exits cleanly when stdin closes (it disposes the session and returns 0),// so close stdin first and only SIGTERM a process that hasn't gone by itself.try { this.child.stdin?.end() } catch { /* ignore */ }- // During daemon shutdown there is no event loop left to run the delayed- // fallback below. Dispatch SIGTERM synchronously before process.exit(), or a- // Pi that does not exit on EOF can be orphaned under the supervisor.- if (options.force) {- try { this.child.kill('SIGTERM') } catch { /* ignore */ }- return+ if (options.force) return terminateEngineTree(this.child, true)+ if (!this.stopPromise) {+ this.stopPromise = (async () => {+ if (await waitForChildExit(this.child, 2_000)) return+ await terminateEngineTree(this.child)+ })()}- this.stopTimer = setTimeout(() => { try { this.child.kill('SIGTERM') } catch { /* ignore */ } }, 2000)- this.stopTimer.unref?.()+ return this.stopPromise}private write(msg: object): boolean {@@ -3164,7 +3721,6 @@ class PiSession implements EngineSession {const alreadyDown = this.exitedthis.exited = truethis.exitCode = code- if (this.stopTimer) { clearTimeout(this.stopTimer); this.stopTimer = null }if (!alreadyDown) {this.onLog(`[session] engine process died ${this.pending ? 'MID-TURN' : 'while idle'}: ${why} (exit ${code})`)}@@ -3250,10 +3806,9 @@ class PiAdapter implements EngineAdapter {if (settled) returnsettled = truetry { child.stdin?.end() } catch { /* ignore */ }- try { child.kill('SIGTERM') } catch { /* ignore */ }- resolve(r)+ void terminateEngineTree(child).then(() => resolve(r))}- const child = spawn(command, ['--mode', 'rpc', ...PiAdapter.BARE], {+ const child = spawnEngineChild(command, ['--mode', 'rpc', ...PiAdapter.BARE], {cwd: args.cwd, env: args.env, stdio: ['pipe', 'pipe', 'pipe'], shell,})const onAbort = (): void => finish({ ok: false, detail: 'aborted (timeout)' })@@ -3326,7 +3881,7 @@ class PiAdapter implements EngineAdapter {resumeSessionId: args.resumeSessionId, onLog: args.onLog, onHopUsage: args.onHopUsage,})if (!session) return { exitCode: 1, error: 'pi session could not be started', sessionId: args.resumeSessionId ?? null }- const onAbort = (): void => session.stop({ force: true })+ const onAbort = (): void => { void session.stop({ force: true }) }args.signal.addEventListener('abort', onAbort, { once: true })// The signal may have flipped after the pre-spawn check but before the// listener above was installed.@@ -3361,7 +3916,7 @@ class PiAdapter implements EngineAdapter {let carriesStanding = falseif (args.standingPrompt) {const file = join(args.home, '.cumora-standing-prompt.md')- try { writeFileSync(file, args.standingPrompt, { mode: 0o600 }); sys = ['--append-system-prompt', file]; carriesStanding = true }+ try { atomicAgentWriteSync(file, args.standingPrompt); sys = ['--append-system-prompt', file]; carriesStanding = true }catch { /* couldn't write → leave it; the daemon inlines the standing prompt instead */ }}const argv = [diff --git a/server/src/agents/computer/registry.ts b/server/src/agents/computer/registry.tsindex c811dfc..6c27627 100644--- a/server/src/agents/computer/registry.ts+++ b/server/src/agents/computer/registry.ts@@ -14,9 +14,9 @@* - per-agent runtime JWTs minted for a paired device (reuses* runtime/jwt.ts — the same token a pod gets)*/-import { randomUUID, randomBytes, createHash } from 'node:crypto'+import { createHash, randomBytes, randomUUID } from 'node:crypto'import { pool } from '../../db/pool.js'-import { publish, CH_STATUS } from '../../redis.js'+import { CH_STATUS, publish } from '../../redis.js'import { signAgentToken } from '../runtime/jwt.js'export type ComputerKind = 'cloud' | 'local' | 'vps'@@ -488,7 +488,7 @@ export async function resolveDevice(token: string): Promise<{ computerId: string/** Mint a short-lived per-agent runtime JWT for a paired device — but only if* the agent is actually assigned to that device's computer (same company).* This is the credential the daemon uses for the agent's wake-stream SSE and- * as CUMORA_AGENT_RUNTIME_TOKEN for the `cumora` shim. */+ * daemon-side runtime calls. It never enters the model process or agent home. */export async function mintAgentRuntimeToken(args: {computerId: stringagentId: string