Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

feat(byoa): add OpenCode engine adapter (#74)

OKNOTOKc0dbf4be1533
diff --git a/README.md b/README.md
index b6b1916..3c03487 100644
--- a/README.md
+++ b/README.md
@@ -17,7 +17,7 @@ Cumora is cross-platform team chat where AI agents are first-class participants
Two "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**, or **Cursor Agent** CLI, on your own subscription. 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 the agent's brain becomes your local **Claude Code**, **Codex**, **Grok Build**, **Cursor Agent**, or **OpenCode** CLI, on your own provider account. The server never sees your provider keys. See [`docs/BYOA.md`](docs/BYOA.md).
## Architecture
@@ -94,7 +94,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 as an agent's brain.
+- [`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/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/agent-cli/README.md b/agent-cli/README.md
index 1e4ad9a..037f198 100644
--- a/agent-cli/README.md
+++ b/agent-cli/README.md
@@ -1,7 +1,7 @@
# cumora
Run your [Cumora](https://cumora.ai) agents on your own machine or VPS,
-powered by your **local Claude Code, Codex, Grok Build, or Cursor Agent CLI**
+powered by your **local Claude Code, Codex, Grok Build, Cursor Agent, or OpenCode CLI**
(BYOA — Bring Your Own Agent). One daemon can host many agents; each gets its own isolated
workspace, memory, and skills on that machine.
@@ -21,5 +21,5 @@ npx cumora agent computer --server <your-server-url>
```
Requires **Node ≥ 18** and `claude` (Claude Code), `codex`, `grok` (Grok Build),
-or `cursor-agent` (Cursor) on your `PATH`. The daemon talks to the Cumora server over HTTPS only — it needs no
+`cursor-agent` (Cursor), or `opencode` on your `PATH`. The daemon talks to the Cumora server over HTTPS only — it needs no
database access.
diff --git a/agent-cli/package.json b/agent-cli/package.json
index 73b8f81..aad3b7e 100644
--- a/agent-cli/package.json
+++ b/agent-cli/package.json
@@ -1,7 +1,7 @@
{
"name": "cumora",
"version": "0.3.0",
- "description": "Run Cumora agents on your own machine with Claude Code, Codex, Grok Build, or Cursor Agent (BYOA).",
+ "description": "Run Cumora agents on your own machine with Claude Code, Codex, Grok Build, Cursor Agent, or OpenCode (BYOA).",
"license": "MIT",
"type": "module",
"bin": {
diff --git a/agent-cli/src/cli.ts b/agent-cli/src/cli.ts
index 40e832e..967d4dc 100644
--- a/agent-cli/src/cli.ts
+++ b/agent-cli/src/cli.ts
@@ -21,7 +21,7 @@ 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), or `cursor-agent` (Cursor) on PATH. Get a pairing code from\n' +
+ 'Needs `claude` (Claude Code), `codex`, `grok` (Grok Build), `cursor-agent` (Cursor), or `opencode` on PATH. 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.md
index 51083f7..00fb4f6 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 as the engine)
+# BYOA — Bring Your Own Agent (local Claude Code / Codex / Grok Build / Cursor Agent / OpenCode as the engine)
Every Cumora agent has a "brain" and a host. The managed path is
server-side: `runAgentTurn` in `server/src/agents/turn.ts` runs a
@@ -7,8 +7,9 @@ a per-agent Kubernetes pod (the `agent-computer` image).
**BYOA** lets a user supply the brain instead: a long-running daemon on
the user's own machine (laptop **or** VPS) drives a local **Claude Code**,
-**Codex CLI**, **Grok Build** (`grok`), or **Cursor Agent** (`cursor-agent`) as the reasoning engine, on the
-user's own subscription — the server never holds the user's provider credentials.
+**Codex CLI**, **Grok Build** (`grok`), **Cursor Agent** (`cursor-agent`), or
+**OpenCode** (`opencode`) as the reasoning engine, on the user's own provider
+account — the server never holds the user's provider credentials.
One daemon hosts **many independent agents** — each with its own isolated
home directory, memory, skills, and notes. In Cumora these still appear
as ordinary `kind='agent'` participants; only their engine differs.
@@ -38,7 +39,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). Agents you place here are BYOA agents.
+ Codex / Grok Build / Cursor Agent / OpenCode). Agents you place here are BYOA agents.
```
Computers
@@ -111,7 +112,7 @@ 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-agent one-shot │
+ │ codex app-server / grok ACP / cursor/opencode run │
│ bash → cumora shim → POST /runtime/cli (per-agent JWT)│
└─────────────────────────────────────────────────────────┘
```
@@ -152,8 +153,9 @@ different token".
`GLANCE_YIELD_RULES`, memory rules, privacy boundary) is delivered
once per persistent session out-of-band — `--append-system-prompt-file`
for Claude, `developerInstructions` for Codex, `_meta.rules` for Grok
- ACP. Cursor has no persistent protocol in the tested CLI version, so the
- daemon inlines the standing prompt into each one-shot wake.
+ 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.
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
@@ -162,11 +164,12 @@ different token".
mid-turn is injected into the live session at the next safe stream
boundary; plain group activity gets a content-free nudge (default
on). See COORDINATION.md 3c. Grok Build's ACP `session/prompt` is
- one-in-flight, and Cursor has no persistent stdio session, so mid-turn
- inject is a no-op for those engines and the ping coalesces onto the next wake.
-8. Turn ends → run finished, status back. Per-hop token usage is posted
- to `/runtime/llm-calls`, landing in the same universal `llm_calls`
- ledger as cloud turns. Engine failures surface as a
+ one-in-flight, and Cursor/OpenCode have no persistent stdio session, so
+ mid-turn inject is a no-op for those engines and the ping coalesces onto the
+ next wake.
+8. Turn ends → run finished, status back. Per-hop token usage reported by the
+ engine is posted to `/runtime/llm-calls`, landing in the same universal
+ `llm_calls` ledger as cloud turns. Engine failures surface as a
`byoa_engine_failed` notice (with auth hints); provider rate limits
are absorbed silently (cooldown + pacer), never leaked into chat.
@@ -180,12 +183,13 @@ 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`). Persistent per-agent sessions
-are preferred when the CLI exposes one; Cursor uses one-shot `run()` for every wake.
+engine (`claude`, `codex`, `grok`, `cursor`, `opencode`). Persistent per-agent
+sessions are preferred when the CLI exposes one; Cursor and OpenCode use
+one-shot `run()` for every wake and resume the session id reported by the CLI.
```ts
interface EngineAdapter {
- id: 'claude' | 'codex' | 'grok' | 'cursor'
+ id: 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode'
seedHome(home, persona) // lay out CLAUDE.md/AGENTS.md, skills, dirs
startSession?(args): EngineSession | null // persistent session (primary)
run(args): Promise<…> // one-shot fallback
@@ -200,20 +204,25 @@ interface EngineSession {
}
```
-| Concern | Claude Code | Codex CLI | Grok Build | Cursor Agent |
-| --- | --- | --- | --- | --- |
-| 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` |
-| Standing prompt | `--append-system-prompt-file <home>/.cumora-standing-prompt.md` | `developerInstructions` on `thread/start` | ACP `_meta.rules` | 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>]` |
-| 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 |
-| Memory / persona file | `CLAUDE.md` | `AGENTS.md` | `AGENTS.md` | `AGENTS.md` |
-| 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` |
+| Concern | Claude Code | Codex CLI | Grok Build | Cursor Agent | OpenCode |
+| --- | --- | --- | --- | --- | --- |
+| 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>` |
+| 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 |
+| 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) |
+| 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 |
+| Memory / persona file | `CLAUDE.md` | `AGENTS.md` | `AGENTS.md` | `AGENTS.md` | `AGENTS.md` plus `.opencode/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 |
Sessions carry a resume id (`~/.cumora/sessions/<agentId>.session`); a
failed resume falls back to a fresh thread instead of wedging the agent.
Engines run headless with their permission prompts disabled, scoped to
the agent's isolated home. On Windows the daemon resolves the real
-`claude`/`codex`/`grok`/`cursor-agent` `.cmd` shims and routes large prompts via stdin.
+`claude`/`codex`/`grok`/`cursor-agent`/`opencode` `.cmd` shims and routes large
+prompts via stdin. OpenCode JSONL `step_finish` events are recorded as individual
+provider hops; uncached input, output+reasoning, and cache read/write tokens map
+to Cumora's common usage ledger without double-counting. OpenCode may race its
+final `step_finish` against the terminal idle event, so a clean process exit is
+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.
@@ -256,6 +265,7 @@ CUMORA_ENGINE_MODEL=local CUMORA_TRIAGE_MODEL=local-small cumora agent computer
.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
.claude/settings.json ← permissions (allow Bash)
bin/cumora ← the shim (see below); bin/.runtime-token
memory/MEMORY.md ← the agent's durable memory index
@@ -285,8 +295,8 @@ 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`, or Cursor's login store). Agents are independent in
-all project state and share one engine login per host.
+`~/.codex` / `~/.grok`, Cursor's login store, or OpenCode's config/auth store).
+Agents are independent in all project state and share one engine login per host.
---
@@ -299,7 +309,7 @@ CREATE TABLE computers (
owner_user_id TEXT, -- null for the managed Cumora Cloud row
name TEXT NOT NULL, -- "Cumora Cloud", "MacBook Pro", …
kind TEXT NOT NULL, -- 'cloud' | 'local' | 'vps'
- available_engines JSONB, -- ['claude','codex','grok','cursor'] (daemon-detected)
+ available_engines JSONB, -- ['claude','codex','grok','cursor','opencode'] (daemon-detected)
status TEXT NOT NULL, -- 'online' | 'offline' | 'busy'
last_seen_at TIMESTAMP,
credential_hash TEXT, -- SHA256 of the device token
@@ -312,7 +322,7 @@ CREATE TABLE computers (
-- participants carry their host + engine + models
-- computer_id TEXT (FK → computers.id)
--- engine TEXT ('managed' | 'claude' | 'codex' | 'grok' | 'cursor')
+-- engine TEXT ('managed' | 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode')
-- model TEXT (big-brain override)
-- fast_model TEXT (small-brain override)
```
@@ -401,7 +411,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 subscription) — a stated BYOA benefit. The daemon's semaphores, spawn
+ Cursor subscription or OpenCode provider account) — a stated BYOA benefit. The daemon's semaphores, spawn
pacing, 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/docs/COORDINATION.md b/docs/COORDINATION.md
index 08d055c..c6ce713 100644
--- a/docs/COORDINATION.md
+++ b/docs/COORDINATION.md
@@ -672,6 +672,7 @@ one and re-test. Don't pile on.
| `CUMORA_DEFAULT_CODEX_MODEL` | unset | Same shape for Codex; deliberately not set by default. |
| `CUMORA_DEFAULT_GROK_MODEL` | unset | Same shape for Grok Build. |
| `CUMORA_DEFAULT_CURSOR_MODEL` | unset | Same shape for Cursor Agent; blank lets Cursor use Auto. |
+| `CUMORA_DEFAULT_OPENCODE_MODEL` | unset | Same shape for OpenCode; use its `provider/model` id, or leave blank for the configured default. |
| `CUMORA_BYOA_MAX_CONCURRENT_BIG_BRAIN` | 6 | Per-computer big-brain turn cap. Drop to 2-4 for very tight quotas; raise for higher tiers. |
| `CUMORA_BYOA_MAX_CONCURRENT_TRIAGE` | 8 | Per-computer small-brain (triage) spawn cap. Higher than big-brain because triage is cheap; bounded so the herd can't blow the 30s triage timeout. |
| `CUMORA_BYOA_MIN_SPAWN_INTERVAL_MS` | 500 | Deterministic minimum interval between local-CLI spawn starts — the AdaptivePacer's base (3, 3b). |
diff --git a/scripts/guard-big-brain.mjs b/scripts/guard-big-brain.mjs
index 70ffb2a..5edfb90 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)['"`]/.test(code) && !ALLOW.engineSpawn.includes(rel)) {
+ if (/(?:spawn|execFile\w*|exec)\s*\(\s*['"`](claude|codex|grok|cursor-agent|opencode)['"`]/.test(code) && !ALLOW.engineSpawn.includes(rel)) {
out.push('engine binary spawned outside the engine adapter (bypasses the classify=small / run=big split)')
}
return out
diff --git a/server/src/__tests__/agent-computer-pairing-token.test.ts b/server/src/__tests__/agent-computer-pairing-token.test.ts
index b0ba539..adada04 100644
--- a/server/src/__tests__/agent-computer-pairing-token.test.ts
+++ b/server/src/__tests__/agent-computer-pairing-token.test.ts
@@ -57,7 +57,7 @@ test('company add token is persistent and reattaches an existing host by name',
const paired = await registry.pairComputer({
code: 'company-token',
hostName: 'MacBook Air',
- engines: ['claude', 'cursor', 'bogus'],
+ engines: ['claude', 'cursor', 'opencode', 'bogus'],
deferBroadcast: true,
})
assert.equal(paired?.computerId, 'comp-existing')
@@ -65,7 +65,7 @@ test('company add token is persistent and reattaches an existing host by name',
const update = calls.find((c) => /UPDATE computers\s+SET credential_hash/.test(c.sql))
assert.ok(update, 'existing computer should be updated instead of inserting a duplicate')
- assert.equal(update.params[1], JSON.stringify(['claude', 'cursor']))
+ assert.equal(update.params[1], JSON.stringify(['claude', 'cursor', 'opencode']))
assert.equal(calls.some((c) => /INSERT INTO computers/.test(c.sql)), false)
})
diff --git a/server/src/__tests__/agents-computer-engine-opencode.test.ts b/server/src/__tests__/agents-computer-engine-opencode.test.ts
new file mode 100644
index 0000000..d4ca34a
--- /dev/null
+++ b/server/src/__tests__/agents-computer-engine-opencode.test.ts
@@ -0,0 +1,368 @@
+/**
+ * Contract tests for the BYOA OpenCode adapter.
+ *
+ * OpenCode is not installed in CI. Each test puts a fake `opencode` first on
+ * PATH and drives the JSONL shapes emitted by `opencode run --format json`
+ * v1.18.20.
+ */
+import { existsSync } from 'node:fs'
+import { chmod, mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { delimiter, join } from 'node:path'
+import { afterEach, test } from 'node:test'
+import assert from 'node:assert/strict'
+import { detectEngines, getAdapter, type EngineHopReport } from '../agents/computer/engine.js'
+
+const IS_WIN = process.platform === 'win32'
+const ORIGINAL_PATH = process.env.PATH
+const tempDirs: string[] = []
+
+afterEach(async () => {
+ delete process.env.CUMORA_OPENCODE_ARGS
+ delete process.env.CUMORA_TRIAGE_ARGS
+ process.env.PATH = ORIGINAL_PATH
+ await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })))
+})
+
+const FAKE_OPENCODE = `#!/usr/bin/env node
+'use strict'
+const fs = require('node:fs')
+const argv = process.argv.slice(2)
+const scenario = process.env.FAKE_OPENCODE_SCENARIO || 'ok'
+let stdin = ''
+process.stdin.setEncoding('utf8')
+process.stdin.on('data', (chunk) => { stdin += chunk })
+process.stdin.on('end', () => {
+ const sessionAt = argv.indexOf('--session')
+ const modelAt = argv.indexOf('--model')
+ const sid = sessionAt >= 0 ? argv[sessionAt + 1] : 'ses_opencode_new'
+ const model = modelAt >= 0 ? argv[modelAt + 1] : null
+ if (process.env.FAKE_OPENCODE_LOG) {
+ fs.appendFileSync(process.env.FAKE_OPENCODE_LOG, JSON.stringify({
+ argv, stdin, cwd: process.cwd(), config: process.env.OPENCODE_CONFIG_CONTENT || null,
+ }) + '\\n')
+ }
+ const out = (event) => process.stdout.write(JSON.stringify({ timestamp: Date.now(), sessionID: sid, ...event }) + '\\n')
+ if (scenario === 'stream-error') {
+ out({ type: 'error', error: { name: 'ProviderError', data: { message: 'model unavailable' } } })
+ return
+ }
+ if (scenario === 'nonzero') {
+ process.stderr.write('authentication required\\n')
+ process.exitCode = 2
+ return
+ }
+ out({ type: 'step_start', part: { type: 'step-start' } })
+ if (scenario === 'missing-finish') {
+ out({ type: 'text', part: { type: 'text', text: 'partial', time: { end: Date.now() } } })
+ return
+ }
+ if (scenario === 'multi-hop') {
+ out({ type: 'tool_use', part: { type: 'tool', tool: 'bash', state: { status: 'completed' } } })
+ out({ type: 'step_finish', part: { type: 'step-finish', tokens: {
+ input: 10, output: 2, reasoning: 1, cache: { read: 4, write: 1 },
+ } } })
+ out({ type: 'step_start', part: { type: 'step-start' } })
+ }
+ const textEvent = { type: 'text', part: { type: 'text', text: 'echo:' + stdin, time: { end: Date.now() } } }
+ if (scenario === 'split-unicode') {
+ textEvent.part.text = 'echo:🧪' + stdin
+ const line = Buffer.from(JSON.stringify({ timestamp: Date.now(), sessionID: sid, ...textEvent }) + '\\n')
+ const marker = line.indexOf(Buffer.from('🧪'))
+ process.stdout.write(line.subarray(0, marker + 1))
+ setTimeout(() => {
+ process.stdout.write(line.subarray(marker + 1))
+ out({ type: 'step_finish', part: { type: 'step-finish', tokens: {
+ input: 100, output: 12, reasoning: 3, cache: { read: 40, write: 2 },
+ } } })
+ }, 10)
+ return
+ }
+ out(textEvent)
+ out({ type: 'step_finish', part: { type: 'step-finish', model, tokens: {
+ input: 100, output: 12, reasoning: 3, cache: { read: 40, write: 2 },
+ } } })
+})
+`
+
+interface Fixture {
+ root: string
+ home: string
+ log: string
+ env: NodeJS.ProcessEnv
+}
+
+async function fixture(scenario = 'ok', extraEnv: NodeJS.ProcessEnv = {}): Promise<Fixture> {
+ const root = await mkdtemp(join(tmpdir(), 'cumora-opencode-'))
+ tempDirs.push(root)
+ const binDir = join(root, 'bin')
+ const home = join(root, 'home')
+ const log = join(root, 'fake.log')
+ await mkdir(binDir)
+ await mkdir(home)
+ const fake = join(binDir, 'opencode')
+ await writeFile(fake, FAKE_OPENCODE, 'utf8')
+ await chmod(fake, 0o755)
+ return {
+ root,
+ home,
+ log,
+ env: {
+ ...process.env,
+ ...extraEnv,
+ PATH: `${binDir}${delimiter}${ORIGINAL_PATH ?? ''}`,
+ FAKE_OPENCODE_LOG: log,
+ FAKE_OPENCODE_SCENARIO: scenario,
+ },
+ }
+}
+
+async function fakeLog(f: Fixture): Promise<Array<{
+ argv: string[]
+ stdin: string
+ cwd: string
+ config: string | null
+}>> {
+ if (!existsSync(f.log)) return []
+ return (await readFile(f.log, 'utf8'))
+ .split('\n')
+ .filter(Boolean)
+ .map((line) => JSON.parse(line))
+}
+
+test('opencode seedHome writes AGENTS.md, native skills, and common directories', { skip: IS_WIN }, async () => {
+ const f = await fixture()
+ const adapter = getAdapter('opencode')
+ await adapter.seedHome(f.home, {
+ id: 'opencode', name: 'Open', role: 'Implementer', systemPrompt: 'Implement only.',
+ })
+
+ const agents = await readFile(join(f.home, 'AGENTS.md'), 'utf8')
+ assert.match(agents, /^# Open — Implementer/)
+ assert.match(agents, /Implement only\./)
+ assert.match(agents, /`AGENTS\.md` \(this file\)/)
+ assert.match(agents, /`\.opencode\/skills\/` — your skills/)
+ assert.doesNotMatch(agents, /CLAUDE\.md|\.claude\/skills|\.cursor\/skills/)
+ assert.ok(existsSync(join(f.home, 'memory', 'MEMORY.md')))
+ assert.ok(existsSync(join(f.home, 'workspace')))
+ assert.ok(existsSync(join(f.home, '.opencode', 'skills')))
+})
+
+test('opencode run streams a turn, normalizes usage, and sends the prompt through stdin', { skip: IS_WIN }, async () => {
+ const f = await fixture()
+ const hops: EngineHopReport[] = []
+ const result = await getAdapter('opencode').run({
+ home: f.home,
+ prompt: 'build it & keep $literal',
+ env: f.env,
+ model: 'anthropic/claude-sonnet-4-6',
+ fastModel: null,
+ resumeSessionId: null,
+ onLog: () => {},
+ onHopUsage: (hop) => hops.push(hop),
+ signal: new AbortController().signal,
+ })
+
+ assert.equal(result.exitCode, 0, result.error)
+ assert.equal(result.sessionId, 'ses_opencode_new')
+ assert.equal(result.model, 'anthropic/claude-sonnet-4-6')
+ assert.deepEqual(result.usage, {
+ input_tokens: 100,
+ output_tokens: 15,
+ cache_read_input_tokens: 40,
+ cache_creation_input_tokens: 2,
+ })
+ assert.equal(hops.length, 1)
+ assert.equal(hops[0].model, 'anthropic/claude-sonnet-4-6')
+ assert.equal(hops[0].textChars, 'echo:build it & keep $literal'.length)
+ assert.deepEqual(hops[0].usage, result.usage)
+
+ const call = (await fakeLog(f))[0]
+ assert.ok(call)
+ assert.deepEqual(call.argv.slice(0, 4), ['run', '--format', 'json', '--auto'])
+ assert.equal(call.argv[call.argv.indexOf('--model') + 1], 'anthropic/claude-sonnet-4-6')
+ assert.equal(call.argv.includes('build it & keep $literal'), false, 'large/shell-sensitive prompt must not use argv')
+ assert.equal(call.stdin, 'build it & keep $literal')
+})
+
+test('opencode run resumes a session and uses an honest fallback model label', { skip: IS_WIN }, async () => {
+ const f = await fixture()
+ const hops: EngineHopReport[] = []
+ const result = await getAdapter('opencode').run({
+ home: f.home,
+ prompt: 'continue',
+ env: f.env,
+ model: null,
+ fastModel: null,
+ resumeSessionId: 'ses_existing',
+ onLog: () => {},
+ onHopUsage: (hop) => hops.push(hop),
+ signal: new AbortController().signal,
+ })
+
+ assert.equal(result.exitCode, 0, result.error)
+ assert.equal(result.sessionId, 'ses_existing')
+ assert.equal(result.model, null, 'the stream does not name an unpinned provider model')
+ assert.equal(hops[0]?.model, 'opencode', 'do not invent a provider/model id')
+ const argv = (await fakeLog(f))[0]?.argv ?? []
+ assert.equal(argv[argv.indexOf('--session') + 1], 'ses_existing')
+ assert.equal(getAdapter('opencode').startSession?.({ home: f.home, env: f.env, onLog: () => {} }) ?? null, null)
+})
+
+test('opencode reports every step_finish as a hop and sums turn usage', { skip: IS_WIN }, async () => {
+ const f = await fixture('multi-hop')
+ const hops: EngineHopReport[] = []
+ const result = await getAdapter('opencode').run({
+ home: f.home,
+ prompt: 'two steps',
+ env: f.env,
+ model: 'openai/gpt-5.5',
+ fastModel: null,
+ resumeSessionId: null,
+ onLog: () => {},
+ onHopUsage: (hop) => hops.push(hop),
+ signal: new AbortController().signal,
+ })
+
+ assert.equal(result.exitCode, 0, result.error)
+ assert.equal(hops.length, 2)
+ assert.equal(hops[0].toolUses, 1)
+ assert.deepEqual(result.usage, {
+ input_tokens: 110,
+ output_tokens: 18,
+ cache_read_input_tokens: 44,
+ cache_creation_input_tokens: 3,
+ })
+})
+
+test('opencode triage is tool-free, parses JSONL, and preserves inline provider config', { skip: IS_WIN }, async () => {
+ const f = await fixture('ok', {
+ OPENCODE_CONFIG_CONTENT: JSON.stringify({
+ theme: 'system',
+ agent: { mine: { description: 'keep me', mode: 'primary' } },
+ }),
+ })
+ const result = await getAdapter('opencode').classify({
+ cwd: f.home,
+ prompt: 'classify this',
+ env: f.env,
+ model: 'openai/gpt-5.4-mini',
+ signal: new AbortController().signal,
+ })
+
+ assert.equal(result.error, undefined)
+ assert.equal(result.text, 'echo:classify this')
+ assert.equal(result.model, 'openai/gpt-5.4-mini')
+ assert.deepEqual(result.usage, {
+ input_tokens: 100,
+ output_tokens: 15,
+ cache_read_input_tokens: 40,
+ cache_creation_input_tokens: 2,
+ })
+ const call = (await fakeLog(f))[0]
+ assert.ok(call)
+ assert.equal(call.argv.includes('--auto'), false, 'triage must never auto-approve tools')
+ assert.equal(call.argv[call.argv.indexOf('--agent') + 1], 'cumora-triage')
+ assert.equal(call.stdin, 'classify this')
+ const config = JSON.parse(call.config ?? '{}') as {
+ theme?: string
+ agent?: Record<string, { description?: string; permission?: Record<string, string> }>
+ }
+ assert.equal(config.theme, 'system')
+ assert.equal(config.agent?.mine?.description, 'keep me')
+ assert.equal(config.agent?.['cumora-triage']?.permission?.['*'], 'deny')
+})
+
+test('opencode parser preserves a Unicode JSON line split across chunks', { skip: IS_WIN }, async () => {
+ const f = await fixture('split-unicode')
+ const result = await getAdapter('opencode').classify({
+ cwd: f.home,
+ prompt: 'split',
+ env: f.env,
+ signal: new AbortController().signal,
+ })
+ assert.equal(result.error, undefined)
+ assert.equal(result.text, 'echo:🧪split')
+ assert.equal(result.usage?.output_tokens, 15)
+})
+
+test('opencode stream error fails a turn even when the process exits zero', { skip: IS_WIN }, async () => {
+ const f = await fixture('stream-error')
+ const result = await getAdapter('opencode').run({
+ home: f.home,
+ prompt: 'fail',
+ env: f.env,
+ model: null,
+ fastModel: null,
+ resumeSessionId: null,
+ onLog: () => {},
+ signal: new AbortController().signal,
+ })
+ assert.equal(result.exitCode, 1)
+ assert.match(result.error ?? '', /model unavailable/)
+ assert.equal(result.sessionId, 'ses_opencode_new')
+})
+
+test('opencode accepts a clean exit when the best-effort stream omits step_finish', { skip: IS_WIN }, async () => {
+ const f = await fixture('missing-finish')
+ const result = await getAdapter('opencode').run({
+ home: f.home,
+ prompt: 'unfinished',
+ env: f.env,
+ model: null,
+ fastModel: null,
+ resumeSessionId: null,
+ onLog: () => {},
+ signal: new AbortController().signal,
+ })
+ assert.equal(result.exitCode, 0, result.error)
+ assert.equal(result.sessionId, 'ses_opencode_new')
+ assert.equal(result.usage, undefined)
+})
+
+test('opencode preserves a non-zero process failure instead of misreporting a protocol error', { skip: IS_WIN }, async () => {
+ const f = await fixture('nonzero')
+ const result = await getAdapter('opencode').run({
+ home: f.home,
+ prompt: 'authenticate',
+ env: f.env,
+ model: null,
+ fastModel: null,
+ resumeSessionId: null,
+ onLog: () => {},
+ signal: new AbortController().signal,
+ })
+ assert.equal(result.exitCode, 2)
+ assert.match(result.error ?? '', /authentication required/)
+})
+
+test('opencode custom args keep stdin and resume while making output opaque', { skip: IS_WIN }, async () => {
+ process.env.CUMORA_OPENCODE_ARGS = '--pure'
+ const f = await fixture()
+ const result = await getAdapter('opencode').run({
+ home: f.home,
+ prompt: 'custom',
+ env: f.env,
+ model: 'ignored/by-override',
+ fastModel: null,
+ resumeSessionId: 'ses_custom',
+ onLog: () => {},
+ signal: new AbortController().signal,
+ })
+ assert.equal(result.exitCode, 0, result.error)
+ const call = (await fakeLog(f))[0]
+ assert.deepEqual(call?.argv, ['run', '--pure', '--session', 'ses_custom'])
+ assert.equal(call?.stdin, 'custom')
+})
+
+test('opencode detection and wake probe expose the one-shot contract', { skip: IS_WIN }, async () => {
+ const f = await fixture()
+ process.env.PATH = f.env.PATH
+ assert.ok((await detectEngines()).includes('opencode'))
+ const wake = await getAdapter('opencode').probeWake({
+ cwd: f.home,
+ env: f.env,
+ signal: new AbortController().signal,
+ })
+ assert.deepEqual(wake, { ok: true, detail: '', skipped: true })
+})
diff --git a/server/src/__tests__/guard-big-brain.test.ts b/server/src/__tests__/guard-big-brain.test.ts
index 9112a9e..09b197c 100644
--- a/server/src/__tests__/guard-big-brain.test.ts
+++ b/server/src/__tests__/guard-big-brain.test.ts
@@ -49,10 +49,10 @@ test('R3 — adapter.run() outside the daemon is caught; inside it is allowed',
})
test('R4 — spawning a supported engine binary outside the engine adapter is caught', () => {
- for (const bin of ['claude', 'codex', 'grok', 'cursor-agent']) {
+ for (const bin of ['claude', 'codex', 'grok', 'cursor-agent', 'opencode']) {
assert.ok(lineViolations('server/src/agents/tools.ts', `spawn('${bin}', args)`).length > 0, bin)
}
- assert.deepEqual(lineViolations('server/src/agents/computer/engine.ts', `spawn('cursor-agent', args)`), [])
+ assert.deepEqual(lineViolations('server/src/agents/computer/engine.ts', `spawn('opencode', args)`), [])
})
test('commented-out examples do not trip the guard', () => {
diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.ts
index b9031fb..f9758f6 100644
--- a/server/src/agents/computer/daemon.ts
+++ b/server/src/agents/computer/daemon.ts
@@ -3,7 +3,7 @@
*
* A long-running process on the user's machine (laptop or VPS) that hosts one
* or more of their Cumora agents, using a local engine (Claude Code / Codex /
- * Grok Build / Cursor Agent) as each agent's brain. See docs/BYOA.md.
+ * Grok Build / Cursor Agent / OpenCode) as each agent's brain. See docs/BYOA.md.
*
* It talks to the Cumora server only over HTTP — no DB/Redis — so it can run
* anywhere:
@@ -627,6 +627,9 @@ function authFailureHint(engine: EngineId, detail: string): string {
if (engine === 'cursor') {
return 'Open a terminal on that computer and run `cursor-agent login` (or fix its quota / API key), then wake the agent again.'
}
+ if (engine === 'opencode') {
+ return 'Open a terminal on that computer and run `opencode providers login` (or fix the selected provider/model quota), then wake the agent again.'
+ }
return 'Open Codex on that computer and refresh its login or quota, then wake the agent again.'
}
@@ -639,6 +642,7 @@ function missingEngineMessage(): string {
' - Codex: install the `codex` CLI, then run `codex` once to sign in',
' - 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',
'',
'After that, rerun:',
' npx cumora@latest agent computer --pair <code>',
@@ -650,7 +654,7 @@ function helpText(): string {
'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, or Cursor Agent). Pair once, then it runs in the background.',
+ 'engine (Claude Code, Codex, Grok Build, Cursor Agent, or OpenCode). Pair once, then it runs in the background.',
'',
'Usage:',
' npx cumora@latest agent computer --pair <code> [--server <url>] [--engine <id>]',
@@ -1062,16 +1066,15 @@ class AgentRunner {
return this.hopReporter
}
- /** Map an engine's raw EngineUsage → universal TokenUsage. Both Claude and
- * Codex (which adapters their codex.totals into Claude-shaped fields, see
- * CodexSession.turnUsage) report via the EngineUsage interface, so a single
- * shape covers both. */
+ /** Map every adapter's raw EngineUsage → universal TokenUsage. Adapters
+ * normalize their native counters into this Claude-shaped interface, so a
+ * single ledger path covers every BYOA engine. */
private hopUsageOf(u: EngineUsage): TokenUsage {
return usageFromClaude(u as unknown as Record<string, unknown>)
}
- /** Called by ClaudeSession / CodexSession for every assistant hop (Claude)
- * or every turn-completed (Codex). Pushes one PendingHop into the batched
+ /** Called by engine sessions/stream trackers for every provider hop. Pushes
+ * one PendingHop into the batched
* reporter; never throws. The engine's optional enrichment hints
* (hopIndex/toolUses/textChars) ride along in `extras` — these are exactly
* the columns the operator needs to ANSWER "why was this hop expensive?"
@@ -1263,8 +1266,8 @@ class AgentRunner {
/** The long-lived engine process for this agent (persistent stream-json),
* created lazily and reused across wakes so turns 2..N skip the cold start.
- * Returns null if the engine has no persistent mode (Cursor, Codex fallback,
- * or a custom args override) — the caller then uses one-shot run(). If the
+ * Returns null if the engine has no persistent mode (Cursor/OpenCode, Codex
+ * fallback, or custom args) — the caller then uses one-shot run(). If the
* prior process has died it respawns, resuming this.sessionId so context
* carries across the restart. */
private ensureEngineSession(): EngineSession | null {
@@ -1455,7 +1458,8 @@ class AgentRunner {
const verdict = finalizeTriage(parsed, 'support-model-local')
// Record the gate's cache-aware cost (fire-and-forget). A BYOA triage runs
// LOCAL + cold-session — its input is uncached, the cost this ledger exists
- // to weigh. usage is present for Claude and Cursor; absent for Codex/Grok.
+ // to weigh. usage is present for Claude, Cursor, and OpenCode; absent for
+ // the current Codex/Grok one-shot classifiers.
void this.recordTriageUsage(token, verdict.actionable, verdict.reason, res.usage, res.model)
return verdict
}
@@ -1477,14 +1481,15 @@ class AgentRunner {
}
}
- /** Triage model id for pricing, honoring CUMORA_TRIAGE_MODEL. Cursor has
- * no fixed cheap alias, so its reported stream model wins; the agent model
- * is only a fallback when the stream does not name one. */
+ /** Triage model id for pricing, honoring CUMORA_TRIAGE_MODEL. Cursor and
+ * OpenCode have no universal cheap alias, so a reported/pinned stream model
+ * wins and the agent model is only a fallback. */
private triageModel(): string {
if (process.env.CUMORA_TRIAGE_MODEL) return process.env.CUMORA_TRIAGE_MODEL
if (this.adapter.id === 'claude') return 'haiku'
if (this.adapter.id === 'grok') return 'grok-4.5'
if (this.adapter.id === 'codex') return 'gpt-5.4-mini'
+ if (this.adapter.id === 'opencode') return this.agent.model ?? '<opencode-default>'
return this.agent.model ?? '<cursor-default>'
}
@@ -2167,7 +2172,7 @@ class AgentRunner {
// (with --resume this.sessionId to carry context across the restart).
if (!session.alive) this.engineSession = null
} else {
- // One-shot path: Cursor, Codex fallback, or a custom args override.
+ // One-shot path: Cursor/OpenCode, Codex fallback, or a custom args override.
result = await this.adapter.run({
home: this.home,
prompt,
diff --git a/server/src/agents/computer/engine.ts b/server/src/agents/computer/engine.ts
index aa21184..9d69158 100644
--- a/server/src/agents/computer/engine.ts
+++ b/server/src/agents/computer/engine.ts
@@ -2,7 +2,8 @@
* EngineAdapter — the pluggable "brain" for a BYOA agent.
*
* A BYOA agent's reasoning loop is delegated to a local CLI engine running
- * on the user's machine: Claude Code, Codex, Grok Build, or Cursor Agent. The daemon (daemon.ts) hands
+ * on the user's machine: Claude Code, Codex, Grok Build, Cursor Agent, or
+ * OpenCode. 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
* from that home natively (CLAUDE.md / AGENTS.md, .claude/skills, …) and acts
@@ -15,7 +16,7 @@
* across engine versions. We pick sensible defaults for an isolated,
* user-owned runner and let the user override via env
* (CUMORA_CLAUDE_ARGS / CUMORA_CODEX_ARGS / CUMORA_GROK_ARGS /
- * CUMORA_CURSOR_ARGS, space-split). Correctness of the
+ * CUMORA_CURSOR_ARGS / CUMORA_OPENCODE_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.
*/
@@ -86,10 +87,10 @@ export function resolveSpawn(bin: string): { command: string; shell: boolean; wa
return { command: bin, shell: true, wantsStdinPrompt: true }
}
-export type EngineId = 'claude' | 'codex' | 'grok' | 'cursor'
+export type EngineId = 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode'
/** The pairable engine ids, in the daemon's default detection order. */
-export const ENGINE_IDS: EngineId[] = ['claude', 'codex', 'grok', 'cursor']
+export const ENGINE_IDS: EngineId[] = ['claude', 'codex', 'grok', 'cursor', 'opencode']
export interface EnginePersona {
id: string
@@ -2263,11 +2264,409 @@ class CursorAdapter implements EngineAdapter {
// the session id it reports (see the section note).
}
+// ─── opencode ────────────────────────────────────────────────────────────
+//
+// OpenCode (the `opencode` CLI, contract verified against v1.18.20) is a
+// ONE-SHOT engine in Cumora. `opencode run --format json` starts a process for
+// one wake and emits JSONL events; continuity comes from passing the emitted
+// `sessionID` back through `--session <id>` on the next wake. OpenCode has an
+// ACP server, but that protocol is intended for editor clients and does not buy
+// us the daemon's standing-prompt/session semantics, so the supported path is
+// the documented `run` interface.
+//
+// opencode run --format json --auto [--model provider/model]
+// [--session <id>] # prompt always travels via stdin
+//
+// A `step_finish` event is one provider hop. Its token fields are already
+// disjoint (uncached input, output, reasoning, cache read/write), so the
+// adapter can report honest per-hop ledger rows and sum them for the turn.
+// OpenCode's event loop can race the terminal `session.status=idle` event and
+// omit the final step_finish even after a successful run, so process exit 0 is
+// authoritative; accounting is best-effort rather than a completion gate.
+// OpenCode's JSON stream does not currently include the resolved model when no
+// pin is supplied; in that case the hop uses the explicit `opencode` fallback
+// label rather than inventing a provider/model id.
+//
+// Full turns use `--auto` because the daemon is headless and the agent's home is
+// operator-owned. Triage/doctor deliberately do NOT: they select an injected
+// `cumora-triage` agent whose wildcard permission is `deny`, giving the small
+// brain a hard, tool-free boundary even if the user's normal OpenCode agent is
+// configured to allow shell or edits.
+
+interface OpenCodeTokens {
+ input?: unknown
+ output?: unknown
+ reasoning?: unknown
+ cache?: { read?: unknown; write?: unknown }
+}
+
+interface OpenCodePart {
+ type?: unknown
+ text?: unknown
+ tokens?: OpenCodeTokens
+}
+
+interface OpenCodeEvent {
+ type?: unknown
+ sessionID?: unknown
+ part?: OpenCodePart
+ error?: unknown
+}
+
+function openCodeUsage(tokens: OpenCodeTokens | undefined): EngineUsage | undefined {
+ if (!tokens || typeof tokens !== 'object') return undefined
+ const num = (value: unknown): number =>
+ typeof value === 'number' && Number.isFinite(value) ? Math.max(0, value) : 0
+ return {
+ input_tokens: num(tokens.input),
+ // OpenCode keeps reasoning separate from ordinary output; Cumora's common
+ // usage shape prices both as output tokens, so fold them together here.
+ output_tokens: num(tokens.output) + num(tokens.reasoning),
+ cache_read_input_tokens: num(tokens.cache?.read),
+ cache_creation_input_tokens: num(tokens.cache?.write),
+ }
+}
+
+function addEngineUsage(total: EngineUsage | undefined, next: EngineUsage): EngineUsage {
+ return {
+ input_tokens: (total?.input_tokens ?? 0) + (next.input_tokens ?? 0),
+ output_tokens: (total?.output_tokens ?? 0) + (next.output_tokens ?? 0),
+ cache_read_input_tokens: (total?.cache_read_input_tokens ?? 0) + (next.cache_read_input_tokens ?? 0),
+ cache_creation_input_tokens: (total?.cache_creation_input_tokens ?? 0) + (next.cache_creation_input_tokens ?? 0),
+ }
+}
+
+function objectRecord(value: unknown): value is Record<string, unknown> {
+ return !!value && typeof value === 'object' && !Array.isArray(value)
+}
+
+function openCodeErrorText(value: unknown): string {
+ if (typeof value === 'string') return value
+ if (!objectRecord(value)) return value == null ? 'unknown OpenCode error' : String(value)
+ const data = objectRecord(value.data) ? value.data : null
+ for (const candidate of [data?.message, value.message, value.name]) {
+ if (typeof candidate === 'string' && candidate.trim()) return candidate.trim()
+ }
+ try { return JSON.stringify(value) } catch { return 'unknown OpenCode error' }
+}
+
+/** Fold OpenCode's JSONL into the common turn/result shape. */
+class OpenCodeTurnTracker {
+ sessionId: string | null = null
+ model: string | null
+ usage: EngineUsage | undefined
+ text = ''
+ error: string | null = null
+ private hopStartedAt: number | null = null
+ private hopIndex = 0
+ private hopTextChars = 0
+ private hopToolUses = 0
+
+ constructor(
+ pin: string | null,
+ private readonly onHopUsage?: (report: EngineHopReport) => void,
+ ) {
+ this.model = pin
+ }
+
+ observe(event: OpenCodeEvent): void {
+ if (typeof event.sessionID === 'string' && event.sessionID) this.sessionId = event.sessionID
+
+ if (event.type === 'error') {
+ this.error = openCodeErrorText(event.error)
+ return
+ }
+
+ if (event.type === 'step_start') {
+ this.hopStartedAt = Date.now()
+ this.hopTextChars = 0
+ this.hopToolUses = 0
+ return
+ }
+
+ if (event.type === 'text' && typeof event.part?.text === 'string') {
+ this.text += event.part.text
+ this.hopTextChars += event.part.text.length
+ return
+ }
+
+ if (event.type === 'tool_use') {
+ this.hopToolUses += 1
+ return
+ }
+
+ if (event.type !== 'step_finish') return
+ const hopUsage = openCodeUsage(event.part?.tokens)
+ if (!hopUsage) return
+ this.usage = addEngineUsage(this.usage, hopUsage)
+ this.hopIndex += 1
+ if (this.onHopUsage) {
+ try {
+ this.onHopUsage({
+ model: this.model ?? 'opencode',
+ usage: hopUsage,
+ latencyMs: this.hopStartedAt == null ? undefined : Date.now() - this.hopStartedAt,
+ hopIndex: this.hopIndex,
+ toolUses: this.hopToolUses,
+ textChars: this.hopTextChars,
+ })
+ } catch { /* ledger reporting is best-effort */ }
+ }
+ this.hopStartedAt = null
+ this.hopTextChars = 0
+ this.hopToolUses = 0
+ }
+}
+
+function parseOpenCodeLine(line: string): OpenCodeEvent | null {
+ if (!line.startsWith('{')) return null
+ try { return JSON.parse(line) as OpenCodeEvent } catch { return null }
+}
+
+/** Reuse the battle-tested one-shot process pump (UTF-8/chunk boundaries,
+ * abort handling, bounded failure tails) while folding each complete stdout
+ * line through the OpenCode tracker. */
+async function spawnOpenCodeStream(
+ command: string,
+ argv: string[],
+ opts: {
+ cwd: string
+ env: NodeJS.ProcessEnv
+ prompt: string
+ signal: AbortSignal
+ onLog?: (line: string) => void
+ shell: boolean
+ onHopUsage?: (report: EngineHopReport) => void
+ pin?: string | null
+ },
+): Promise<EngineRunResult & { text: string }> {
+ const tracker = new OpenCodeTurnTracker(opts.pin ?? null, opts.onHopUsage)
+ let processResult: EngineRunResult
+ try {
+ processResult = await spawnEngine(
+ command,
+ argv,
+ {
+ home: opts.cwd,
+ prompt: opts.prompt,
+ env: opts.env,
+ onLog: (line) => {
+ const event = parseOpenCodeLine(line)
+ if (event) tracker.observe(event)
+ opts.onLog?.(line)
+ },
+ signal: opts.signal,
+ },
+ { shell: opts.shell, stdinText: opts.prompt },
+ )
+ } catch (err) {
+ return {
+ exitCode: 1,
+ error: err instanceof Error ? err.message : String(err),
+ sessionId: tracker.sessionId,
+ usage: tracker.usage,
+ model: tracker.model,
+ text: tracker.text,
+ }
+ }
+
+ const eventError = tracker.error
+ ? `engine turn error: ${tracker.error.slice(0, MAX_FAILURE_CHARS)}`
+ : null
+ const streamError = eventError
+ const exitCode = processResult.exitCode !== 0 ? processResult.exitCode : (streamError ? 1 : 0)
+ return {
+ exitCode,
+ // A real process failure (auth, quota, bad flag, abort) is more useful than
+ // the secondary fact that its stream never reached step_finish. Promote a
+ // stream-only error only when the process itself exited cleanly. If the
+ // JSON stream also carried a provider error, append its decoded prose so
+ // stale-session/rate-limit recovery can match it without parsing JSON.
+ error: processResult.exitCode !== 0
+ ? [processResult.error, eventError].filter(Boolean).join('\n')
+ : (streamError ?? undefined),
+ sessionId: tracker.sessionId,
+ usage: tracker.usage,
+ model: tracker.model,
+ text: tracker.text,
+ }
+}
+
+const OPENCODE_TRIAGE_AGENT = 'cumora-triage'
+
+/** Inject a reserved, tool-free agent as the final inline config layer while
+ * preserving any provider/plugin config the operator already supplied there. */
+function openCodeTriageEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
+ let inline: Record<string, unknown> = {}
+ const raw = env.OPENCODE_CONFIG_CONTENT?.trim()
+ if (raw) {
+ let parsed: unknown
+ try { parsed = JSON.parse(raw) }
+ catch (err) {
+ throw new Error(`OPENCODE_CONFIG_CONTENT is not valid JSON: ${err instanceof Error ? err.message : String(err)}`)
+ }
+ if (!objectRecord(parsed)) throw new Error('OPENCODE_CONFIG_CONTENT must be a JSON object')
+ inline = parsed
+ }
+ const agents = objectRecord(inline.agent) ? inline.agent : {}
+ return {
+ ...env,
+ OPENCODE_CONFIG_CONTENT: JSON.stringify({
+ ...inline,
+ agent: {
+ ...agents,
+ [OPENCODE_TRIAGE_AGENT]: {
+ description: 'Cumora local small-brain classifier (tool-free)',
+ mode: 'primary',
+ prompt: 'Answer the user directly. Do not call tools or modify anything.',
+ permission: { '*': 'deny' },
+ },
+ },
+ }),
+ }
+}
+
+class OpenCodeAdapter implements EngineAdapter {
+ readonly id = 'opencode' as const
+ readonly bin = 'opencode'
+
+ private turn(prompt: string, args: {
+ cwd: string
+ env: NodeJS.ProcessEnv
+ signal: AbortSignal
+ onLog?: (line: string) => void
+ model?: string | null
+ resumeSessionId?: string | null
+ onHopUsage?: (report: EngineHopReport) => void
+ }): Promise<EngineRunResult & { text: string }> {
+ const { command, shell } = resolveSpawn(this.bin)
+ const model = args.model ? ['--model', args.model] : []
+ const resume = args.resumeSessionId ? ['--session', args.resumeSessionId] : []
+ return spawnOpenCodeStream(
+ command,
+ ['run', '--format', 'json', '--auto', ...resume, ...model],
+ {
+ cwd: args.cwd,
+ env: args.env,
+ prompt,
+ signal: args.signal,
+ onLog: args.onLog,
+ shell,
+ onHopUsage: args.onHopUsage,
+ pin: args.model ?? null,
+ },
+ )
+ }
+
+ private ask(prompt: string, args: {
+ cwd: string
+ env: NodeJS.ProcessEnv
+ signal: AbortSignal
+ onLog?: (line: string) => void
+ model?: string | null
+ }): Promise<EngineRunResult & { text: string }> {
+ const { command, shell } = resolveSpawn(this.bin)
+ const model = args.model ? ['--model', args.model] : []
+ return spawnOpenCodeStream(
+ command,
+ ['run', '--format', 'json', '--agent', OPENCODE_TRIAGE_AGENT, ...model],
+ {
+ cwd: args.cwd,
+ env: openCodeTriageEnv(args.env),
+ prompt,
+ signal: args.signal,
+ onLog: args.onLog,
+ shell,
+ pin: args.model ?? null,
+ },
+ )
+ }
+
+ async classify(args: EngineClassifyArgs): Promise<EngineClassifyResult> {
+ const flags = extraArgs('CUMORA_TRIAGE_ARGS')
+ if (flags.length) {
+ // User-owned output flags remain an escape hatch, but the reserved agent
+ // is appended last so the triage process stays tool-free.
+ const { command, shell } = resolveSpawn(this.bin)
+ return spawnCapture(command, ['run', ...flags, '--agent', OPENCODE_TRIAGE_AGENT], {
+ cwd: args.cwd,
+ env: openCodeTriageEnv(args.env),
+ signal: args.signal,
+ onLog: args.onLog,
+ shell,
+ stdinText: args.prompt,
+ })
+ }
+ const result = await this.ask(args.prompt, {
+ cwd: args.cwd,
+ env: args.env,
+ signal: args.signal,
+ onLog: args.onLog,
+ model: args.model,
+ })
+ return { text: result.text, error: result.error, usage: result.usage, model: result.model }
+ }
+
+ async probe(args: EngineProbeArgs): Promise<EngineClassifyResult> {
+ // OpenCode has no universal cheap model alias: provider/model ids are
+ // operator-specific. The small tier honors CUMORA_TRIAGE_MODEL; otherwise
+ // both probes use the operator's configured default.
+ const model = args.tier === 'small' ? (process.env.CUMORA_TRIAGE_MODEL?.trim() || null) : null
+ const result = await this.ask(DOCTOR_PROMPT, {
+ cwd: args.cwd,
+ env: args.env,
+ signal: args.signal,
+ model,
+ })
+ return { text: result.text, error: result.error, usage: result.usage, model: result.model }
+ }
+
+ probeWake(_args: EngineWakeProbeArgs): Promise<EngineWakeProbeResult> {
+ // The real wake is the same one-shot `opencode run` shape probe() already
+ // exercises; --session only adds continuity, not a second protocol.
+ return Promise.resolve({ ok: true, detail: '', skipped: true })
+ }
+
+ async seedHome(home: string, persona: EnginePersona): Promise<void> {
+ await ensureCommonHome(home)
+ await mkdir(join(home, '.opencode', 'skills'), { recursive: true })
+ await writeFile(
+ join(home, 'AGENTS.md'),
+ PERSONA_HEADER(persona, { personaFile: 'AGENTS.md', skillsDir: '.opencode/skills/' }),
+ 'utf8',
+ )
+ }
+
+ async run(args: EngineRunArgs): Promise<EngineRunResult> {
+ const flags = extraArgs('CUMORA_OPENCODE_ARGS')
+ if (flags.length) {
+ // Whole user-owned run-flag override: output becomes opaque, but preserve
+ // the session id and stdin prompt so continuity and Windows safety remain.
+ const resume = args.resumeSessionId ? ['--session', args.resumeSessionId] : []
+ const { command, shell } = resolveSpawn(this.bin)
+ return spawnEngine(command, ['run', ...flags, ...resume], args, { shell, stdinText: args.prompt })
+ }
+ return this.turn(args.prompt, {
+ cwd: args.home,
+ env: args.env,
+ signal: args.signal,
+ onLog: args.onLog,
+ model: args.model,
+ resumeSessionId: args.resumeSessionId,
+ onHopUsage: args.onHopUsage,
+ })
+ }
+
+ // No startSession: the documented headless contract is one `run` process per
+ // wake; --session re-opens the same conversation in that fresh process.
+}
+
const ADAPTERS: Record<EngineId, EngineAdapter> = {
claude: new ClaudeAdapter(),
codex: new CodexAdapter(),
grok: new GrokAdapter(),
cursor: new CursorAdapter(),
+ opencode: new OpenCodeAdapter(),
}
export function getAdapter(id: EngineId): EngineAdapter {
@@ -2325,9 +2724,10 @@ export interface EngineHealth {
big: BrainHealth | null
small: BrainHealth | null
/** Wake-path protocol health (codex app-server JSON-RPC handshake; claude
- * persistent-session flag set; grok ACP stdio handshake). Separate signal from big/small because the
- * failure modes are different — those are auth/quota; this is protocol/CLI
- * version compatibility. */
+ * persistent-session flag set; grok ACP stdio handshake). Cursor/OpenCode
+ * skip it because their wake path is the same one-shot call as the brain
+ * probe. Separate signal from big/small because those failures are
+ * auth/quota, while this one is protocol/CLI compatibility. */
wake: WakeHealth | null
}
diff --git a/server/src/agents/computer/registry.ts b/server/src/agents/computer/registry.ts
index 9522cee..f9b02da 100644
--- a/server/src/agents/computer/registry.ts
+++ b/server/src/agents/computer/registry.ts
@@ -4,7 +4,7 @@
* A Computer is the host an agent runs on (see docs/BYOA.md). Cumora Cloud
* is the built-in managed computer; the user pairs their own machines (a
* Mac, a VPS) which run the `cumora agent computer` daemon and a local
- * engine (Claude Code / Codex / Grok Build / Cursor Agent).
+ * engine (Claude Code / Codex / Grok Build / Cursor Agent / OpenCode).
*
* This module owns the data-access + credential plumbing so the route
* layer (api/router.ts) stays thin and this logic stays unit-testable:
@@ -20,7 +20,7 @@ import { publish, CH_STATUS } from '../../redis.js'
import { signAgentToken } from '../runtime/jwt.js'
export type ComputerKind = 'cloud' | 'local' | 'vps'
-export type EngineId = 'managed' | 'claude' | 'codex' | 'grok' | 'cursor'
+export type EngineId = 'managed' | 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode'
export type ComputerStatus = 'online' | 'offline' | 'busy'
/** How long a paired computer can go without a heartbeat before the sweep
@@ -45,7 +45,7 @@ export async function announceComputerOnline(computerId: string, companyId: stri
}
/** Engines a paired (non-cloud) computer is allowed to advertise. */
-const PAIRABLE_ENGINES: ReadonlySet<string> = new Set(['claude', 'codex', 'grok', 'cursor'])
+const PAIRABLE_ENGINES: ReadonlySet<string> = new Set(['claude', 'codex', 'grok', 'cursor', 'opencode'])
export interface ComputerRow {
id: string
@@ -350,7 +350,8 @@ export async function mintAgentRuntimeToken(args: {
*
* When a row has no explicit model, fall back to the deploy-level default
* (CUMORA_DEFAULT_CLAUDE_MODEL / CUMORA_DEFAULT_CODEX_MODEL /
- * CUMORA_DEFAULT_GROK_MODEL / CUMORA_DEFAULT_CURSOR_MODEL) so every BYOA
+ * CUMORA_DEFAULT_GROK_MODEL / CUMORA_DEFAULT_CURSOR_MODEL /
+ * CUMORA_DEFAULT_OPENCODE_MODEL) so every BYOA
* daemon gets a consistent pin — independent of whatever model the local
* engine CLI happens to default to today. Critical: a model
* upgrade in the underlying CLI (e.g. claude 4.7 → 4.8) silently changes
@@ -368,9 +369,20 @@ export async function listAgentsForComputer(computerId: string): Promise<
const codexDefault = process.env.CUMORA_DEFAULT_CODEX_MODEL?.trim() || null
const grokDefault = process.env.CUMORA_DEFAULT_GROK_MODEL?.trim() || null
const cursorDefault = process.env.CUMORA_DEFAULT_CURSOR_MODEL?.trim() || null
+ const openCodeDefault = process.env.CUMORA_DEFAULT_OPENCODE_MODEL?.trim() || null
return rows.map((r) => {
if (r.model) return r
- const dflt = r.engine === 'codex' ? codexDefault : r.engine === 'claude' ? claudeDefault : r.engine === 'grok' ? grokDefault : r.engine === 'cursor' ? cursorDefault : null
+ const dflt = r.engine === 'codex'
+ ? codexDefault
+ : r.engine === 'claude'
+ ? claudeDefault
+ : r.engine === 'grok'
+ ? grokDefault
+ : r.engine === 'cursor'
+ ? cursorDefault
+ : r.engine === 'opencode'
+ ? openCodeDefault
+ : null
return dflt ? { ...r, model: dflt } : r
})
}
diff --git a/server/src/agents/llm-ledger.ts b/server/src/agents/llm-ledger.ts
index af8fb9b..6525bfa 100644
--- a/server/src/agents/llm-ledger.ts
+++ b/server/src/agents/llm-ledger.ts
@@ -71,7 +71,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'
+export type LlmCallSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode'
/** Context bound to a tracked client. Every LLM call it makes carries this
* shape into the ledger. `purpose` is mandatory; everything else scopes the
diff --git a/server/src/agents/observability.ts b/server/src/agents/observability.ts
index 2383fee..543f151 100644
--- a/server/src/agents/observability.ts
+++ b/server/src/agents/observability.ts
@@ -3,7 +3,7 @@ import { pool } from '../db/pool.js'
import { effectiveCostUsd, priceFor, modelPriceTable, EMPTY_USAGE, type TokenUsage } from './cost.js'
export type AgentRunStatus = 'running' | 'completed' | 'failed' | 'skipped'
-export type TriageSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor'
+export type TriageSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode'
export type AgentEventLevel = 'debug' | 'info' | 'warn' | 'error'
const MAX_STRING_CHARS = 24_000
diff --git a/server/src/agents/runtime/server.ts b/server/src/agents/runtime/server.ts
index 0c34717..55c0b40 100644
--- a/server/src/agents/runtime/server.ts
+++ b/server/src/agents/runtime/server.ts
@@ -421,7 +421,8 @@ runtimeRouter.post('/triage', withAgent(async (c, req, res) => {
// per turn-completed (Codex) and batches them into one POST per N hops or
// every ~250ms (whichever first). This endpoint accepts a batch + inserts
// one llm_calls row per hop with the appropriate source ('byoa-claude' |
-// 'byoa-codex' | 'byoa-grok' | 'byoa-cursor'). Fire-and-forget; a DB hiccup must never break the wake.
+// 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode').
+// Fire-and-forget; a DB hiccup must never break the wake.
runtimeRouter.post('/llm-calls', withAgent(async (c, req, res) => {
const body = req.body as {
source?: string
@@ -441,7 +442,11 @@ runtimeRouter.post('/llm-calls', withAgent(async (c, req, res) => {
extras?: Record<string, unknown>
}>
} | undefined
- const source = (body?.source === 'byoa-claude' || body?.source === 'byoa-codex' || body?.source === 'byoa-grok' || body?.source === 'byoa-cursor') ? body.source : 'byoa-claude'
+ const source = (
+ body?.source === 'byoa-claude' || body?.source === 'byoa-codex' ||
+ body?.source === 'byoa-grok' || body?.source === 'byoa-cursor' ||
+ body?.source === 'byoa-opencode'
+ ) ? body.source : 'byoa-claude'
const daemonVersion = typeof body?.daemonVersion === 'string' && body.daemonVersion.trim() ? body.daemonVersion.trim().slice(0, 32) : null
const hops = Array.isArray(body?.hops) ? body!.hops : []
if (hops.length === 0) { res.json({ ok: true, inserted: 0 }); return }
diff --git a/server/src/api/router.ts b/server/src/api/router.ts
index e965f3c..5f07bcb 100644
--- a/server/src/api/router.ts
+++ b/server/src/api/router.ts
@@ -1099,7 +1099,10 @@ api.post('/computers/pair', safe(async (req, res) => {
// and any adopted agent are created with. Fall back to Claude if unreported.
try {
if ((await companyTier(paired.companyId)) === 'free') {
- const engine = (engines[0] === 'claude' || engines[0] === 'codex' || engines[0] === 'grok' || engines[0] === 'cursor') ? engines[0] : 'claude'
+ const engine = (
+ engines[0] === 'claude' || engines[0] === 'codex' || engines[0] === 'grok' ||
+ engines[0] === 'cursor' || engines[0] === 'opencode'
+ ) ? engines[0] : 'claude'
// Adopt only agents that are stranded on the managed Cumora Cloud (or
// unassigned) onto the just-paired machine — earlier builds' boot backfill
// wrongly seeded free starters on cloud, where free can't run them. Agents
diff --git a/server/src/db/migrate.ts b/server/src/db/migrate.ts
index f307f2a..e1b8fd0 100644
--- a/server/src/db/migrate.ts
+++ b/server/src/db/migrate.ts
@@ -212,7 +212,7 @@ CREATE TABLE IF NOT EXISTS agent_triages (
id TEXT PRIMARY KEY,
agent_id TEXT NOT NULL,
company_id TEXT,
- source TEXT NOT NULL, -- cloud | byoa-claude | byoa-codex | byoa-grok | byoa-cursor
+ source TEXT NOT NULL, -- cloud | byoa-claude | byoa-codex | byoa-grok | byoa-cursor | byoa-opencode
model TEXT,
actionable BOOLEAN NOT NULL DEFAULT FALSE, -- verdict: woke the big brain?
reason TEXT,
@@ -241,7 +241,7 @@ CREATE INDEX IF NOT EXISTS idx_agent_triages_agent_created ON agent_triages(agen
-- - WHO: company_id (tenant), agent_id (when applicable), run_id (when part
-- of a turn), conversation_id (when applicable, e.g. convene).
-- - WHAT: purpose (the business reason), model, source (cloud|byoa-claude|
--- byoa-codex|byoa-grok|byoa-cursor — almost always 'cloud' here; BYOA local triages still
+-- byoa-codex|byoa-grok|byoa-cursor|byoa-opencode — almost always 'cloud' here; BYOA local triages still
-- write to agent_triages with their own source).
-- - HOW MUCH: cache-aware token breakdown + cost_usd (computed at insert
-- via cost.ts → priceFor; cost_estimated flags seeded vs operator-
@@ -1473,7 +1473,7 @@ CREATE TABLE IF NOT EXISTS computers (
owner_user_id TEXT, -- NULL for the managed Cumora Cloud row
name TEXT NOT NULL, -- "Cumora Cloud", "MacBook Pro", "prod-vps-01"
kind TEXT NOT NULL, -- 'cloud' | 'local' | 'vps'
- available_engines JSONB NOT NULL DEFAULT '[]'::jsonb, -- ['claude','codex','grok','cursor']; ['managed'] for cloud
+ available_engines JSONB NOT NULL DEFAULT '[]'::jsonb, -- ['claude','codex','grok','cursor','opencode']; ['managed'] for cloud
status TEXT NOT NULL DEFAULT 'offline', -- 'online' | 'offline' | 'busy'
last_seen_at TIMESTAMP WITH TIME ZONE,
credential_hash TEXT, -- SHA256 of the device token; NULL for cloud
@@ -1495,7 +1495,7 @@ ALTER TABLE computers ADD COLUMN IF NOT EXISTS daemon_supervised BOOLEAN;
-- a 'cloud' computer, means managed (current pod behavior). A 'local' /
-- 'vps' computer means BYOA: wakes go to the paired daemon, no pod.
ALTER TABLE participants ADD COLUMN IF NOT EXISTS computer_id TEXT;
-ALTER TABLE participants ADD COLUMN IF NOT EXISTS engine TEXT; -- 'managed' | 'claude' | 'codex' | 'grok' | 'cursor'
+ALTER TABLE participants ADD COLUMN IF NOT EXISTS engine TEXT; -- 'managed' | 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode'
-- Per-agent model overrides. "model" (added earlier) is the big-brain / main
-- reasoning model; "fast_model" is the small-brain model for cheap auxiliary
-- work. For BYOA agents these pass through to the engine as --model (big) and,
diff --git a/src/admin/api.ts b/src/admin/api.ts
index 403d4ad..34ee47b 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'
+export type LlmCallSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode'
export interface LlmSummary {
sinceDays: number
diff --git a/src/api/client.ts b/src/api/client.ts
index 96f2d8b..7985187 100644
--- a/src/api/client.ts
+++ b/src/api/client.ts
@@ -401,7 +401,7 @@ export interface ApiAgentRun {
}
// ── Triage cost-effectiveness ledger ──
-export type ApiTriageSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor'
+export type ApiTriageSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode'
export interface ApiTriageAgentRow {
agentId: string
diff --git a/src/components/AgentEditor.tsx b/src/components/AgentEditor.tsx
index d36b74d..8ad207c 100644
--- a/src/components/AgentEditor.tsx
+++ b/src/components/AgentEditor.tsx
@@ -241,7 +241,7 @@ export function AgentEditor({ agent, onClose }: Props) {
<Field
label={isByoa ? t('agent.modelLabelByoa') : t('agent.modelLabel')}
hint={isByoa
- ? `${t('agent.modelHintByoaPrefix')} ${engine === 'codex' ? t('agent.modelHintByoaCodex') : engine === 'grok' ? t('agent.modelHintByoaGrok') : engine === 'cursor' ? t('agent.modelHintByoaCursor') : t('agent.modelHintByoaClaude')} ${t('agent.modelHintByoaSuffix')}`
+ ? `${t('agent.modelHintByoaPrefix')} ${engine === 'codex' ? t('agent.modelHintByoaCodex') : engine === 'grok' ? t('agent.modelHintByoaGrok') : engine === 'cursor' ? t('agent.modelHintByoaCursor') : engine === 'opencode' ? t('agent.modelHintByoaOpenCode') : t('agent.modelHintByoaClaude')} ${t('agent.modelHintByoaSuffix')}`
: t('agent.modelHintCloud')}
>
<Input
@@ -263,7 +263,9 @@ export function AgentEditor({ agent, onClose }: Props) {
? t('agent.fastHintByoaGrok')
: engine === 'cursor'
? t('agent.fastHintByoaCursor')
- : t('agent.fastHintByoaClaude')}
+ : engine === 'opencode'
+ ? t('agent.fastHintByoaOpenCode')
+ : t('agent.fastHintByoaClaude')}
>
<Input
type="text"
@@ -311,7 +313,7 @@ export function AgentEditor({ agent, onClose }: Props) {
options={(selectedComputer.availableEngines.length
? selectedComputer.availableEngines
: (['claude'] as EngineId[])
- ).map((en) => ({ value: en, label: en === 'claude' ? t('agent.engineClaude') : en === 'codex' ? t('agent.engineCodex') : en === 'grok' ? t('agent.engineGrok') : en === 'cursor' ? t('agent.engineCursor') : en }))}
+ ).map((en) => ({ value: en, label: en === 'claude' ? t('agent.engineClaude') : en === 'codex' ? t('agent.engineCodex') : en === 'grok' ? t('agent.engineGrok') : en === 'cursor' ? t('agent.engineCursor') : en === 'opencode' ? t('agent.engineOpenCode') : en }))}
/>
</div>
)}
diff --git a/src/desktop/MeView.tsx b/src/desktop/MeView.tsx
index 9680a7b..aca7aa4 100644
--- a/src/desktop/MeView.tsx
+++ b/src/desktop/MeView.tsx
@@ -759,7 +759,7 @@ function SkypeSoundSection() {
// Brand and engine names stay in English in every locale. The values
// below are display labels surfaced to users when we list computers —
// products keep their own casing.
-const ENGINE_LABEL: Record<string, string> = { managed: 'Cumora', claude: 'Claude Code', codex: 'Codex', grok: 'Grok Build', cursor: 'Cursor' }
+const ENGINE_LABEL: Record<string, string> = { managed: 'Cumora', claude: 'Claude Code', codex: 'Codex', grok: 'Grok Build', cursor: 'Cursor', opencode: 'OpenCode' }
const KIND_ICON: Record<string, string> = { cloud: '☁', local: '💻', vps: '🖥' }
const STATUS_COLOR: Record<string, string> = { online: '#3BB273', busy: '#E6A23C', offline: 'var(--ink-300)' }
@@ -775,7 +775,7 @@ function ComputersTab() {
// Engine for a NEWLY added computer's starter/assigned agents. Claude is the
// default (no flag → daemon auto-detects); every other pick is named
// explicitly, or the daemon auto-detects and engines[0] silently wins.
- const [engine, setEngine] = useState<'claude' | 'codex' | 'grok' | 'cursor'>('claude')
+ const [engine, setEngine] = useState<'claude' | 'codex' | 'grok' | 'cursor' | 'opencode'>('claude')
// Default on: install the always-on service (auto-start/restart/update).
const [asService, setAsService] = useState(true)
// Per-computer re-pair (reconnect) command, keyed by computer id.
@@ -921,7 +921,7 @@ function ComputersTab() {
<div className="flex items-center gap-2.5 mb-2.5">
<span className="text-[12px] text-ink-500">{t('me.engineLabel')}</span>
<div className="inline-flex rounded-[9px] p-0.5" style={{ background: 'var(--ink-100)' }}>
- {([['claude', 'Claude Code'], ['codex', 'Codex'], ['grok', 'Grok Build'], ['cursor', 'Cursor']] as const).map(([id, label]) => (
+ {([['claude', 'Claude Code'], ['codex', 'Codex'], ['grok', 'Grok Build'], ['cursor', 'Cursor'], ['opencode', 'OpenCode']] as const).map(([id, label]) => (
<button key={id} type="button" onClick={() => setEngine(id)}
className="px-3 py-1 rounded-[7px] text-[12px] font-semibold transition-colors duration-150"
style={engine === id
diff --git a/src/desktop/ObservabilityView.tsx b/src/desktop/ObservabilityView.tsx
index 52ea2df..c3dd744 100644
--- a/src/desktop/ObservabilityView.tsx
+++ b/src/desktop/ObservabilityView.tsx
@@ -646,8 +646,8 @@ function PriceMenuTable({ rows }: { rows: { model: string; inPer1M: number; cach
const t = useT()
if (rows.length === 0) return null
// Fixed cerebellum aliases: claude→haiku, codex→gpt-5.4-mini,
- // grok→grok-4.5. Cursor has no fixed cheap alias and reports the model its
- // account selected, so it is classified by that model id.
+ // grok→grok-4.5. Cursor/OpenCode have no fixed cheap alias and report the
+ // configured model, so they are classified by that model id.
const isSmall = (m: string) => /haiku|mini|grok-4\.5/i.test(m)
return (
<div className="rounded-[10px] border border-ink-100 bg-paper px-3.5 py-3">
diff --git a/src/desktop/Onboarding.tsx b/src/desktop/Onboarding.tsx
index 2162831..da40d45 100644
--- a/src/desktop/Onboarding.tsx
+++ b/src/desktop/Onboarding.tsx
@@ -21,7 +21,7 @@ export function Onboarding() {
// Claude is the default; ANY other pick must be named explicitly. We DON'T
// append `--engine claude` so a Claude-less machine still auto-detects rather
// than erroring on a Claude it doesn't have.
- const [engine, setEngine] = useState<'claude' | 'codex' | 'grok' | 'cursor'>('claude')
+ const [engine, setEngine] = useState<'claude' | 'codex' | 'grok' | 'cursor' | 'opencode'>('claude')
// Default to installing the always-on service: it auto-starts at sign-in,
// auto-restarts on crash, and auto-updates — so the user isn't tied to a
// terminal that must stay open. Appends `--install-service` to the command.
@@ -87,7 +87,7 @@ export function Onboarding() {
<div className="flex items-center gap-2.5 mb-2.5">
<span className="text-[12px] text-ink-500">{t('onboard.engine')}</span>
<div className="inline-flex rounded-[9px] p-0.5" style={{ background: 'var(--ink-100)' }}>
- {([['claude', 'Claude Code'], ['codex', 'Codex'], ['grok', 'Grok Build'], ['cursor', 'Cursor']] as const).map(([id, label]) => (
+ {([['claude', 'Claude Code'], ['codex', 'Codex'], ['grok', 'Grok Build'], ['cursor', 'Cursor'], ['opencode', 'OpenCode']] as const).map(([id, label]) => (
<button key={id} type="button" onClick={() => setEngine(id)}
className="px-3 py-1 rounded-[7px] text-[12px] font-semibold transition-colors duration-150"
style={engine === id
diff --git a/src/locales/en.ts b/src/locales/en.ts
index ed62d41..008a402 100644
--- a/src/locales/en.ts
+++ b/src/locales/en.ts
@@ -450,6 +450,7 @@ export const en = {
'agent.modelHintByoaCodex': 'A model name (e.g. gpt-5.5, o3).',
'agent.modelHintByoaGrok': 'A Grok model (e.g. grok-4.6).',
'agent.modelHintByoaCursor': 'A Cursor model id or alias; blank = Auto.',
+ 'agent.modelHintByoaOpenCode': 'An OpenCode provider/model id (e.g. anthropic/claude-sonnet-4-6).',
'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).',
@@ -457,10 +458,11 @@ export const en = {
'agent.fastHintByoaCodex': 'Cheaper model for light auxiliary tasks (e.g. gpt-5.4-mini). Blank = same as big-brain.',
'agent.fastHintByoaGrok': 'Cheaper/faster Grok model for light auxiliary tasks (e.g. grok-4.5). Blank = engine default.',
'agent.fastHintByoaCursor': 'Not used by Cursor; triage follows CUMORA_TRIAGE_MODEL on the computer. Blank = Auto.',
+ 'agent.fastHintByoaOpenCode': 'Not used by OpenCode; triage follows CUMORA_TRIAGE_MODEL on the computer. Blank = OpenCode 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',
- 'agent.runsOnHint': "Which computer executes this agent. Cumora Cloud is managed; a computer you've paired runs it on your local Claude Code, Codex, Grok Build, or Cursor Agent.",
+ 'agent.runsOnHint': "Which computer executes this agent. Cumora Cloud is managed; a computer you've paired runs it on your local Claude Code, Codex, Grok Build, Cursor Agent, or OpenCode.",
'agent.offlineSuffix': '(offline)',
'agent.upgradeToPro': '☁ Cumora Cloud — upgrade to Pro',
'agent.engineLabel': 'Engine',
@@ -468,6 +470,7 @@ export const en = {
'agent.engineCodex': 'Codex',
'agent.engineGrok': 'Grok Build',
'agent.engineCursor': 'Cursor',
+ 'agent.engineOpenCode': 'OpenCode',
'agent.computerOfflineMsg': '{name} is offline. Run this on that computer:',
'agent.copyCommand': 'Copy command',
'agent.copied': '✓ Copied!',
@@ -1044,8 +1047,8 @@ export const en = {
'ship.statusArchived': 'Archived',
// ─── onboarding (first-run computer pairing) ─────────────────────
'onboard.title': 'Set up your computer',
- 'onboard.body': 'Your agents run on <strong>your own machine</strong> (or a VPS), powered by your local <span class="font-mono text-[13px]"> Claude Code</span>, <span class="font-mono text-[13px]"> Codex</span>, <span class="font-mono text-[13px]"> Grok Build</span>, or <span class="font-mono text-[13px]"> Cursor</span>. Pair a computer to get started — your starter team will set up there, each with its own isolated workspace, memory, and skills.',
- 'onboard.cmdIntro': 'On the machine you want to host your agents, you’ll run one command. It needs <span class="font-mono">claude</span>, <span class="font-mono">codex</span>, <span class="font-mono">grok</span>, or <span class="font-mono">cursor-agent</span> installed.',
+ 'onboard.body': 'Your agents run on <strong>your own machine</strong> (or a VPS), powered by your local <span class="font-mono text-[13px]"> Claude Code</span>, <span class="font-mono text-[13px]"> Codex</span>, <span class="font-mono text-[13px]"> Grok Build</span>, <span class="font-mono text-[13px]"> Cursor</span>, or <span class="font-mono text-[13px]"> OpenCode</span>. Pair a computer to get started — your starter team will set up there, each with its own isolated workspace, memory, and skills.',
+ 'onboard.cmdIntro': 'On the machine you want to host your agents, you’ll run one command. It needs <span class="font-mono">claude</span>, <span class="font-mono">codex</span>, <span class="font-mono">grok</span>, <span class="font-mono">cursor-agent</span>, or <span class="font-mono">opencode</span> installed.',
'onboard.generating': 'Generating…',
'onboard.addComputer': 'Add a computer',
'onboard.runThis': 'Run this on that machine:',
@@ -1211,7 +1214,7 @@ export const en = {
'me.hideArchived': 'Hide archived',
'me.showArchivedCount': 'Show archived ({n})',
'me.sectionComputers': '↳ Where your agents run',
- 'me.computersIntro': 'Every agent runs on a <strong>Computer</strong>. <em>Cumora Cloud</em> is built in and always on. Pair your own machine or a VPS to run agents on your local <span class="font-mono text-[12px]"> Claude Code</span>, <span class="font-mono text-[12px]"> Codex</span>, <span class="font-mono text-[12px]"> Grok Build</span>, or <span class="font-mono text-[12px]"> Cursor</span> — each agent gets its own isolated workspace, memory and skills there.',
+ 'me.computersIntro': 'Every agent runs on a <strong>Computer</strong>. <em>Cumora Cloud</em> is built in and always on. Pair your own machine or a VPS to run agents on your local <span class="font-mono text-[12px]"> Claude Code</span>, <span class="font-mono text-[12px]"> Codex</span>, <span class="font-mono text-[12px]"> Grok Build</span>, <span class="font-mono text-[12px]"> Cursor</span>, or <span class="font-mono text-[12px]"> OpenCode</span> — each agent gets its own isolated workspace, memory and skills there.',
'me.agentsCountOne': '{n} agent',
'me.agentsCountOther': '{n} agents',
'me.updateAvailableShort': 'update',
@@ -1227,7 +1230,7 @@ export const en = {
'me.copy': 'Copy',
'me.copiedShort': '✓ Copied',
'me.runOnHost': 'Run this on the machine you want to host agents:',
- 'me.engineRequired': 'Needs <span class="font-mono not-italic">claude</span>, <span class="font-mono not-italic">codex</span>, <span class="font-mono not-italic">grok</span>, or <span class="font-mono not-italic">cursor-agent</span> installed. The computer names itself after that machine and appears here once paired. This token stays valid.',
+ 'me.engineRequired': 'Needs <span class="font-mono not-italic">claude</span>, <span class="font-mono not-italic">codex</span>, <span class="font-mono not-italic">grok</span>, <span class="font-mono not-italic">cursor-agent</span>, or <span class="font-mono not-italic">opencode</span> installed. The computer names itself after that machine and appears here once paired. This token stays valid.',
'me.keepInBackground': 'Keep it running in the background',
'me.keepInBackgroundDetail': '— auto-start when you sign in, auto-restart on crash, auto-update. Otherwise this terminal has to stay open.',
'me.done': 'Done',
diff --git a/src/locales/zh-CN.ts b/src/locales/zh-CN.ts
index 019cce6..454da87 100644
--- a/src/locales/zh-CN.ts
+++ b/src/locales/zh-CN.ts
@@ -452,6 +452,7 @@ export const zhCN: Partial<Record<keyof typeof en, string>> = {
'agent.modelHintByoaCodex': '模型名称(例如 gpt-5.5、o3)。',
'agent.modelHintByoaGrok': 'Grok 模型(例如 grok-4.6)。',
'agent.modelHintByoaCursor': 'Cursor 模型 id 或别名;留空 = Auto。',
+ 'agent.modelHintByoaOpenCode': 'OpenCode 的 provider/model id(例如 anthropic/claude-sonnet-4-6)。',
'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)。',
@@ -459,10 +460,11 @@ export const zhCN: Partial<Record<keyof typeof en, string>> = {
'agent.fastHintByoaCodex': '处理轻量辅助任务的便宜模型(例如 gpt-5.4-mini)。留空 = 与主力模型相同。',
'agent.fastHintByoaGrok': '处理轻量辅助任务的更快更便宜的 Grok 模型(例如 grok-4.5)。留空 = 引擎默认。',
'agent.fastHintByoaCursor': 'Cursor 用不到这一项;分流跟随该计算机上的 CUMORA_TRIAGE_MODEL。留空 = Auto。',
+ 'agent.fastHintByoaOpenCode': 'OpenCode 用不到这一项;分流跟随该计算机上的 CUMORA_TRIAGE_MODEL。留空 = OpenCode 默认模型。',
'agent.fastHintByoaClaude': "更便宜、更快的轻量任务模型 —— 对应 Claude 的 ANTHROPIC_SMALL_FAST_MODEL。留空 = 引擎默认。",
'agent.defaultPh': '(默认)',
'agent.runsOnLabel': '运行于',
- 'agent.runsOnHint': '哪个计算机执行这个智能体。Cumora Cloud 是托管的;你已配对的计算机会在本地的 Claude Code、Codex、Grok Build 或 Cursor Agent 上运行。',
+ 'agent.runsOnHint': '哪个计算机执行这个智能体。Cumora Cloud 是托管的;你已配对的计算机会在本地的 Claude Code、Codex、Grok Build、Cursor Agent 或 OpenCode 上运行。',
'agent.offlineSuffix': '(离线)',
'agent.upgradeToPro': '☁ Cumora Cloud — 升级到 Pro',
'agent.engineLabel': '引擎',
@@ -470,6 +472,7 @@ export const zhCN: Partial<Record<keyof typeof en, string>> = {
'agent.engineCodex': 'Codex',
'agent.engineCursor': 'Cursor',
'agent.engineGrok': 'Grok Build',
+ 'agent.engineOpenCode': 'OpenCode',
'agent.computerOfflineMsg': '{name} 当前离线。请在该计算机上运行:',
'agent.copyCommand': '复制命令',
'agent.copied': '✓ 已复制!',
@@ -1045,8 +1048,8 @@ export const zhCN: Partial<Record<keyof typeof en, string>> = {
'ship.statusArchived': '已归档',
// ─── onboarding(首次配对计算机)─────────────────────────────────────
'onboard.title': '设置你的计算机',
- 'onboard.body': '智能体跑在你自己的机器(或 VPS)上,由本地的 <span class="font-mono text-[13px]">Claude Code</span>、<span class="font-mono text-[13px]">Codex</span>、<span class="font-mono text-[13px]">Grok Build</span> 或 <span class="font-mono text-[13px]">Cursor</span> 驱动。配对一台计算机开始吧 —— 初始团队会部署在那里,每人都有独立的 workspace、记忆和技能。',
- 'onboard.cmdIntro': '在你想要托管智能体的机器上,运行这一条命令即可。需要先装好 <span class="font-mono">claude</span>、<span class="font-mono">codex</span>、<span class="font-mono">grok</span> 或 <span class="font-mono">cursor-agent</span>。',
+ 'onboard.body': '智能体跑在你自己的机器(或 VPS)上,由本地的 <span class="font-mono text-[13px]">Claude Code</span>、<span class="font-mono text-[13px]">Codex</span>、<span class="font-mono text-[13px]">Grok Build</span>、<span class="font-mono text-[13px]">Cursor</span> 或 <span class="font-mono text-[13px]">OpenCode</span> 驱动。配对一台计算机开始吧 —— 初始团队会部署在那里,每人都有独立的 workspace、记忆和技能。',
+ 'onboard.cmdIntro': '在你想要托管智能体的机器上,运行这一条命令即可。需要先装好 <span class="font-mono">claude</span>、<span class="font-mono">codex</span>、<span class="font-mono">grok</span>、<span class="font-mono">cursor-agent</span> 或 <span class="font-mono">opencode</span>。',
'onboard.generating': '生成中…',
'onboard.addComputer': '添加一台计算机',
'onboard.runThis': '在那台机器上跑这条命令:',
@@ -1213,7 +1216,7 @@ export const zhCN: Partial<Record<keyof typeof en, string>> = {
'me.hideArchived': '隐藏已归档',
'me.showArchivedCount': '显示已归档 ({n})',
'me.sectionComputers': '↳ 智能体跑在哪',
- 'me.computersIntro': '每位智能体都跑在一台「计算机」上。<em>Cumora Cloud</em> 是内置的、一直在线的。配对你的机器或 VPS,即可在本地的 <span class="font-mono text-[12px]">Claude Code</span>、<span class="font-mono text-[12px]">Codex</span>、<span class="font-mono text-[12px]">Grok Build</span> 或 <span class="font-mono text-[12px]">Cursor</span> 上运行智能体——每位智能体在那里都有自己独立的工作区、记忆和技能。',
+ 'me.computersIntro': '每位智能体都跑在一台「计算机」上。<em>Cumora Cloud</em> 是内置的、一直在线的。配对你的机器或 VPS,即可在本地的 <span class="font-mono text-[12px]">Claude Code</span>、<span class="font-mono text-[12px]">Codex</span>、<span class="font-mono text-[12px]">Grok Build</span>、<span class="font-mono text-[12px]">Cursor</span> 或 <span class="font-mono text-[12px]">OpenCode</span> 上运行智能体——每位智能体在那里都有自己独立的工作区、记忆和技能。',
'me.agentsCountOne': '{n} 位智能体',
'me.agentsCountOther': '{n} 位智能体',
'me.updateAvailableShort': '更新',
@@ -1229,7 +1232,7 @@ export const zhCN: Partial<Record<keyof typeof en, string>> = {
'me.copy': '复制',
'me.copiedShort': '✓ 已复制',
'me.runOnHost': '在想要托管智能体的机器上跑这条命令:',
- 'me.engineRequired': '需要装好 <span class="font-mono not-italic">claude</span>、<span class="font-mono not-italic">codex</span>、<span class="font-mono not-italic">grok</span> 或 <span class="font-mono not-italic">cursor-agent</span>。计算机会以那台机器命名,配对后出现在这里。这个令牌长期有效。',
+ 'me.engineRequired': '需要装好 <span class="font-mono not-italic">claude</span>、<span class="font-mono not-italic">codex</span>、<span class="font-mono not-italic">grok</span>、<span class="font-mono not-italic">cursor-agent</span> 或 <span class="font-mono not-italic">opencode</span>。计算机会以那台机器命名,配对后出现在这里。这个令牌长期有效。',
'me.keepInBackground': '让它在后台保持运行',
'me.keepInBackgroundDetail': '—— 登录自启、崩溃自恢复、自动更新。否则这个终端就得一直开着。',
'me.done': '完成',
diff --git a/src/types.ts b/src/types.ts
index 7272681..2a870e6 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'
+export type EngineId = 'managed' | 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode'
export interface Computer {
id: string