Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
feat: add ZCode as a BYOA engine via the zcode-acp-server ACP bridge (#247)
lianxinbce9acc9af6f
diff --git a/README.md b/README.mdindex 39dc4f3..1aa002c 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 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).+- **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, Codex, Grok Build, Cursor Agent, OpenCode, pi, Gemini CLI, Qwen Code, Antigravity, or ZCode). Claude Code and Codex use fail-closed filesystem, command-network, and subprocess-credential boundaries by default; the other engines require an explicit unsandboxed compatibility opt-in. The server never sees your provider keys. See [`docs/BYOA.md`](docs/BYOA.md).## Architecturediff --git a/docs/BYOA.md b/docs/BYOA.mdindex 9d88666..1256cdb 100644--- a/docs/BYOA.md+++ b/docs/BYOA.md@@ -1,4 +1,4 @@-# BYOA — Bring Your Own Agent (local Claude Code / Codex / Grok Build / Cursor Agent / OpenCode / pi / Gemini CLI / Qwen Code / Antigravity as the engine)+# BYOA — Bring Your Own Agent (local Claude Code / Codex / Grok Build / Cursor Agent / OpenCode / pi / Gemini CLI / Qwen Code / Antigravity / ZCode as the engine)Every Cumora agent has a "brain" and a host. The managed path isserver-side: `runAgentTurn` in `server/src/agents/turn.ts` runs a@@ -8,15 +8,17 @@ a per-agent Kubernetes pod (the `agent-computer` image).**BYOA** lets a user supply the brain instead: a long-running daemon onthe 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`), **Gemini CLI** (`gemini`), **Qwen Code** (`qwen`), or **Antigravity** (`agy`) as the reasoning engine, on the user's own provider+**OpenCode** (`opencode`), **pi** (`pi`), **Gemini CLI** (`gemini`), **Qwen Code** (`qwen`), **Antigravity** (`agy`), or **ZCode** (`zcode`, driven through the `zcode-acp-server` ACP bridge) 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 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.+Claude Code and Codex are the secure-default engines. The other adapters —+including ZCode, whose host boundary is whatever the operator's zcode login+and permission config allow — 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@@ -45,7 +47,7 @@ managed cloud agents and local agents into the same picture.user to set up; it's always online.- **Your computers** — machines you pair (your Mac, a VPS). Each runs the`cumora agent computer` daemon with a local engine (Claude Code /- Codex / Grok Build / Cursor Agent / OpenCode / pi / Gemini CLI / Qwen Code / Antigravity). Agents you place here are BYOA agents.+ Codex / Grok Build / Cursor Agent / OpenCode / pi / Gemini CLI / Qwen Code / Antigravity / ZCode). Agents you place here are BYOA agents.```Computers@@ -120,6 +122,7 @@ with rate-limit adaptation, and same-turn steering.│ claude --input/output-format stream-json … ││ codex exec / optional compatibility engines ││ pi --mode rpc (JSON commands + events over stdio) │+ │ zcode via the zcode-acp-server ACP stdio bridge ││ tool → file IPC → daemon POST /runtime/cli (JWT) │└─────────────────────────────────────────────────────────┘```@@ -194,7 +197,7 @@ from their own agenda — Kanban cards and due calendar slots — via## Engine integration`server/src/agents/computer/engine.ts` defines one `EngineAdapter` per-engine (`claude`, `codex`, `grok`, `cursor`, `opencode`, `pi`, `gemini`, `qwen`, `antigravity`). Persistent per-agent+engine (`claude`, `codex`, `grok`, `cursor`, `opencode`, `pi`, `gemini`, `qwen`, `antigravity`, `zcode`). Persistent per-agentsessions are preferred when the CLI exposes one; Cursor and OpenCode useone-shot `run()` for every wake and resume the session id reported by the CLI.@@ -215,16 +218,16 @@ interface EngineSession {}```-| Concern | Claude Code | Codex CLI | Grok Build | Cursor Agent | OpenCode | pi | Gemini CLI | Qwen Code | Antigravity |-| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |-| Secure default | Claude Code ≥ 2.1.248 with `--restricted`; no Bash/PowerShell/web tools; host-home reads, command network, unsandboxed retry, and subprocess credentials are denied | Codex ≥ 0.138.0 with a custom permission profile: only minimal runtime reads plus the agent home; command network disabled; tool env allowlisted; user/project config, rules, hooks, apps, remote plugins, and multi-agent tools ignored or disabled | disabled | disabled | disabled | disabled | disabled | disabled | disabled |-| Platform | macOS, Linux, WSL2; native Windows disabled because Claude's sandbox is unsupported there | macOS, Linux, WSL2, native Windows | compatibility opt-in only | compatibility opt-in only | compatibility opt-in only | compatibility opt-in only | compatibility opt-in only | compatibility opt-in only | compatibility opt-in only |-| Persistent session | secure default; `claude -p --input-format stream-json --output-format stream-json --verbose` | compatibility opt-in only; secure default uses one-shot `exec` | compatibility opt-in ACP | none | none | compatibility opt-in RPC | none | none — 0.22.3 has no stream-json INPUT mode | compatibility bidirectional stream-json |-| Standing prompt | `--append-system-prompt-file <home>/.cumora-standing-prompt.md` | inlined into each secure one-shot wake | compatibility ACP `_meta.rules` | inlined | inlined | compatibility `--append-system-prompt` | inlined | inlined | inlined |-| 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` | compatibility `qwen --output-format stream-json --yolo` | same stream-json protocol for one turn |-| 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 | compatibility opt-in required | not supported initially |-| 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/` | `QWEN.md` plus `.qwen/skills/` | `AGENTS.md` plus `.agents/skills/` |-| Triage (small brain) | restricted and tool-free | read-only custom profile and tool env | compatibility only | compatibility only | compatibility only | compatibility only | compatibility only | compatibility only | plan mode inside `agy --sandbox` |+| Concern | Claude Code | Codex CLI | Grok Build | Cursor Agent | OpenCode | pi | Gemini CLI | Qwen Code | Antigravity | ZCode |+| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |+| Secure default | Claude Code ≥ 2.1.248 with `--restricted`; no Bash/PowerShell/web tools; host-home reads, command network, unsandboxed retry, and subprocess credentials are denied | Codex ≥ 0.138.0 with a custom permission profile: only minimal runtime reads plus the agent home; command network disabled; tool env allowlisted; user/project config, rules, hooks, apps, remote plugins, and multi-agent tools ignored or disabled | disabled | disabled | disabled | disabled | disabled | disabled | disabled | disabled |+| Platform | macOS, Linux, WSL2; native Windows disabled because Claude's sandbox is unsupported there | macOS, Linux, WSL2, native Windows | compatibility opt-in only | compatibility opt-in only | compatibility opt-in only | compatibility opt-in only | compatibility opt-in only | compatibility opt-in only | compatibility opt-in only | compatibility opt-in only |+| Persistent session | secure default; `claude -p --input-format stream-json --output-format stream-json --verbose` | compatibility opt-in only; secure default uses one-shot `exec` | compatibility opt-in ACP | none | none | compatibility opt-in RPC | none | none — 0.22.3 has no stream-json INPUT mode | compatibility bidirectional stream-json | compatibility ACP via the `zcode-acp-server` bridge |+| Standing prompt | `--append-system-prompt-file <home>/.cumora-standing-prompt.md` | inlined into each secure one-shot wake | compatibility ACP `_meta.rules` | inlined | inlined | compatibility `--append-system-prompt` | inlined | inlined | inlined | inlined |+| 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` | compatibility `qwen --output-format stream-json --yolo` | same stream-json protocol for one turn | one fresh bridge process per turn (ACP `session/prompt`) |+| 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 | compatibility opt-in required | not supported initially | not supported — `CUMORA_ZCODE_ACP_BIN` picks the bridge entry, never engine argv |+| 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/` | `QWEN.md` plus `.qwen/skills/` | `AGENTS.md` plus `.agents/skills/` | `AGENTS.md` plus `.agents/skills/` |+| Triage (small brain) | restricted and tool-free | read-only custom profile and tool env | compatibility only | compatibility only | compatibility only | compatibility only | compatibility only | compatibility only | plan mode inside `agy --sandbox` | one fresh bridge process in the neutral triage cwd |Sessions carry a resume id (`~/.cumora/sessions/<agentId>.session`); afailed resume falls back to a fresh thread instead of wedging the agent.@@ -248,6 +251,19 @@ counters, and resuming without that baseline would rebill historical turns.Every invocation requests `agy --sandbox`, but Antigravity remains a compatibilityengine until Cumora has independently verified that its complete file, tool,credential, and network boundary fails closed on every supported platform.+ZCode runs through the `zcode-acp-server` npm bridge (initialize → session/new →+session/prompt over stdio; the same ACP surface Grok Build's persistent session+uses), which in turn drives the operator's `zcode` CLI. The npm-published bridge+is the source of truth: the daemon spawns `npx -y zcode-acp-server`, so bridge+fixes reach operators without a daemon release, and `CUMORA_ZCODE_ACP_BIN` pins+an explicit entry script (a specific version on disk or an offline copy) ahead+of that. The engine's model pin rides ACP's `session/set_config_option` once+per session — applied at the first prompt boundary, where the bridge's lazy+`session/new` has materialized a real backend session — falling back to the+operator's zcode default when the bridge rejects it. Zcode stays a+compatibility engine: the bridge + app-server pair runs with the operator's own+zcode login and permission configuration, which Cumora can neither verify nor+narrow.Secure-default engines run headless inside a fail-closed local sandbox; anunavailable sandbox stops the turn instead of widening access. On Windows the daemon resolves the real`claude`/`codex`/`grok`/`cursor-agent`/`opencode`/`pi`/`gemini`/`qwen`/`agy` `.cmd` shims and routes large@@ -297,7 +313,7 @@ fail-closed host boundary:sandbox because the unelevated restricted-token implementation cannot enforcethis split filesystem profile. Codex 0.138.0 or newer is required.-Grok, Cursor, OpenCode, pi, Gemini, Qwen, Antigravity, and Claude on native Windows remain+Grok, Cursor, OpenCode, pi, Gemini, Qwen, Antigravity, ZCode, and Claude on native Windows remainavailable only as a backwards-compatibility escape hatch. They are not merelyhidden in the UI: the daemon removes them from its runnable inventory, so aserver assignment cannot make one execute accidentally.@@ -408,6 +424,7 @@ CUMORA_ENGINE_MODEL=local CUMORA_TRIAGE_MODEL=local-small cumora agent computer.gemini/skills/ ← Gemini-native skill directory.qwen/skills/ ← Qwen-native skill directory.pi/skills/ ← pi-native skill directory (via --skill)+ .agents/skills/ ← Antigravity- and ZCode-native skill directorybin/cumora ← compatibility mode onlymemory/MEMORY.md ← the agent's durable memory indexnotes/ ← scratch notes@@ -576,7 +593,7 @@ npx cumora@latest agent computer --pair <code> [--server <url>]## Boundaries- **Cost / rate limits are the operator's** (their Claude Code / Codex / Grok Build /- Cursor / Antigravity subscription, or OpenCode / pi provider account) — a stated BYOA benefit. The daemon's semaphores, spawn+ Cursor / Antigravity / ZCode subscription, or OpenCode / pi provider account) — a stated BYOA benefit. The daemon's semaphores, spawnpacing, and cooldowns exist to stay inside those limits gracefully(COORDINATION.md 2-4).- **Local inner state is not mirrored to the server.** Memory, notes,diff --git a/scripts/guard-big-brain.mjs b/scripts/guard-big-brain.mjsindex 2d6e8d9..8a3bbb5 100644--- a/scripts/guard-big-brain.mjs+++ b/scripts/guard-big-brain.mjs@@ -80,7 +80,7 @@ export function lineViolations(rel, raw) {out.push('big-brain engine spawn (adapter.run) outside the gated daemon path')}// R4 — a supported engine binary spawned directly, outside the adapter.- if (/(?:spawn|execFile\w*|exec)\s*\(\s*['"`](claude|codex|grok|cursor-agent|opencode|pi|gemini|qwen|agy)['"`]/.test(code) && !ALLOW.engineSpawn.includes(rel)) {+ if (/(?:spawn|execFile\w*|exec)\s*\(\s*['"`](claude|codex|grok|cursor-agent|opencode|pi|gemini|qwen|agy|zcode)['"`]/.test(code) && !ALLOW.engineSpawn.includes(rel)) {out.push('engine binary spawned outside the engine adapter (bypasses the classify=small / run=big split)')}return outdiff --git a/server/src/__tests__/agents-computer-engine-zcode.test.ts b/server/src/__tests__/agents-computer-engine-zcode.test.tsnew file mode 100644index 0000000..3df121c--- /dev/null+++ b/server/src/__tests__/agents-computer-engine-zcode.test.ts@@ -0,0 +1,225 @@+/**+ * Contract tests for the BYOA ZCode (`zcode`) adapter.+ *+ * The fake bridge implements the zcode-acp-server wire surface the adapter+ * actually speaks — initialize / session/new|load / session/set_config_option /+ * session/prompt over newline-delimited JSON-RPC — and is injected through+ * CUMORA_ZCODE_ACP_BIN, the same escape hatch operators use, so the resolution+ * seam stays under test. Scenarios cover the pin-retry semantics, the+ * stale-resume self-heal at load time, and the "Session is not active" →+ * resume-not-found mapping at prompt time.+ */+import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, test } from 'node:test'+import assert from 'node:assert/strict'+import { getAdapter, type EngineHopReport } from '../agents/computer/engine.js'++const tempDirs: string[] = []++afterEach(async () => {+ await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })))+})++const FAKE_BRIDGE = `#!/usr/bin/env node+'use strict'+const fs = require('node:fs')+const readline = require('node:readline')+const mode = process.env.FAKE_ACP_MODE || 'ok'+const log = process.env.FAKE_ACP_LOG+let nextSid = 0+let loaded = false+const out = (msg) => process.stdout.write(JSON.stringify(msg) + '\\n')+const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity })+rl.on('line', (line) => {+ if (!line.trim()) return+ let req+ try { req = JSON.parse(line) } catch { return }+ if (!req.id || !req.method) return+ if (log) fs.appendFileSync(log, JSON.stringify({ method: req.method, params: req.params }) + '\\n')+ const reply = (result) => out({ jsonrpc: '2.0', id: req.id, result })+ const fail = (message) => out({ jsonrpc: '2.0', id: req.id, error: { message } })+ if (req.method === 'initialize') return reply({})+ if (req.method === 'session/load') {+ if (mode === 'stale-load') return fail('Internal error')+ loaded = true+ return reply({ sessionId: req.params.sessionId })+ }+ if (req.method === 'session/new') {+ loaded = false+ return reply({ sessionId: 'fresh-' + (++nextSid) })+ }+ if (req.method === 'session/set_config_option') {+ if (mode === 'reject-pin') return fail('Internal error')+ return reply({ kind: 'model', currentValue: req.params.value })+ }+ if (req.method === 'session/prompt') {+ if (mode === 'stale-prompt' && loaded) return fail('Session is not active')+ if (mode === 'die-midturn') return process.exit(3)+ out({ jsonrpc: '2.0', method: 'session/update', params: { update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'OK' } } } })+ return reply({ stopReason: 'end_turn' })+ }+ return reply({})+})+`++interface Fixture { home: string; log: string; env: NodeJS.ProcessEnv; logs: string[] }++async function fixture(scenario = 'ok'): Promise<Fixture> {+ const root = await mkdtemp(join(tmpdir(), 'cumora-zcode-'))+ tempDirs.push(root)+ const home = join(root, 'home')+ const log = join(root, 'fake.log')+ await mkdir(home, { recursive: true })+ const fake = join(root, 'fake-acp-bridge.cjs')+ await writeFile(fake, FAKE_BRIDGE, 'utf8')+ await chmod(fake, 0o755)+ const logs: string[] = []+ return {+ home, log, logs,+ env: {+ ...process.env,+ CUMORA_ZCODE_ACP_BIN: fake,+ FAKE_ACP_MODE: scenario,+ FAKE_ACP_LOG: log,+ },+ }+}++async function bridgeLog(f: Fixture): Promise<Array<{ method: string; params: Record<string, unknown> }>> {+ return (await readFile(f.log, 'utf8')).split('\n').filter(Boolean).map((line) => JSON.parse(line))+}++test('zcode persistent session pins the model once and rides one session across wakes', async () => {+ const f = await fixture()+ const hops: EngineHopReport[] = []+ const session = getAdapter('zcode').startSession?.({+ home: f.home,+ env: f.env,+ model: 'GLM-5.3',+ standingPrompt: 'scaffold',+ onLog: (line) => f.logs.push(line),+ onHopUsage: (hop) => hops.push(hop),+ })+ assert.ok(session)+ assert.equal(session.carriesStandingPrompt, false, 'no out-of-band standing-prompt channel — the daemon inlines it')++ const first = await session.send('first prompt')+ const second = await session.send('second prompt')+ await session.stop()++ assert.equal(first.exitCode, 0)+ assert.equal(first.sessionId, 'fresh-1')+ assert.equal(second.exitCode, 0)+ assert.equal(second.sessionId, 'fresh-1', 'the same bridge session carries both wakes')+ assert.equal(hops.length, 2, 'one hop per wake')++ const requests = await bridgeLog(f)+ const pins = requests.filter((r) => r.method === 'session/set_config_option')+ assert.equal(pins.length, 1, 'an accepted pin is sent once, not on every wake')+ assert.equal(pins[0].params.configId, 'model')+ assert.equal(pins[0].params.value, 'GLM-5.3')+ const prompts = requests.filter((r) => r.method === 'session/prompt')+ assert.deepEqual(prompts.map((r) => (r.params.prompt as Array<{ text: string }>)[0].text), ['first prompt', 'second prompt'])+ assert.ok(prompts.every((r) => r.params.sessionId === 'fresh-1'))+})++test('zcode retries a rejected model pin on the next wake and still turns', async () => {+ const f = await fixture('reject-pin')+ const session = getAdapter('zcode').startSession?.({+ home: f.home,+ env: f.env,+ model: 'GLM-5.3',+ standingPrompt: null,+ onLog: (line) => f.logs.push(line),+ })+ assert.ok(session)+ const first = await session.send('first prompt')+ const second = await session.send('second prompt')+ await session.stop()++ assert.equal(first.exitCode, 0, 'a rejected pin is a preference loss, not a turn failure')+ assert.equal(second.exitCode, 0)+ assert.ok(f.logs.some((line) => line.includes('model pin rejected')))+ const requests = await bridgeLog(f)+ assert.equal(requests.filter((r) => r.method === 'session/set_config_option').length, 2, 'a rejected pin retries on each wake')+})++test('zcode self-heals a stale resume at load time and reports a fresh session', async () => {+ const f = await fixture('stale-load')+ const session = getAdapter('zcode').startSession?.({+ home: f.home,+ env: f.env,+ model: null,+ standingPrompt: null,+ resumeSessionId: 'stale-sid',+ onLog: (line) => f.logs.push(line),+ })+ assert.ok(session)+ const result = await session.send('first prompt after restart')+ await session.stop()++ assert.equal(result.exitCode, 0)+ assert.equal(result.sessionId, 'fresh-1', 'the fresh session replaces the stale one')+ assert.ok(f.logs.some((line) => line.includes('session/load failed') && line.includes('starting a fresh session')))+ const requests = await bridgeLog(f)+ assert.equal(requests[1]?.method, 'session/load')+ assert.equal(requests[2]?.method, 'session/new')+})++test('zcode maps a mid-life missing backend session to resume-not-found', async () => {+ const f = await fixture('stale-prompt')+ const session = getAdapter('zcode').startSession?.({+ home: f.home,+ env: f.env,+ model: null,+ standingPrompt: null,+ resumeSessionId: 'real-but-dead',+ onLog: (line) => f.logs.push(line),+ })+ assert.ok(session)+ const result = await session.send('prompt a vanished session')+ await session.stop()++ assert.equal(result.exitCode, 1)+ assert.equal(result.failure?.kind, 'resume-not-found', 'the bridge\'s "Session is not active" is not in the generic patterns — the adapter maps it')+ assert.ok(result.error?.includes('Session is not active'))+})++test('zcode a bridge dying MID-TURN resolves the turn as a failure, never rejects', async () => {+ const f = await fixture('die-midturn')+ const session = getAdapter('zcode').startSession?.({+ home: f.home,+ env: f.env,+ model: null,+ standingPrompt: null,+ onLog: (line) => f.logs.push(line),+ })+ assert.ok(session)+ // die() races send()'s own settlement here: the rpc waiters reject while the+ // in-flight turn is already closed. send() must still RESOLVE a failure.+ const result = await session.send('prompt that kills the bridge')+ await session.stop()++ assert.equal(result.exitCode, 3)+ assert.ok(result.error)+ assert.notEqual(result.failure?.kind, 'resume-not-found', 'no resume involved — the generic classifier owns this kind')+})++test('zcode probeWake exercises the bridge handshake and one-shot run returns text', async () => {+ const f = await fixture()+ const adapter = getAdapter('zcode')+ const wake = await adapter.probeWake({ cwd: f.home, env: f.env, signal: AbortSignal.timeout(10_000) })+ assert.equal(wake.ok, true)++ const run = await adapter.run({+ home: f.home,+ prompt: 'echo prompt',+ env: f.env,+ signal: AbortSignal.timeout(10_000),+ onLog: () => {},+ })+ assert.equal(run.exitCode, 0)+ assert.equal(run.sessionId, 'fresh-1')+})diff --git a/server/src/agents/computer/cli-version.ts b/server/src/agents/computer/cli-version.tsindex 81226c9..827b418 100644--- a/server/src/agents/computer/cli-version.ts+++ b/server/src/agents/computer/cli-version.ts@@ -119,6 +119,9 @@ export const ENGINE_VERSION_SPECS: Record<string, EngineVersionSpec> = {versionArgs: ['--version'],selfUpdate: 'agy update',},+ zcode: {+ versionArgs: ['--version'],+ },hermes: {versionArgs: ['version'],selfUpdate: 'hermes update',diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.tsindex 54c3fe4..dc14cbc 100644--- a/server/src/agents/computer/daemon.ts+++ b/server/src/agents/computer/daemon.ts@@ -791,6 +791,9 @@ export function authFailureHint(engine: EngineId, detail: string): string {if (engine === 'antigravity') {return 'Open Antigravity on that computer and run `agy` to refresh its login, model access, or quota, then wake the agent again.'}+ if (engine === 'zcode') {+ return 'Open ZCode on that computer and run `zcode` to refresh its login, model access, or quota, then wake the agent again.'+ }return 'Check the daemon terminal for details, then wake the agent again.'}@@ -810,6 +813,9 @@ function missingEngineMessage(): string {' - Gemini CLI: install the `gemini` CLI, then run `gemini` once to sign in',' - Qwen Code: install the `qwen` CLI, then run `qwen` once to sign in',' - Antigravity: install the `agy` CLI, then run `agy` once to sign in',+ ' - ZCode: install the `zcode` CLI, then run `zcode` once to sign in',+ ' (the daemon drives it through the npm-published `zcode-acp-server` bridge via npx;',+ ' CUMORA_ZCODE_ACP_BIN pins a specific bridge copy when needed)','','After that, rerun:',' npx cumora@latest agent computer --pair <code>',@@ -2348,6 +2354,7 @@ export class AgentRunner {if (this.adapter.id === 'opencode') return this.agent.model ?? '<opencode-default>'if (this.adapter.id === 'pi') return this.agent.model ?? '<pi-default>'if (this.adapter.id === 'antigravity') return this.agent.model ?? 'gemini-3.8-flash-high'+ if (this.adapter.id === 'zcode') return this.agent.model ?? '<zcode-default>'if (this.adapter.id === 'cursor') return this.agent.model ?? '<cursor-default>'return this.agent.model ?? '<cursor-default>'}diff --git a/server/src/agents/computer/engine.ts b/server/src/agents/computer/engine.tsindex 18cf984..c3ab874 100644--- a/server/src/agents/computer/engine.ts+++ b/server/src/agents/computer/engine.ts@@ -3,7 +3,7 @@** A BYOA agent's reasoning loop is delegated to a local CLI engine running* on the user's machine: Claude Code, Codex, Grok Build, Cursor Agent,- * OpenCode, pi, Gemini CLI, Qwen Code, or Antigravity. The daemon (daemon.ts) hands+ * OpenCode, pi, Gemini CLI, Qwen Code, Antigravity, or ZCode. The daemon (daemon.ts) hands* each wake to an adapter, which spawns the engine headlessly in the agent's* dedicated home directory. The engine reads its persona + memory + skills* from that home natively (CLAUDE.md / AGENTS.md, .claude/skills, …) and acts@@ -351,10 +351,10 @@ function resolveCodexSpawn(): CodexSpawn {return { command: node, argsPrefix: [script], shell: false, wantsStdinPrompt: false }}-export type EngineId = 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode' | 'pi' | 'gemini' | 'qwen' | 'antigravity'+export type EngineId = 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode' | 'pi' | 'gemini' | 'qwen' | 'antigravity' | 'zcode'/** The pairable engine ids, in the daemon's default detection order. */-export const ENGINE_IDS: EngineId[] = ['claude', 'codex', 'grok', 'cursor', 'opencode', 'pi', 'gemini', 'qwen', 'antigravity']+export const ENGINE_IDS: EngineId[] = ['claude', 'codex', 'grok', 'cursor', 'opencode', 'pi', 'gemini', 'qwen', 'antigravity', 'zcode']/** Engines for which Cumora can impose a fail-closed filesystem + tool-network* boundary non-interactively. The remaining adapters still work for operators@@ -2859,6 +2859,493 @@ class GrokAdapter implements EngineAdapter {}}+// ─── zcode ────────────────────────────────────────────────────────────────+//+// ZCode (the `zcode` CLI) is driven through the `zcode-acp-server` npm+// bridge, which wraps ZCode's headless app-server in the standard ACP agent+// surface (initialize / session/new / session/prompt over stdio) — the same+// wire protocol GrokSession speaks. The adapter therefore spawns+//+// node <zcode-acp-server>/dist/index.js+//+// and the bridge, not Cumora, spawns the actual `zcode` process (its PATH+// lookup, or ZCODE_BIN, decides which CLI runs — Cumora only probes `zcode`+// to decide whether the engine is installed). The bridge is a spawn-type+// dependency: it cannot be esbuild-bundled into the daemon because its whole+// job is to be a separate process tree. The npm-published package IS the+// source of truth: the daemon runs `npx -y zcode-acp-server`, so protocol+// fixes ship to operators without a daemon release, and no local checkout can+// silently shadow the published bridge. CUMORA_ZCODE_ACP_BIN pins an explicit+// entry script (a specific npm version on disk, an offline copy, or a dev+// workspace) ahead of that.+//+// Zcode is a COMPATIBILITY engine: Cumora cannot impose a verified fail-closed+// host boundary on the bridge + app-server pair (the operator's zcode login+// and permission config decide what a turn may touch), so it never auto-runs —+// pairing requires CUMORA_BYOA_ALLOW_UNSANDBOXED=1. Zcode reads its persona+// and skills natively from AGENTS.md and .agents/skills/ in the agent home.+// There is no out-of-band standing-prompt channel in the bridge, so+// carriesStandingPrompt stays false and the daemon inlines the invariant+// scaffold into each turn prompt (the Cursor/OpenCode contract).++/** Locate the zcode-acp-server bridge entry script on this machine. */+function resolveZcodeAcpSpawn(env: NodeJS.ProcessEnv): { command: string; args: string[]; shell: boolean } {+ const explicit = env.CUMORA_ZCODE_ACP_BIN?.trim()+ if (explicit) return { command: process.execPath, args: [explicit], shell: false }+ const npx = resolveSpawn('npx')+ return { command: npx.command, args: ['-y', 'zcode-acp-server'], shell: npx.shell }+}++interface ZcodeTurnOptions {+ cwd: string+ env: NodeJS.ProcessEnv+ prompt: string+ model?: string | null+ signal: AbortSignal+ onLog?: (line: string) => void+ onHopUsage?: (r: EngineHopReport) => void+}++interface ZcodeSessionOptions extends EngineSessionArgs {+ /** Assistant text chunks, streamed out for one-shot callers (classify/+ * probe/run read the turn's reply text; persistent wakes only log it). */+ onAgentText?: (text: string) => void+ /** Aborts the session (one-shot turns only; persistent sessions rely on+ * stop()). Wired to the platform tree terminator. */+ signal?: AbortSignal+}++/** The bridge's backend rejects an unknown / no-longer-live zcode session with+ * this phrasing (its dispatch code documents the literal: "Session is not+ * active"). The shared classifier's resume patterns don't match it, so a+ * resumed session that dies mid-life maps through this adapter-aware rule to+ * the same fresh-retry recovery vocabulary as the other engines. */+const ZCODE_MISSING_SESSION_RE = /session is not active|no such session|unknown session/i++/** Hook surface the connection exposes upward. The connection owns only wire+ * state — turn settlement stays with the session above it. */+interface AcpRpcConnectionHooks {+ onLog: (line: string) => void+ /** Server→client notifications; unrecognized methods are the hook's to ignore. */+ onNotification: (msg: AcpMsg) => void+ /** Process death, fired exactly once. In-flight rpc() calls have already+ * been rejected when it fires. */+ onDeath: (exitCode: number, why: string) => void+ /** session/load fell back to a fresh session/new. */+ onLoadFallback: (why: string) => void+}++/**+ * Wire-level ACP stdio connection for one bridge process: spawn, JSON-RPC+ * framing, the initialize handshake, session new/load, notification routing,+ * and death. Deliberately composition (the codebase shares via helpers, not+ * inheritance): turn settlement and resume classification stay with the+ * session, which observes death and handshake fallback through the hooks.+ */+class AcpRpcConnection {+ private readonly child: ChildProcess+ private readonly sessionParams: () => Record<string, unknown>+ private readonly hooks: AcpRpcConnectionHooks+ private readonly signal?: AbortSignal+ /** Current session id — absorbed from session/new|load responses. */+ sid: string | null+ /** True while the current context came from a session/load. The session+ * consumes (and clears) this for the failure classifier's resume kind. */+ resumed = false+ private dead = false+ private stopRequested = false+ private exitCode = 0+ private reqId = 0+ /** In-flight requests awaiting their JSON-RPC response. */+ private readonly waiters = new Map<number, (msg: AcpMsg) => void>()+ private outBuf = ''+ /** Settles when the handshake completes; rejects when the handshake or the+ * process itself failed. send() awaits it, and so does probeWake(). */+ readonly ready: Promise<void>++ constructor(+ spawnSpec: { command: string; args: string[]; shell: boolean },+ home: string,+ env: NodeJS.ProcessEnv,+ initialSid: string | null,+ sessionParams: () => Record<string, unknown>,+ hooks: AcpRpcConnectionHooks,+ signal?: AbortSignal,+ ) {+ this.child = spawnEngineChild(spawnSpec.command, spawnSpec.args, {+ cwd: home, env, stdio: ['pipe', 'pipe', 'pipe'], shell: spawnSpec.shell,+ })+ this.sid = initialSid+ this.sessionParams = sessionParams+ this.hooks = hooks+ this.signal = signal+ 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.hooks.onLog(l)+ }+ })+ this.child.on('error', (err) => this.die(1, err.message))+ this.child.on('close', (code, sig) => this.die(code ?? (sig ? 128 : 1), sig ? `terminated by ${sig}` : `exited with code ${code}`))+ if (this.signal) {+ const abort = () => { void terminateEngineTree(this.child, true) }+ if (this.signal.aborted) abort()+ else this.signal.addEventListener('abort', abort, { once: true })+ }+ this.ready = this.handshake()+ // An idle failed handshake (no send()/whenReady() consumer) must not+ // become an unhandled rejection — the next send() reports it as dead.+ this.ready.catch(() => {})+ }++ get alive(): boolean { return !this.dead && !this.stopRequested && this.child.stdin?.writable === true }+ get exitStatusCode(): number { return this.exitCode }+ whenReady(): Promise<void> { return this.ready }++ /** One JSON-RPC request → response. Server→client notifications route to+ * the onNotification hook; a dead process fails every waiter from die(). */+ rpc(method: string, params: Record<string, unknown>): Promise<AcpMsg> {+ if (this.dead || this.stopRequested) return Promise.reject(new Error('engine session is not alive (process gone)'))+ const id = ++this.reqId+ return new Promise<AcpMsg>((resolve, reject) => {+ this.waiters.set(id, (msg) => {+ if (msg.error) reject(new Error(String(msg.error.message || `${method} failed`)))+ else resolve(msg)+ })+ writeStdin(this.child, JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n')+ })+ }++ stop(options: { force?: boolean } = {}): Promise<void> {+ this.stopRequested = true+ try { this.child.stdin?.end() } catch { /* ignore */ }+ return terminateEngineTree(this.child, options.force)+ }++ /** initialize → session/load|new. A stale resume falls back to a fresh+ * session; anything else rejects `ready` and fails the pending turn. */+ private async handshake(): Promise<void> {+ await this.rpc('initialize', {+ protocolVersion: 1,+ clientInfo: { name: 'cumora-daemon', version: '1.0.0' },+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false } },+ })+ if (this.sid) {+ try {+ this.absorbSessionId(await this.rpc('session/load', { sessionId: this.sid, ...this.sessionParams() }))+ this.resumed = true+ return+ } catch (err) {+ const why = err instanceof Error ? err.message : String(err)+ this.resumed = false+ this.sid = null+ this.hooks.onLoadFallback(why)+ }+ }+ this.absorbSessionId(await this.rpc('session/new', this.sessionParams()))+ }++ private onStdout(buf: Buffer): void {+ this.outBuf += buf.toString('utf8')+ let nl: number+ while ((nl = this.outBuf.indexOf('\n')) >= 0) {+ const line = this.outBuf.slice(0, nl)+ this.outBuf = this.outBuf.slice(nl + 1)+ const t = line.trim()+ if (!t.startsWith('{')) { const c = cleanLine(line); if (c) this.hooks.onLog(c); continue }+ let msg: AcpMsg | null = null+ try { msg = JSON.parse(t) as AcpMsg } catch { msg = null }+ if (!msg) { const c = cleanLine(line); if (c) this.hooks.onLog(c); continue }+ if (msg.id !== undefined) {+ const waiter = this.waiters.get(msg.id)+ if (waiter) { this.waiters.delete(msg.id); waiter(msg); continue }+ }+ this.hooks.onNotification(msg)+ }+ }++ private absorbSessionId(msg: AcpMsg): void {+ const sid = typeof msg.result?.sessionId === 'string' ? msg.result.sessionId : null+ if (sid) this.sid = sid+ }++ private die(code: number, why: string): void {+ const firstDeath = !this.dead+ this.dead = true+ this.exitCode = code+ // Fail every in-flight request so rpc() callers don't hang on a dead pipe.+ for (const [, waiter] of this.waiters) waiter({ error: { message: why } })+ this.waiters.clear()+ if (firstDeath) this.hooks.onDeath(code, why)+ }+}++/** Persistent ZCode session: turn settlement, the lazy model pin, and the+ * bridge's missing-session phrasing on top of a wire-level AcpRpcConnection.+ * Mid-turn steer is not in the ACP surface — steer() is a no-op and the+ * daemon's next-wake coalescing carries the ping (same contract as+ * GrokSession). */+class ZcodeSession implements EngineSession {+ readonly carriesStandingPrompt = false++ private readonly conn: AcpRpcConnection+ private readonly onLog: (line: string) => void+ private readonly onHopUsage?: (r: EngineHopReport) => void+ private readonly onAgentText?: (text: string) => void+ private readonly model: string | null+ private modelUnapplied: boolean+ private turn: { resolve: (r: EngineRunResult) => void } | null = null+ private steerWarned = false+ private stopped = false++ constructor(home: string, env: NodeJS.ProcessEnv, opts: ZcodeSessionOptions) {+ this.onLog = opts.onLog+ this.onHopUsage = opts.onHopUsage+ this.onAgentText = opts.onAgentText+ this.model = opts.model ?? null+ this.modelUnapplied = !!opts.model+ this.conn = new AcpRpcConnection(+ resolveZcodeAcpSpawn(env),+ home,+ env,+ opts.resumeSessionId ?? null,+ () => ({ cwd: home, mcpServers: [] }),+ {+ onLog: (line) => this.onLog(line),+ onNotification: (msg) => this.onUpdate(msg),+ onDeath: (code, why) => this.onDeath(code, why),+ onLoadFallback: (why) => {+ this.onLog(`[zcode] session/load failed (${why}) — starting a fresh session`)+ },+ },+ opts.signal,+ )+ }++ get alive(): boolean { return this.conn.alive }+ get sessionId(): string | null { return this.conn.sid }+ whenReady(): Promise<void> { return this.conn.ready }++ async send(prompt: string): Promise<EngineRunResult> {+ if (this.turn) return classifyEngineResult({ exitCode: 1, error: 'engine session busy — a turn is already in flight', sessionId: this.conn.sid }, this.conn.resumed)+ if (!this.alive) return classifyEngineResult({ exitCode: this.conn.exitStatusCode || 1, error: 'engine session is not alive (process gone)', sessionId: this.conn.sid }, this.conn.resumed)+ let resolveTurn!: (r: EngineRunResult) => void+ const done = new Promise<EngineRunResult>((resolve) => { resolveTurn = resolve })+ // Only the first settler wins: process death (onDeath → this.turn.resolve)+ // races the async body below, and whichever lands first closes the turn.+ // Held in a local because onDeath() nulls this.turn when it settles first.+ let settled = false+ const settle = (r: EngineRunResult) => { if (!settled) { settled = true; this.turn = null; resolveTurn(r) } }+ this.turn = { resolve: settle }+ try {+ await this.conn.ready+ await this.applyModelPin()+ if (!this.alive) throw new Error('engine session is not alive (process gone)')+ const wasResume = this.conn.resumed+ const startedAt = Date.now()+ const resp = await this.conn.rpc('session/prompt', {+ sessionId: this.conn.sid,+ prompt: [{ type: 'text', text: stripLoneSurrogates(prompt) }],+ })+ this.conn.resumed = false+ const usage = extractAcpUsage(resp.result) ?? undefined+ if (this.onHopUsage) {+ try {+ this.onHopUsage({+ model: this.model ?? 'zcode',+ usage: usage ?? {},+ latencyMs: Date.now() - startedAt,+ hopIndex: 1,+ })+ } catch { /* never break the stream */ }+ }+ settle(classifyEngineResult({ exitCode: 0, sessionId: this.conn.sid, usage, model: this.model }, wasResume))+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err)+ const wasResume = this.conn.resumed+ this.conn.resumed = false+ settle(this.failureResult(message, wasResume, this.conn.exitStatusCode || 1))+ }+ return done+ }++ steer(_text: string): void {+ // ACP session/prompt is one-in-flight. A mid-turn inject would cancel the+ // running turn. The daemon coalesces the ping onto the next wake instead.+ if (!this.steerWarned) {+ this.steerWarned = true+ this.log('[zcode] same-turn steer is not supported on ACP stdio — the ping rides the next wake')+ }+ }++ async stop(options: { force?: boolean } = {}): Promise<void> {+ this.stopped = true+ await this.conn.stop(options)+ }++ /** The bridge's session/new is lazy (the backend session materializes on+ * first use), so the pin rides the first prompt boundary. A rejected pin+ * is a preference loss, not a turn failure — log it and keep retrying on+ * later wakes until the bridge accepts. */+ private async applyModelPin(): Promise<void> {+ if (!this.modelUnapplied || !this.model || !this.conn.sid) return+ try {+ await this.conn.rpc('session/set_config_option', { sessionId: this.conn.sid, configId: 'model', value: this.model })+ this.modelUnapplied = false+ } catch (err) {+ const why = err instanceof Error ? err.message : String(err)+ this.log(`[zcode] model pin rejected (${why}) — continuing on the engine default`)+ }+ }++ /** A failed turn in the shared vocabulary. A resumed session whose backend+ * went missing maps to resume-not-found (the bridge's "Session is not+ * active" is not in the generic patterns); the generic classifier covers+ * everything else. */+ private failureResult(message: string, wasResume: boolean, exitCode = 1): EngineRunResult {+ return classifyEngineResult({+ exitCode,+ error: message,+ failure: wasResume && ZCODE_MISSING_SESSION_RE.test(message)+ ? { kind: 'resume-not-found', message, diagnostic: message }+ : undefined,+ sessionId: this.conn.sid,+ }, wasResume)+ }++ private onDeath(code: number, why: string): void {+ if (!this.stopped) {+ this.log(`[session] engine process died ${this.turn ? 'MID-TURN' : 'while idle'}: ${why} (exit ${code})`)+ }+ const wasResume = this.conn.resumed+ this.conn.resumed = false+ this.turn?.resolve(this.failureResult(why, wasResume, code))+ }++ /** Common ACP notification surface; unrecognized update kinds are ignored,+ * so a new event type in a future bridge never breaks a turn. */+ private onUpdate(msg: AcpMsg): void {+ if (msg.method !== 'session/update') return+ const u = (msg.params?.update ?? msg.params) as Record<string, unknown> | undefined+ const kind = typeof u?.sessionUpdate === 'string' ? u.sessionUpdate : null+ if (kind === 'tool_call' && typeof u?.title === 'string') {+ this.log(`[zcode] tool ${u.title}`)+ } else if (kind === 'agent_message_chunk') {+ const content = u?.content as { text?: unknown } | undefined+ if (typeof content?.text === 'string' && content.text) {+ this.onAgentText?.(content.text)+ if (content.text.trim()) this.log(`[zcode] » ${content.text.replace(/\s+/g, ' ').slice(0, 200)}`)+ }+ }+ }++ private log(line: string): void { this.onLog(line) }+}++/** One full bridge lifecycle for the stateless paths (run/classify/probe): a+ * fresh session, one turn, tear-down. Failures fold into the result — a+ * missing bridge or a rejected handshake is a failed turn, not a thrown+ * one. One-shot turns never resume, so hadResume stays false and the generic+ * classifier still tags auth/rate-limit/overflow/transport kinds. */+async function runZcodeAcpTurn(opts: ZcodeTurnOptions): Promise<EngineRunResult & { text: string }> {+ const chunks: string[] = []+ const session = new ZcodeSession(opts.cwd, opts.env, {+ home: opts.cwd,+ env: opts.env,+ model: opts.model,+ standingPrompt: null,+ resumeSessionId: null,+ onLog: opts.onLog ?? (() => {}),+ onHopUsage: opts.onHopUsage,+ onAgentText: (text) => chunks.push(text),+ signal: opts.signal,+ })+ try {+ return { ...await session.send(opts.prompt), text: chunks.join('') }+ } finally {+ await session.stop({ force: true })+ }+}++class ZcodeAdapter implements EngineAdapter {+ readonly id = 'zcode' as const+ readonly bin = 'zcode'++ async seedHome(home: string, persona: EnginePersona): Promise<void> {+ await ensureCommonHome(home)+ // zcode-acp-server's skill discovery scans PROJECT skills from+ // .agents/skills/ in the session cwd (the same shared directory+ // Antigravity reads) — not a zcode-specific folder.+ await mkdir(join(home, '.agents', 'skills'), { recursive: true })+ await atomicAgentWrite(+ join(home, 'AGENTS.md'),+ PERSONA_HEADER(persona, { personaFile: 'AGENTS.md', skillsDir: '.agents/skills/' }),+ )+ }++ run(args: EngineRunArgs): Promise<EngineRunResult> {+ return runZcodeAcpTurn({+ cwd: args.home,+ env: args.env,+ prompt: args.prompt,+ model: args.model,+ signal: args.signal,+ onLog: args.onLog,+ onHopUsage: args.onHopUsage,+ })+ }++ startSession(args: EngineSessionArgs): EngineSession | null {+ return new ZcodeSession(args.home, args.env, args)+ }++ classify(args: EngineClassifyArgs): Promise<EngineClassifyResult> {+ // One fresh bridge process in the neutral triage cwd: slower than Claude's+ // restricted one-shot, but the bridge has no cheaper no-tool surface.+ return runZcodeAcpTurn({+ cwd: args.cwd,+ env: args.env,+ prompt: args.prompt,+ model: args.model,+ signal: args.signal,+ onLog: args.onLog,+ })+ }++ probe(args: EngineProbeArgs): Promise<EngineClassifyResult> {+ // Both tiers run the same bridge probe: the model catalog is the+ // operator's zcode config, so there is no first-party cheap alias to pin.+ return runZcodeAcpTurn({ cwd: args.cwd, env: args.env, prompt: DOCTOR_PROMPT, signal: args.signal })+ }++ async probeWake(args: EngineWakeProbeArgs): Promise<EngineWakeProbeResult> {+ // The wake path IS the bridge handshake on every platform — never skipped.+ // Run a real session against the same spawn the wake uses and wait for the+ // handshake to settle, then tear down; the bridge's lazy session/new means+ // the probe leaves no backend session behind.+ const session = new ZcodeSession(args.cwd, args.env, {+ home: args.cwd,+ env: args.env,+ standingPrompt: null,+ resumeSessionId: null,+ onLog: () => {},+ signal: args.signal,+ })+ try {+ await session.whenReady()+ return { ok: true, detail: '' }+ } catch (err) {+ const why = args.signal.aborted+ ? 'aborted (timeout)'+ : err instanceof Error ? err.message : String(err)+ return { ok: false, detail: `zcode bridge handshake failed: ${why}`.slice(0, 240) }+ } finally {+ await session.stop({ force: true })+ }+ }+}+// ─── cursor ───────────────────────────────────────────────────────────────//// Cursor Agent (the `cursor-agent` CLI bundled with Cursor, 2026.08.11-e8db854)@@ -5268,6 +5755,7 @@ const ADAPTERS: Record<EngineId, EngineAdapter> = {gemini: new GeminiAdapter(),qwen: new QwenAdapter(),antigravity: new AntigravityAdapter(),+ zcode: new ZcodeAdapter(),}export function getAdapter(id: EngineId): EngineAdapter {diff --git a/server/src/agents/computer/model-catalog.ts b/server/src/agents/computer/model-catalog.tsindex ed78d72..d2827f4 100644--- a/server/src/agents/computer/model-catalog.ts+++ b/server/src/agents/computer/model-catalog.ts@@ -123,6 +123,17 @@ const PRESETS: Record<EngineId, EngineModelCatalog> = {fastModelScope: 'agent',source: 'presets',},+ zcode: {+ // The model namespace is the operator's zcode config (GLM plan or a+ // third-party provider), so there is no first-party preset to name —+ // supportsCustom lets an agent pin any id their zcode install accepts.+ models: [],+ defaultModel: null,+ defaultFastModel: null,+ supportsCustom: true,+ fastModelScope: 'agent',+ source: 'presets',+ },}const MODEL_PROBE_TIMEOUT_MS = 10_000diff --git a/server/src/agents/computer/registry.ts b/server/src/agents/computer/registry.tsindex c738ef0..b408249 100644--- a/server/src/agents/computer/registry.ts+++ b/server/src/agents/computer/registry.ts@@ -23,7 +23,7 @@ import { signAgentToken } from '../runtime/jwt.js'import type { EngineModelCatalog, EngineModelOption, FastModelScope, ModelCatalogSource } from './model-catalog.js'export type ComputerKind = 'cloud' | 'local' | 'vps'-export type EngineId = 'managed' | 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode' | 'pi' | 'gemini' | 'qwen' | 'antigravity'+export type EngineId = 'managed' | 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode' | 'pi' | 'gemini' | 'qwen' | 'antigravity' | 'zcode'export type ComputerStatus = 'online' | 'offline' | 'busy'/** How long a paired computer can go without a heartbeat before the sweep@@ -63,6 +63,7 @@ const PAIRABLE: Record<Exclude<EngineId, 'managed'>, true> = {claude: true, codex: true, grok: true, cursor: true, opencode: true, pi: true, gemini: true,qwen: true,antigravity: true,+ zcode: true,}export const PAIRABLE_ENGINES: ReadonlySet<string> = new Set<string>(Object.keys(PAIRABLE))@@ -114,6 +115,7 @@ const ENGINE_BINS: Record<Exclude<EngineId, 'managed'>, string> = {gemini: 'gemini',qwen: 'qwen',antigravity: 'agy',+ zcode: 'zcode',}/** Cached PATH snapshot from the daemon. The app reads this; it never probes. */@@ -680,6 +682,7 @@ export async function listAgentsForComputer(computerId: string, supportsProviderconst geminiDefault = process.env.CUMORA_DEFAULT_GEMINI_MODEL?.trim() || nullconst qwenDefault = process.env.CUMORA_DEFAULT_QWEN_MODEL?.trim() || nullconst antigravityDefault = process.env.CUMORA_DEFAULT_ANTIGRAVITY_MODEL?.trim() || null+ const zcodeDefault = process.env.CUMORA_DEFAULT_ZCODE_MODEL?.trim() || nullreturn rows.map((r) => {const { availableEngines, detectedEngines, engineDefaults, ...agent } = r// A profile's endpoint owns its model namespace: neither the computer's@@ -727,6 +730,8 @@ export async function listAgentsForComputer(computerId: string, supportsProvider? qwenDefault: r.engine === 'antigravity'? antigravityDefault+ : r.engine === 'zcode'+ ? zcodeDefault: nullreturn dflt ? { ...agent, model: dflt, fastModel: fastModelWithEngineDefault } : { ...agent, fastModel: fastModelWithEngineDefault }})diff --git a/server/src/agents/llm-ledger.ts b/server/src/agents/llm-ledger.tsindex e6ec906..3cc4e1c 100644--- a/server/src/agents/llm-ledger.ts+++ b/server/src/agents/llm-ledger.ts@@ -75,7 +75,7 @@ export type LlmCallPurpose =| 'agent-image'export type LlmCallStatus = 'ok' | 'rate_limited' | 'timeout' | 'failed'-export type LlmCallSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode' | 'byoa-pi' | 'byoa-gemini' | 'byoa-qwen' | 'byoa-antigravity'+export type LlmCallSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode' | 'byoa-pi' | 'byoa-gemini' | 'byoa-qwen' | 'byoa-antigravity' | 'byoa-zcode'/** Context bound to a tracked client. Every LLM call it makes carries this* shape into the ledger. `purpose` is mandatory; everything else scopes thediff --git a/server/src/agents/observability.ts b/server/src/agents/observability.tsindex 089dd24..c706158 100644--- a/server/src/agents/observability.ts+++ b/server/src/agents/observability.ts@@ -4,7 +4,7 @@ import { pool } from '../db/pool.js'import { EMPTY_USAGE, effectiveCostUsd, modelPriceTable, priceFor, type TokenUsage } from './cost.js'export type AgentRunStatus = 'running' | 'completed' | 'failed' | 'skipped'-export type TriageSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode' | 'byoa-pi' | 'byoa-gemini' | 'byoa-qwen' | 'byoa-antigravity'+export type TriageSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode' | 'byoa-pi' | 'byoa-gemini' | 'byoa-qwen' | 'byoa-antigravity' | 'byoa-zcode'export type AgentEventLevel = 'debug' | 'info' | 'warn' | 'error'type Queryable = Pick<PoolClient, 'query'>diff --git a/server/src/agents/runtime/byoa-source.ts b/server/src/agents/runtime/byoa-source.tsindex 3926185..09ab7d7 100644--- a/server/src/agents/runtime/byoa-source.ts+++ b/server/src/agents/runtime/byoa-source.ts@@ -10,6 +10,7 @@ export const BYOA_SOURCES = ['byoa-gemini','byoa-qwen','byoa-antigravity',+ 'byoa-zcode',] as constexport type ByoaSource = typeof BYOA_SOURCES[number]diff --git a/src/admin/api.ts b/src/admin/api.tsindex 2ee0e3c..9c2335c 100644--- a/src/admin/api.ts+++ b/src/admin/api.ts@@ -120,7 +120,7 @@ export type LlmCallPurpose =| 'palette' | 'gender' | 'avatar-image' | 'agent-image'export type LlmCallStatus = 'ok' | 'rate_limited' | 'timeout' | 'failed'-export type LlmCallSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode' | 'byoa-pi' | 'byoa-gemini' | 'byoa-qwen' | 'byoa-antigravity'+export type LlmCallSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode' | 'byoa-pi' | 'byoa-gemini' | 'byoa-qwen' | 'byoa-antigravity' | 'byoa-zcode'export interface LlmSummary {sinceDays: numberdiff --git a/src/api/client.ts b/src/api/client.tsindex 3ca5e6e..b23fd6e 100644--- a/src/api/client.ts+++ b/src/api/client.ts@@ -417,7 +417,7 @@ export interface ApiAgentRun {}// ── Triage cost-effectiveness ledger ──-export type ApiTriageSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode' | 'byoa-pi' | 'byoa-gemini' | 'byoa-qwen' | 'byoa-antigravity'+export type ApiTriageSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode' | 'byoa-pi' | 'byoa-gemini' | 'byoa-qwen' | 'byoa-antigravity' | 'byoa-zcode'export interface ApiTriageAgentRow {agentId: stringdiff --git a/src/desktop/MeView.tsx b/src/desktop/MeView.tsxindex 0b26976..622ae49 100644--- a/src/desktop/MeView.tsx+++ b/src/desktop/MeView.tsx@@ -789,7 +789,7 @@ type AgentRow = {const CLI_ORDER = ['claude', 'cursor', 'codex', 'grok', 'opencode',- 'pi', 'gemini', 'qwen', 'hermes',+ 'pi', 'gemini', 'qwen', 'zcode', 'hermes',]const COMPUTER_STATUS_KEY: Record<string, MessageKey> = {diff --git a/src/lib/engines.ts b/src/lib/engines.tsindex 430d16b..bf9ae2d 100644--- a/src/lib/engines.ts+++ b/src/lib/engines.ts@@ -10,6 +10,7 @@ export const ENGINE_LABEL: Record<string, string> = {gemini: 'Gemini',qwen: 'Qwen Code',antigravity: 'Antigravity',+ zcode: 'ZCode',hermes: 'Hermes',}@@ -24,6 +25,7 @@ export const ENGINE_BIN: Record<string, string> = {gemini: 'gemini',qwen: 'qwen',antigravity: 'agy',+ zcode: 'zcode',hermes: 'hermes',}@@ -35,7 +37,7 @@ export const ENGINE_BIN: Record<string, string> = {* state that holds a choice, and the set for membership tests. Engine pickers* used to inline their own copy of this list *and* their own copy of the* labels, which is how adding an engine could leave it unselectable. */-export const RUNNABLE_ENGINES = ['claude', 'codex', 'grok', 'cursor', 'opencode', 'pi', 'gemini', 'qwen', 'antigravity'] as const+export const RUNNABLE_ENGINES = ['claude', 'codex', 'grok', 'cursor', 'opencode', 'pi', 'gemini', 'qwen', 'antigravity', 'zcode'] as constexport type RunnableEngineId = typeof RUNNABLE_ENGINES[number]diff --git a/src/locales/en.ts b/src/locales/en.tsindex 819746e..80ec625 100644--- a/src/locales/en.ts+++ b/src/locales/en.ts@@ -475,6 +475,7 @@ export const en = {'agent.modelHintByoaGemini': 'A Gemini CLI model id or alias; blank = Gemini CLI default.','agent.modelHintByoaQwen': 'A Qwen Code model id or configured provider model; blank = Qwen default.','agent.modelHintByoaAntigravity': 'An exact Antigravity model name shown by `agy models` (e.g. Gemini 3.5 Flash (High)).',+ 'agent.modelHintByoaZcode': 'A model id your zcode install accepts (GLM plan model or a configured provider model); blank = ZCode default.','agent.modelHintByoaClaude': "A Claude alias or full name (e.g. opus, sonnet, claude-sonnet-4-6).",'agent.modelHintByoaSuffix': 'Blank = engine default.','agent.modelHintCloud': 'Optional — leave blank to use the system default. Any OpenAI model name works (e.g. gpt-5.5, gpt-5.5-pro, gpt-5.5-mini). Prefix with novita/ to run this agent on Novita instead (e.g. novita/deepseek/deepseek-v3.2).',@@ -487,6 +488,7 @@ export const en = {'agent.fastHintByoaGemini': 'Not used by Gemini; triage follows CUMORA_TRIAGE_MODEL on the computer. Blank = Gemini default.','agent.fastHintByoaQwen': 'Not used by Qwen; triage follows CUMORA_TRIAGE_MODEL on the computer. Blank = Qwen default.','agent.fastHintByoaAntigravity': 'Not used by Antigravity; triage follows CUMORA_TRIAGE_MODEL on the computer. Blank = Antigravity default.',+ 'agent.fastHintByoaZcode': 'Not used by ZCode; triage follows CUMORA_TRIAGE_MODEL on the computer. Blank = ZCode default.','agent.fastHintByoaClaude': "Cheaper/faster model for light auxiliary tasks — maps to Claude's ANTHROPIC_SMALL_FAST_MODEL. Blank = engine default.",'agent.defaultPh': '(default)','agent.runsOnLabel': 'Runs on',diff --git a/src/locales/zh-CN.ts b/src/locales/zh-CN.tsindex 9442db8..51661be 100644--- a/src/locales/zh-CN.ts+++ b/src/locales/zh-CN.ts@@ -477,6 +477,7 @@ export const zhCN: Partial<Record<keyof typeof en, string>> = {'agent.modelHintByoaGemini': 'Gemini CLI 的模型 id 或别名;留空 = Gemini CLI 默认。','agent.modelHintByoaQwen': 'Qwen Code 的模型 id 或已配置的 provider 模型;留空 = Qwen 默认。','agent.modelHintByoaAntigravity': 'Antigravity `agy models` 显示的完整模型名(例如 Gemini 3.5 Flash (High))。',+ 'agent.modelHintByoaZcode': '你的 zcode 所接受的模型 id(GLM 套餐模型或已配置的 provider 模型);留空 = ZCode 默认。','agent.modelHintByoaClaude': 'Claude 别名或全名(例如 opus、sonnet、claude-sonnet-4-6)。','agent.modelHintByoaSuffix': '留空 = 使用引擎默认。','agent.modelHintCloud': '可选 — 留空使用系统默认。任意 OpenAI 模型名都可以(例如 gpt-5.5、gpt-5.5-pro、gpt-5.5-mini)。加 novita/ 前缀可改走 Novita(例如 novita/deepseek/deepseek-v3.2)。',@@ -489,6 +490,7 @@ export const zhCN: Partial<Record<keyof typeof en, string>> = {'agent.fastHintByoaGemini': 'Gemini 用不到这一项;分流跟随该计算机上的 CUMORA_TRIAGE_MODEL。留空 = Gemini 默认。','agent.fastHintByoaQwen': 'Qwen 用不到这一项;分流跟随该计算机上的 CUMORA_TRIAGE_MODEL。留空 = Qwen 默认。','agent.fastHintByoaAntigravity': 'Antigravity 用不到这一项;分流跟随该计算机上的 CUMORA_TRIAGE_MODEL。留空 = Antigravity 默认。',+ 'agent.fastHintByoaZcode': 'ZCode 用不到这一项;分流跟随该计算机上的 CUMORA_TRIAGE_MODEL。留空 = ZCode 默认。','agent.fastHintByoaClaude': "更便宜、更快的轻量任务模型 —— 对应 Claude 的 ANTHROPIC_SMALL_FAST_MODEL。留空 = 引擎默认。",'agent.defaultPh': '(默认)','agent.runsOnLabel': '运行于',diff --git a/src/types.ts b/src/types.tsindex 59766a9..cb1971e 100644--- a/src/types.ts+++ b/src/types.ts@@ -7,7 +7,7 @@ export type Status = 'avail' | 'working' | 'thinking' | 'waiting' | 'resting'export type ComputerKind = 'cloud' | 'local' | 'vps'export type ComputerStatus = 'online' | 'offline' | 'busy'/** Engine an agent's host runs it on. 'managed' = Cumora's server-side loop. */-export type EngineId = 'managed' | 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode' | 'pi' | 'gemini' | 'qwen' | 'antigravity'+export type EngineId = 'managed' | 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode' | 'pi' | 'gemini' | 'qwen' | 'antigravity' | 'zcode'export interface EngineModelOption {id: string