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 Cursor Agent engine adapter (#46)
Terry Li2bc664828ab5
diff --git a/README.md b/README.mdindex 8128942..f579a7c 100644--- a/README.md+++ b/README.md@@ -17,7 +17,7 @@ Cumora is cross-platform team chat where AI agents are first-class participantsTwo "brain" paths:- **Cumora Cloud** — each agent runs in a managed per-agent pod; turns run a multi-hop tool-calling loop on the OpenAI Responses API (bash, files, browser, email, memory, skills…).-- **BYOA (Bring Your Own Agent)** — pair your own Mac/VPS with `npx cumora agent computer` and the agent's brain becomes your local **Claude Code** or **Codex** 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**, or **Cursor Agent** CLI, on your own subscription. 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 as an agent's brain.+- [`docs/BYOA.md`](docs/BYOA.md) — Bring Your Own Agent: local Claude Code / Codex / Grok Build / Cursor Agent 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/SHIPPING.md`](docs/SHIPPING.md) — the evidence-backed feature lifecycle shared by humans and agents.diff --git a/agent-cli/README.md b/agent-cli/README.mdindex 9d2ed63..1e4ad9a 100644--- a/agent-cli/README.md+++ b/agent-cli/README.md@@ -1,8 +1,8 @@# cumoraRun your [Cumora](https://cumora.ai) agents on your own machine or VPS,-powered by your **local Claude Code or Codex CLI** (BYOA — Bring Your Own-Agent). One daemon can host many agents; each gets its own isolated+powered by your **local Claude Code, Codex, Grok Build, or Cursor Agent CLI**+(BYOA — Bring Your Own Agent). One daemon can host many agents; each gets its own isolatedworkspace, memory, and skills on that machine.## Usage@@ -20,6 +20,6 @@ Then start the daemon (after pairing, the config is saved):npx cumora agent computer --server <your-server-url>```-Requires **Node ≥ 18** and either `claude` (Claude Code) or `codex` on your-`PATH`. The daemon talks to the Cumora server over HTTPS only — it needs no+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 nodatabase access.diff --git a/agent-cli/package.json b/agent-cli/package.jsonindex f93347e..36635b5 100644--- a/agent-cli/package.json+++ b/agent-cli/package.json@@ -1,7 +1,7 @@{"name": "cumora","version": "0.1.127",- "description": "Run your Cumora agents on your own machine or VPS, powered by your local Claude Code or Codex CLI (BYOA).",+ "description": "Run Cumora agents on your own machine with Claude Code, Codex, Grok Build, or Cursor Agent (BYOA).","license": "MIT","type": "module","bin": {diff --git a/agent-cli/src/cli.ts b/agent-cli/src/cli.tsindex 508250f..40e832e 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`, or `grok` (Grok Build) on PATH. Get a pairing code from\n' ++ 'Needs `claude` (Claude Code), `codex`, `grok` (Grok Build), or `cursor-agent` (Cursor) 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.mdindex cb55b8d..dbe8c2a 100644--- a/docs/BYOA.md+++ b/docs/BYOA.md@@ -1,4 +1,4 @@-# BYOA — Bring Your Own Agent (local Claude Code / Codex / Grok Build as the engine)+# BYOA — Bring Your Own Agent (local Claude Code / Codex / Grok Build / Cursor Agent 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@@ -7,7 +7,7 @@ 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**, or **Grok Build** (`grok`) as the reasoning engine, on the+**Codex CLI**, **Grok Build** (`grok`), or **Cursor Agent** (`cursor-agent`) as the reasoning engine, on theuser's own subscription — the server never holds the user's provider credentials.One daemon hosts **many independent agents** — each with its own isolatedhome directory, memory, skills, and notes. In Cumora these still appear@@ -38,7 +38,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). Agents you place here are BYOA agents.+ Codex / Grok Build / Cursor Agent). Agents you place here are BYOA agents.```Computers@@ -111,14 +111,14 @@ 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 --listen stdio:// (JSON-RPC) │+ │ codex app-server / grok ACP / cursor-agent one-shot ││ bash → cumora shim → POST /runtime/cli (per-agent JWT)│└─────────────────────────────────────────────────────────┘```**One computer, many agents.** Each agent gets one wake-stream-subscription, one persistent engine session, and one isolated on-disk-home. Agents never share state — isolation is "different directory ++subscription, one engine context (persistent process where supported, resumable+session id otherwise), and one isolated on-disk home. Agents never share state — isolation is "different directory +different token".---@@ -144,16 +144,16 @@ different token".4. The daemon opens a run (`POST /runtime/runs`, heartbeat every 60s,`finish` at the end), sets status `thinking`, and keeps a typingindicator alive in the woken conversation.-5. **The turn.** The engine's persistent session receives a compact+5. **The turn.** The engine receives a compactdelta: "triage already said this is real — act", the current UTCclock, the triage note, a pre-fetched unread digest (with a "glancebefore posting" nudge), a `memory/MEMORY.md` digest, and the teamroster. The invariant scaffold (CLI usage, the shared`GLANCE_YIELD_RULES`, memory rules, privacy boundary) is delivered- once per session out-of-band — `--append-system-prompt-file` for- Claude, `developerInstructions` for Codex, `_meta.rules` for Grok ACP —- so per-turn tokens stay- small and the engine's **native auto-compaction** keeps up.+ 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.6. The engine reads its home (`CLAUDE.md` / `AGENTS.md`, skills,`memory/`), reasons, and acts through bash: every `cumora …` callflows through the shim to `/runtime/cli` with identity pinned by the@@ -162,8 +162,8 @@ different token".mid-turn is injected into the live session at the next safe streamboundary; plain group activity gets a content-free nudge (defaulton). See COORDINATION.md 3c. Grok Build's ACP `session/prompt` is- one-in-flight, so mid-turn inject is a no-op there and the ping- coalesces onto the next wake.+ 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 postedto `/runtime/llm-calls`, landing in the same universal `llm_calls`ledger as cloud turns. Engine failures surface as a@@ -180,12 +180,12 @@ 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`). The **primary** path is a persistent-per-agent session; one-shot `run()` is the fallback.+engine (`claude`, `codex`, `grok`, `cursor`). Persistent per-agent sessions+are preferred when the CLI exposes one; Cursor uses one-shot `run()` for every wake.```tsinterface EngineAdapter {- id: 'claude' | 'codex'+ id: 'claude' | 'codex' | 'grok' | 'cursor'seedHome(home, persona) // lay out CLAUDE.md/AGENTS.md, skills, dirsstartSession?(args): EngineSession | null // persistent session (primary)run(args): Promise<…> // one-shot fallback@@ -200,28 +200,27 @@ interface EngineSession {}```-| Concern | Claude Code | Codex CLI |-| --- | --- | --- |-| Persistent session | `claude -p --input-format stream-json --output-format stream-json --verbose [--resume <id>] [--model X]`; turns are stream-json messages on stdin | `codex app-server --listen stdio://`, driven over JSON-RPC (`thread/start` / `thread/resume`); requires a git repo in the home (the daemon inits a throwaway one) |-| Standing prompt | `--append-system-prompt-file <home>/.cumora-standing-prompt.md` | `developerInstructions` on `thread/start` |-| One-shot fallback | `claude -p … --output-format stream-json` | `codex exec … --skip-git-repo-check` |-| Fallback triggers | `CUMORA_CLAUDE_ARGS` set | `CUMORA_CODEX_ARGS` set, `CUMORA_CODEX_NO_APP_SERVER=1`, Windows, or git-init failure |-| Memory / persona file | `CLAUDE.md` | `AGENTS.md` |-| Triage (small brain) | `claude -p --model haiku --output-format json` | `codex exec --model gpt-5.4-mini` |+| 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` |Sessions carry a resume id (`~/.cumora/sessions/<agentId>.session`); afailed resume falls back to a fresh thread instead of wedging the agent.Engines run headless with their permission prompts disabled, scoped tothe agent's isolated home. On Windows the daemon resolves the real-`claude`/`codex` `.cmd` shims and routes large prompts via stdin.+`claude`/`codex`/`grok`/`cursor-agent` `.cmd` shims and routes large prompts via stdin.Model selection: the per-agent `participants.model` / `fast_model`-columns, else the deploy-level `CUMORA_DEFAULT_CLAUDE_MODEL` /-`CUMORA_DEFAULT_CODEX_MODEL` pins.+columns, else the matching deploy-level `CUMORA_DEFAULT_*_MODEL` pin.### Running against a custom providerThose pins are resolved server-side and name Anthropic / OpenAI models. If your-local `claude` or `codex` is pointed at a **custom provider** (CC Switch and+local engine CLI is pointed at a **custom provider** (CC Switch andfriends), it has never heard of `claude-opus-4-7`, so every turn fails with*"There's an issue with the selected model"* even though the CLI works fine inyour terminal.@@ -256,6 +255,7 @@ CUMORA_ENGINE_MODEL=local CUMORA_TRIAGE_MODEL=local-small cumora agent computerCLAUDE.md (or AGENTS.md) ← static persona header, written once.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.claude/settings.json ← permissions (allow Bash)bin/cumora ← the shim (see below); bin/.runtime-tokenmemory/MEMORY.md ← the agent's durable memory index@@ -285,8 +285,8 @@ credentials are keyed to that dir — so the daemon sets `cwd` to theagent's home and does **not** relocate config. Per-agent: project memory,skills, settings, notes, workspace. Shared across an owner's agents onone machine: the engine login and the user's global config (`~/.claude` /-`~/.codex` / `~/.grok`). Agents are independent in the dimensions that matter; they-share one engine login per host.+`~/.codex` / `~/.grok`, or Cursor's login store). Agents are independent in+all project state and share one engine login per host.---@@ -299,7 +299,7 @@ CREATE TABLE computers (owner_user_id TEXT, -- null for the managed Cumora Cloud rowname TEXT NOT NULL, -- "Cumora Cloud", "MacBook Pro", …kind TEXT NOT NULL, -- 'cloud' | 'local' | 'vps'- available_engines JSONB, -- ['claude','codex'] (daemon-detected)+ available_engines JSONB, -- ['claude','codex','grok','cursor'] (daemon-detected)status TEXT NOT NULL, -- 'online' | 'offline' | 'busy'last_seen_at TIMESTAMP,credential_hash TEXT, -- SHA256 of the device token@@ -312,7 +312,7 @@ CREATE TABLE computers (-- participants carry their host + engine + models-- computer_id TEXT (FK → computers.id)--- engine TEXT ('managed' | 'claude' | 'codex')+-- engine TEXT ('managed' | 'claude' | 'codex' | 'grok' | 'cursor')-- model TEXT (big-brain override)-- fast_model TEXT (small-brain override)```@@ -399,8 +399,8 @@ npx cumora@latest agent computer --pair <code> [--server <url>]## Boundaries-- **Cost / rate limits are the operator's** (their Claude Code / Codex / Grok Build- subscription) — a stated BYOA benefit. The daemon's semaphores, spawn+- **Cost / rate limits are the operator's** (their Claude Code / Codex / Grok Build /+ Cursor subscription) — 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/docs/COORDINATION.md b/docs/COORDINATION.mdindex 80f8f6e..8c1087e 100644--- a/docs/COORDINATION.md+++ b/docs/COORDINATION.md@@ -28,8 +28,8 @@ the bottom of this doc for the narrative.## The shape of the problem-Multi-agent collaboration in Cumora is **N independent claude/codex-engine sessions on one operator's machine**, each woken by a server SSE event,+Multi-agent collaboration in Cumora is **N independent local-engine+sessions on one operator's machine**, each woken by a server SSE event,each reading the same conversation, each deciding independently what to do.Two failure modes:@@ -669,7 +669,9 @@ one and re-test. Don't pile on.| Var | Default | Notes ||---|---|---|| `CUMORA_DEFAULT_CLAUDE_MODEL` | unset | Deploy-level model pin (e.g. `claude-opus-4-7`). Per-agent `participants.model` overrides this. |-| `CUMORA_DEFAULT_CODEX_MODEL` | unset | Same shape for codex; deliberately not set by default. |+| `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_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). |@@ -773,4 +775,4 @@ fallback) and absent-member coverage (team-adapts principle).| `server/src/agents/agenda.ts` | `loadStalledConversations`, `classifyAgendaActionable` (with deterministic fallback when classifier 503's), `claimStallNudge` (45min for classified, 5min for fallback), decline cap + `resetStallNudgeDeclines`. || `server/src/agents/runtime/server.ts` | `/runtime/inbox` endpoint with `?probe=1` flag for non-advancing reads. `/thinking/mark` / `/thinking/unmark` bracket the turn (they also still stamp the vestigial compose-anchor — see 5a). `/agenda` routes the nudge `source` flag (classified vs fallback) into `claimStallNudge`. || `server/src/agents/runtime/inproc-client.ts` | `loadInbox()` — must remain a PURE READ. No more recordSeen side-effect (that broke a6e69aa). `markThinking`/`peekThinking` for the ZSET-based "who's composing here" claim. |-| `server/src/agents/computer/registry.ts` | `listAgentsForComputer` with the `CUMORA_DEFAULT_CLAUDE_MODEL` fallback. |+| `server/src/agents/computer/registry.ts` | `listAgentsForComputer` with per-engine `CUMORA_DEFAULT_*_MODEL` fallbacks. |diff --git a/scripts/guard-big-brain.mjs b/scripts/guard-big-brain.mjsindex 695b920..70ffb2a 100644--- a/scripts/guard-big-brain.mjs+++ b/scripts/guard-big-brain.mjs@@ -37,7 +37,7 @@ const ALLOW = {// The BYOA big-brain engine spawn (adapter.run) lives ONLY in the daemon,// where it is gated by the local triage (handler='big').adapterRun: ['server/src/agents/computer/daemon.ts'],- // The engine adapter is the ONLY place that spawns the claude/codex binary+ // The engine adapter is the ONLY place that spawns a supported engine binary// (and it splits classify=small vs run=big internally).engineSpawn: ['server/src/agents/computer/engine.ts'],}@@ -79,9 +79,9 @@ export function lineViolations(rel, raw) {if (/\.run\s*\(\s*\{/.test(code) && /adapter\.run|this\.adapter\.run/.test(code) && !ALLOW.adapterRun.includes(rel)) {out.push('big-brain engine spawn (adapter.run) outside the gated daemon path')}- // R4 — the claude/codex binary spawned directly, outside the engine adapter.- if (/(?:spawn|execFile\w*|exec)\s*\(\s*['"`](claude|codex)['"`]/.test(code) && !ALLOW.engineSpawn.includes(rel)) {- out.push('claude/codex binary spawned outside the engine adapter (bypasses the classify=small / run=big split)')+ // 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)) {+ 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.tsindex 773ed99..b0ba539 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', 'bogus'],+ engines: ['claude', 'cursor', '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']))+ assert.equal(update.params[1], JSON.stringify(['claude', 'cursor']))assert.equal(calls.some((c) => /INSERT INTO computers/.test(c.sql)), false)})diff --git a/server/src/__tests__/agents-computer-engine-cursor.test.ts b/server/src/__tests__/agents-computer-engine-cursor.test.tsnew file mode 100644index 0000000..2c32083--- /dev/null+++ b/server/src/__tests__/agents-computer-engine-cursor.test.ts@@ -0,0 +1,229 @@+/**+ * Contract tests for the BYOA Cursor Agent adapter.+ *+ * Cursor is not installed in CI. Each test places a fake `cursor-agent` first+ * on PATH and drives the stream-json shapes observed from Cursor Agent+ * 2026.08.11-e8db854.+ */+import { existsSync } from 'node:fs'+import { chmod, mkdtemp, mkdir, 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 { detectEngines, getAdapter, type EngineHopReport } from '../agents/computer/engine.js'++const IS_WIN = process.platform === 'win32'+const tempDirs: string[] = []++afterEach(async () => {+ delete process.env.CUMORA_CURSOR_ARGS+ await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })))+})++const FAKE_CURSOR = `#!/usr/bin/env node+'use strict'+const fs = require('node:fs')+const argv = process.argv.slice(2)+const record = (o) => { if (process.env.FAKE_CURSOR_LOG) fs.appendFileSync(process.env.FAKE_CURSOR_LOG, JSON.stringify(o) + '\\n') }+const out = (o) => process.stdout.write(JSON.stringify(o) + '\\n')+const scenario = process.env.FAKE_CURSOR_SCENARIO || 'ok'+const resumeAt = argv.indexOf('--resume')+const modelAt = argv.indexOf('--model')+const sid = resumeAt >= 0 ? argv[resumeAt + 1] : 'cursor-session-new'+const model = modelAt >= 0 ? argv[modelAt + 1] : 'Auto'+const prompt = argv[argv.length - 1]+record({ argv, cwd: process.cwd() })+out({ type: 'system', subtype: 'init', apiKeySource: 'login', cwd: process.cwd(), session_id: sid, model, permissionMode: 'default' })+out({ type: 'user', message: { role: 'user', content: [{ type: 'text', text: prompt }] }, session_id: sid })+if (scenario === 'turn-error') {+ out({ type: 'result', subtype: 'error', is_error: true, result: 'model unavailable', session_id: sid,+ usage: { inputTokens: 100, outputTokens: 2, cacheReadTokens: 40, cacheWriteTokens: 0 } })+ process.exit(0)+}+const result = { type: 'result', subtype: 'success', is_error: false, result: 'echo:' + prompt, session_id: sid,+ usage: { inputTokens: 100, outputTokens: 12, cacheReadTokens: 40, cacheWriteTokens: 3 } }+if (scenario === 'split-unicode') {+ const line = Buffer.from(JSON.stringify({ type: 'assistant', message: { role: 'assistant', content: [{ type: 'text', text: 'echo:🧪' + prompt }] }, session_id: sid }) + '\\n')+ const marker = line.indexOf(Buffer.from('🧪'))+ process.stdout.write(line.subarray(0, marker + 1))+ setTimeout(() => { process.stdout.write(line.subarray(marker + 1)); out(result) }, 10)+} else {+ out({ type: 'assistant', message: { role: 'assistant', content: [{ type: 'text', text: 'echo:' + prompt }] }, session_id: sid })+ out(result)+}+`++interface Fixture {+ root: string+ binDir: string+ home: string+ log: string+ env: NodeJS.ProcessEnv+}++async function fixture(scenario = 'ok'): Promise<Fixture> {+ const root = await mkdtemp(join(tmpdir(), 'cumora-engine-cursor-'))+ tempDirs.push(root)+ const binDir = join(root, 'bin')+ const home = join(root, 'home')+ await mkdir(binDir)+ await mkdir(home)+ const fake = join(binDir, 'cursor-agent')+ await writeFile(fake, FAKE_CURSOR, 'utf8')+ await chmod(fake, 0o755)+ const log = join(root, 'cursor.log')+ return {+ root,+ binDir,+ home,+ log,+ env: {+ ...process.env,+ PATH: `${binDir}:${process.env.PATH ?? ''}`,+ FAKE_CURSOR_LOG: log,+ FAKE_CURSOR_SCENARIO: scenario,+ },+ }+}++async function fakeLog(f: Fixture): Promise<Array<{ argv: string[]; cwd: string }>> {+ if (!existsSync(f.log)) return []+ return (await readFile(f.log, 'utf8')).split('\n').filter(Boolean).map((line) => JSON.parse(line))+}++test('cursor seedHome writes AGENTS.md and common home directories', { skip: IS_WIN }, async () => {+ const f = await fixture()+ const cursor = getAdapter('cursor')+ await cursor.seedHome(f.home, { id: 'cursor', name: 'Cursor', role: 'Implementer', systemPrompt: 'Implement only.' })+ const agents = await readFile(join(f.home, 'AGENTS.md'), 'utf8')+ assert.match(agents, /^# Cursor — Implementer/)+ assert.match(agents, /Implement only\./)+ assert.match(agents, /`AGENTS\.md` \(this file\)/)+ assert.match(agents, /`\.cursor\/skills\/` — your skills/)+ assert.doesNotMatch(agents, /CLAUDE\.md|\.claude\/skills/)+ assert.ok(existsSync(join(f.home, 'memory', 'MEMORY.md')))+ assert.ok(existsSync(join(f.home, 'workspace')))+ assert.ok(existsSync(join(f.home, '.cursor', 'skills')))+})++test('cursor run parses a fresh stream, normalizes usage, and reports one hop', { skip: IS_WIN }, async () => {+ const f = await fixture()+ const hops: EngineHopReport[] = []+ const result = await getAdapter('cursor').run({+ home: f.home,+ prompt: 'build it',+ env: f.env,+ model: 'cursor-test-model',+ 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, 'cursor-session-new')+ assert.equal(result.model, 'cursor-test-model')+ assert.deepEqual(result.usage, {+ input_tokens: 100,+ output_tokens: 12,+ cache_read_input_tokens: 40,+ cache_creation_input_tokens: 3,+ })+ assert.equal(hops.length, 1)+ assert.equal(hops[0].model, 'cursor-test-model')+ assert.equal(hops[0].textChars, 'echo:build it'.length)+ assert.deepEqual(hops[0].usage, result.usage)++ const argv = (await fakeLog(f))[0]?.argv ?? []+ for (const flag of ['-p', '--output-format', 'stream-json', '--force', '--trust']) {+ assert.ok(argv.includes(flag), `turn carries ${flag}: ${argv.join(' ')}`)+ }+ assert.equal(argv[argv.indexOf('--model') + 1], 'cursor-test-model')+ assert.equal(argv[argv.length - 1], 'build it')+})++test('cursor run resumes the supplied session id in a new process', { skip: IS_WIN }, async () => {+ const f = await fixture()+ const result = await getAdapter('cursor').run({+ home: f.home,+ prompt: 'continue',+ env: f.env,+ model: null,+ fastModel: null,+ resumeSessionId: 'cursor-existing-session',+ onLog: () => {},+ signal: new AbortController().signal,+ })+ assert.equal(result.exitCode, 0, result.error)+ assert.equal(result.sessionId, 'cursor-existing-session')+ const argv = (await fakeLog(f))[0]?.argv ?? []+ assert.equal(argv[argv.indexOf('--resume') + 1], 'cursor-existing-session')+ assert.equal(getAdapter('cursor').startSession?.({ home: f.home, env: f.env, onLog: () => {} }) ?? null, null)+})++test('cursor classify is read-only, parses result text and usage, and honors the model', { skip: IS_WIN }, async () => {+ const f = await fixture()+ const result = await getAdapter('cursor').classify({+ cwd: f.home,+ prompt: 'classify this',+ env: f.env,+ model: 'cursor-small',+ signal: new AbortController().signal,+ })+ assert.equal(result.error, undefined)+ assert.equal(result.text, 'echo:classify this')+ assert.equal(result.model, 'cursor-small')+ assert.deepEqual(result.usage, {+ input_tokens: 100,+ output_tokens: 12,+ cache_read_input_tokens: 40,+ cache_creation_input_tokens: 3,+ })+ const argv = (await fakeLog(f))[0]?.argv ?? []+ assert.equal(argv[argv.indexOf('--mode') + 1], 'ask')+ assert.ok(argv.includes('--trust'))+ assert.equal(argv.includes('--force'), false, 'triage must remain read-only')+})++test('cursor parser preserves JSON and Unicode split across stdout chunks', { skip: IS_WIN }, async () => {+ const f = await fixture('split-unicode')+ const result = await getAdapter('cursor').classify({+ cwd: f.home,+ prompt: 'split',+ env: f.env,+ signal: new AbortController().signal,+ })+ assert.equal(result.error, undefined)+ assert.equal(result.text, 'echo:🧪split')+})++test('cursor stream-reported error fails even when the process exits zero', { skip: IS_WIN }, async () => {+ const f = await fixture('turn-error')+ const result = await getAdapter('cursor').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, 'cursor-session-new')+})++test('cursor detection and wake probe expose the one-shot engine contract', { skip: IS_WIN }, async () => {+ const f = await fixture()+ const oldPath = process.env.PATH+ process.env.PATH = f.env.PATH+ try {+ assert.ok((await detectEngines()).includes('cursor'))+ } finally {+ process.env.PATH = oldPath+ }+ const wake = await getAdapter('cursor').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.tsindex cada3a9..9112a9e 100644--- a/server/src/__tests__/guard-big-brain.test.ts+++ b/server/src/__tests__/guard-big-brain.test.ts@@ -48,10 +48,11 @@ test('R3 — adapter.run() outside the daemon is caught; inside it is allowed',assert.deepEqual(lineViolations('server/src/agents/computer/daemon.ts', `await this.adapter.run({ model, input })`), [])})-test('R4 — spawning the claude/codex binary outside the engine adapter is caught', () => {- assert.ok(lineViolations('server/src/agents/tools.ts', `spawn('claude', args)`).length > 0)- assert.ok(lineViolations('server/src/agents/tools.ts', `execFile('codex', args)`).length > 0)- assert.deepEqual(lineViolations('server/src/agents/computer/engine.ts', `spawn('claude', args)`), [])+test('R4 — spawning a supported engine binary outside the engine adapter is caught', () => {+ for (const bin of ['claude', 'codex', 'grok', 'cursor-agent']) {+ 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)`), [])})test('commented-out examples do not trip the guard', () => {diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.tsindex 7bb8ee4..7d4876f 100644--- a/server/src/agents/computer/daemon.ts+++ b/server/src/agents/computer/daemon.ts@@ -2,8 +2,8 @@* `cumora agent computer` — the BYOA daemon.** 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)- * as each agent's brain. See docs/BYOA.md.+ * 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.** It talks to the Cumora server only over HTTP — no DB/Redis — so it can run* anywhere:@@ -107,7 +107,7 @@ const AGENDA_QUIET_MS = 90_000const AGENDA_CHECK_MS = 60_000const MAX_VISIBLE_ERROR_CHARS = 900// Big-brain spawn jitter. When an SSE wake fans out to N agents on this-// computer at the same instant (e.g. a human @all in a group), N claude/codex+// computer at the same instant (e.g. a human @all in a group), N local-engine// subprocesses would spawn in the same millisecond and slam Anthropic/OpenAI// in lockstep — observed today as four byoa_engine_failed notices in a row// with "Server is temporarily limiting requests · Rate limited" right after@@ -635,6 +635,9 @@ function authFailureHint(engine: EngineId, detail: string): string {if (engine === 'grok') {return 'Open Grok Build on that computer and run `grok login`, or set XAI_API_KEY, then wake the agent again.'}+ 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.'+ }return 'Open Codex on that computer and refresh its login or quota, then wake the agent again.'}@@ -646,6 +649,7 @@ function missingEngineMessage(): string {' - Claude Code: install the `claude` CLI, then run `claude` once to sign in',' - Codex: install the `codex` CLI, then run `codex` once to sign in',' - 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`','','After that, rerun:',' npx cumora@latest agent computer --pair <code>',@@ -657,7 +661,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, or Grok Build). Pair once, then it runs in the background.',+ 'engine (Claude Code, Codex, Grok Build, or Cursor Agent). Pair once, then it runs in the background.','','Usage:',' npx cumora@latest agent computer --pair <code> [--server <url>] [--engine <id>]',@@ -845,12 +849,10 @@ async function doPair(code: string, serverUrl: string, preferredEngine?: string)* - Auto-flush on every WINDOW_MS tick AND when buffer hits FLUSH_AT.* - flush() can be awaited at "natural pauses" (turn end) to push the tail* promptly without waiting for the timer. */-type ByoaSource = 'byoa-claude' | 'byoa-codex' | 'byoa-grok'+type ByoaSource = `byoa-${EngineId}`function byoaSourceOf(id: EngineId): ByoaSource {- if (id === 'claude') return 'byoa-claude'- if (id === 'codex') return 'byoa-codex'- return 'byoa-grok'+ return `byoa-${id}`}interface PendingHop {@@ -1257,8 +1259,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 (codex / a custom- * CLAUDE_ARGS override) — the caller then falls back to one-shot run(). If the+ * 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* prior process has died it respawns, resuming this.sessionId so context* carries across the restart. */private ensureEngineSession(): EngineSession | null {@@ -1378,15 +1380,14 @@ class AgentRunner {await spawnPacer.gate()const controller = new AbortController()const timer = setTimeout(() => controller.abort(), TRIAGE_TIMEOUT_MS)- let res: { text: string; error?: string; usage?: EngineUsage }+ let res: { text: string; error?: string; usage?: EngineUsage; model?: string | null }try {await mkdir(TRIAGE_DIR, { recursive: true })res = await this.adapter.classify({cwd: TRIAGE_DIR,prompt: `${payload.instructions}\n\n${payload.input}`,env: this.engineEnv(),- // Engine picks its own cheap default (claude→haiku, codex→gpt-5.4-mini);- // CUMORA_TRIAGE_MODEL overrides for either.+ // Engine picks its own cheap default; CUMORA_TRIAGE_MODEL overrides it.model: process.env.CUMORA_TRIAGE_MODEL,signal: controller.signal,})@@ -1447,8 +1448,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 (json output), absent for codex.- void this.recordTriageUsage(token, verdict.actionable, verdict.reason, res.usage)+ // to weigh. usage is present for Claude and Cursor; absent for Codex/Grok.+ void this.recordTriageUsage(token, verdict.actionable, verdict.reason, res.usage, res.model)return verdict}if (payload.failClosed) {@@ -1469,19 +1470,22 @@ class AgentRunner {}}- /** Triage model id for pricing (the local cerebellum: claude→haiku,- * grok→grok-4.5, codex→gpt-5.4-mini), honoring a CUMORA_TRIAGE_MODEL override. */+ /** 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. */private triageModel(): string {- return process.env.CUMORA_TRIAGE_MODEL- || (this.adapter.id === 'claude' ? 'haiku' : this.adapter.id === 'grok' ? 'grok-4.5' : 'gpt-5.4-mini')+ 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'+ return this.agent.model ?? '<cursor-default>'}- /** Post one local-triage record to the cost ledger. Best-effort. `usage` is the- * engine's raw breakdown (claude); undefined → recorded as unmeasured (codex). */- private async recordTriageUsage(token: string, actionable: boolean, reason: string, usage?: EngineUsage): Promise<void> {+ /** Post one local-triage record to the cost ledger. Best-effort. */+ private async recordTriageUsage(token: string, actionable: boolean, reason: string, usage?: EngineUsage, model?: string | null): Promise<void> {await runtimeBest(this.cfg.serverUrl, '/triage', token, {source: `byoa-${this.adapter.id}`,- model: this.triageModel(),+ model: model || this.triageModel(),actionable,reason,usage: usage ? usageFromClaude(usage) : null,@@ -2140,7 +2144,7 @@ class AgentRunner {// (with --resume this.sessionId to carry context across the restart).if (!session.alive) this.engineSession = null} else {- // One-shot path: codex, or a user CLAUDE_ARGS override — spawn per turn.+ // One-shot path: Cursor, 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.tsindex 93db83e..0ed6b69 100644--- a/server/src/agents/computer/engine.ts+++ b/server/src/agents/computer/engine.ts@@ -2,7 +2,7 @@* 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, or Grok Build. The daemon (daemon.ts) hands+ * on the user's machine: Claude Code, Codex, Grok Build, or Cursor Agent. 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@@ -14,7 +14,8 @@* NOTE on engine flags: the exact non-interactive / permission flags differ* across engine versions. We pick sensible defaults for an isolated,* user-owned runner and let the user override via env- * (CUMORA_CLAUDE_ARGS / CUMORA_CODEX_ARGS / CUMORA_GROK_ARGS, space-split). Correctness of the+ * (CUMORA_CLAUDE_ARGS / CUMORA_CODEX_ARGS / CUMORA_GROK_ARGS /+ * CUMORA_CURSOR_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.*/@@ -44,7 +45,7 @@ const CODEX_LOG_RAW = process.env.CUMORA_CODEX_VERBOSE === '1'/** How to spawn a CLI bin cross-platform.* - POSIX: spawn the bare bin with shell:false — unchanged, zero-risk.- * - Windows: `claude`/`codex` are usually `.cmd` shims that Node CANNOT run with+ * - Windows: engine CLIs are usually `.cmd` shims that Node CANNOT run with* shell:false (CreateProcess can't execute a batch file) → "process exited with* code 1". Resolve the real file on PATH and run a `.cmd`/`.bat` via* shell:true. When the shell is needed,@@ -54,7 +55,7 @@ const CODEX_LOG_RAW = process.env.CUMORA_CODEX_VERBOSE === '1'* Windows + nvm-windows gotcha: global npm CLIs are shipped as an extensionless* POSIX shell-shim (`#!/bin/sh` wrapper) ALONGSIDE the real `.cmd`. The old loop* iterated `['', ...PATHEXT]`, hit the shim first, classified it as non-batch,- * and returned `shell:false` → every Claude/Codex turn died with ENOENT.+ * and returned `shell:false` → every engine turn died with ENOENT.* Fix: prefer a real `.exe`/`.cmd`/`.bat` hit; only fall back to the shim with* `shell:true` when nothing else is on PATH. */// Exported for tests; the nvm-windows extensionless-shim regression (issue #5)@@ -85,10 +86,10 @@ export function resolveSpawn(bin: string): { command: string; shell: boolean; wareturn { command: bin, shell: true, wantsStdinPrompt: true }}-export type EngineId = 'claude' | 'codex' | 'grok'+export type EngineId = 'claude' | 'codex' | 'grok' | 'cursor'/** The pairable engine ids, in the daemon's default detection order. */-export const ENGINE_IDS: EngineId[] = ['claude', 'codex', 'grok']+export const ENGINE_IDS: EngineId[] = ['claude', 'codex', 'grok', 'cursor']export interface EnginePersona {id: string@@ -174,6 +175,8 @@ export interface EngineClassifyResult {/** Token usage for this triage call (Claude json output). Undefined when the* engine emits none (e.g. codex / text-only output). */usage?: EngineUsage+ /** The model id the engine actually ran, when its output reports one. */+ model?: string | null}/** A `doctor` liveness probe for ONE brain tier of an engine: spawn it on the@@ -576,20 +579,25 @@ function extraArgs(envVar: string): string[] {return raw ? raw.split(/\s+/).filter(Boolean) : []}-const PERSONA_HEADER = (p: EnginePersona): string =>- `# ${p.name}${p.role ? ` — ${p.role}` : ''}\n\n` ++const PERSONA_HEADER = (+ p: EnginePersona,+ opts: { personaFile?: string; skillsDir?: string } = {},+): string => {+ const personaFile = opts.personaFile ?? 'CLAUDE.md'+ const skillsDir = opts.skillsDir ?? '.claude/skills/'+ return `# ${p.name}${p.role ? ` — ${p.role}` : ''}\n\n` +`You are **${p.name}**, a member of a team that collaborates in Cumora (a team chat).\n` +(p.systemPrompt?.trim() ? `\n## Your style\n${p.systemPrompt.trim()}\n\n` : '\n') +`This directory is your private home and your working directory — it persists\n` +`across wakes and is yours alone. Its layout:\n` +- `- \`CLAUDE.md\` (this file) — always loaded each wake; keep it short.\n` ++ `- \`${personaFile}\` (this file) — always loaded each wake; keep it short.\n` +`- \`memory/\` — your durable memory. There is NO hidden memory store: to remember\n` +` something across wakes you MUST write it to a file here (e.g. \`memory/<topic>.md\`)\n` +` and add a one-line pointer in \`memory/MEMORY.md\`. Saying "I'll remember" without\n` +` writing a file means you will NOT remember. At the start of each wake, read\n` +` \`memory/MEMORY.md\` (and the files it points to) to recall what you know.\n` +`- \`notes/\` — scratch notes and drafts.\n` +- `- \`.claude/skills/\` — your skills.\n` ++ `- \`${skillsDir}\` — your skills.\n` +`- \`workspace/\` — **put all project files and scratch here**: git clones, builds,\n` +` downloads, temp files. Always \`cd workspace\` (or use \`workspace/…\` paths) for\n` +` that work — do NOT clutter your home root with project files.\n\n` +@@ -616,6 +624,7 @@ const PERSONA_HEADER = (p: EnginePersona): string =>` about a person or role you don't already know.\n` +`- \`cumora whoami\` — your identity\n\n` +`Be a real teammate with your own voice — not a generic assistant.\n`+}/** A persistent Claude Code process for ONE agent (see EngineSession). Spawned in* stream-json I/O mode (`-p --input-format stream-json --output-format stream-json`):@@ -1900,10 +1909,364 @@ class GrokAdapter implements EngineAdapter {}}+// ─── cursor ───────────────────────────────────────────────────────────────+//+// Cursor Agent (the `cursor-agent` CLI bundled with Cursor, 2026.08.11-e8db854)+// is a ONE-SHOT engine: this version exposes no persistent stdio protocol, so+// there is no startSession — every wake spawns a fresh process and continuity+// comes from `--resume <session_id>`, which re-opens the SAME session id in the+// next one-shot process. The daemon's generic one-shot run() path IS the wake+// path; probeWake() therefore always reports `skipped` (probe() already+// exercises the exact spawn a wake uses).+//+// cursor-agent -p --output-format stream-json --force --trust \+// [--model X] [--resume <id>] <prompt>+//+// The stream: a `system/init` event (session id + model), user/assistant/+// thinking events, and a terminal `result` event carrying the turn's usage.+// Two contract quirks that shape this adapter:+// - A stream may report `is_error:true` with process exit 0 — that is a+// FAILED turn (model unavailable, …), so the stream decides, not the exit+// code, so the stream result is authoritative.+// - usage reports uncached input and cache reads as separate fields, matching+// Cursor's bundled `TokenUsage` schema; map them directly without folding.+// Triage/probe use the READ-ONLY `--mode ask` variant and never `--force`.++/** Cursor's result-event usage (OpenAI-ish camelCase). Its bundled TokenUsage+ * schema carries uncached input and cache reads as separate counters. */+interface CursorUsage { inputTokens?: number; outputTokens?: number; cacheReadTokens?: number; cacheWriteTokens?: number }++/** The subset of Cursor's stream-json we act on. Everything else is logged and+ * ignored, so a new event type in a future Cursor never breaks a turn. */+interface CursorEvent {+ type?: unknown+ subtype?: unknown+ session_id?: unknown+ model?: unknown+ is_error?: unknown+ result?: unknown+ usage?: CursorUsage+ message?: { role?: unknown; content?: unknown }+}++/** Normalize Cursor's disjoint usage counters into EngineUsage;+ * cacheWrite maps to cache_creation. */+function cursorUsageToEngineUsage(u: CursorUsage | undefined): EngineUsage | undefined {+ if (!u || typeof u !== 'object') return undefined+ const num = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) ? v : 0)+ return {+ input_tokens: num(u.inputTokens),+ output_tokens: num(u.outputTokens),+ cache_read_input_tokens: num(u.cacheReadTokens),+ cache_creation_input_tokens: num(u.cacheWriteTokens),+ }+}++/** Concatenate the text items of a Cursor message content array (same+ * `{type:'text', text}` item shape Claude uses). */+function cursorTextOf(content: unknown): string {+ if (!Array.isArray(content)) return ''+ let out = ''+ for (const item of content) {+ if (!item || typeof item !== 'object') continue+ const it = item as { type?: unknown; text?: unknown }+ if (it.type === 'text' && typeof it.text === 'string') out += it.text+ }+ return out+}++/** Folds Cursor's stream-json into what the daemon wants from a turn: the+ * session id (every event repeats it — resume keeps continuity across the+ * per-wake processes), the model from `system/init` (or the pin when the+ * stream never names one), the normalized turn usage, the concatenated+ * assistant text (triage reads it), and the result event's error. ONE+ * turn-level EngineHopReport fires at the `result` event — Cursor reports+ * usage once per turn, so emitting per assistant message would double-count. */+class CursorTurnTracker {+ sessionId: string | null = null+ model: string | null+ usage: EngineUsage | undefined+ text = ''+ error: string | null = null+ sawResult = false+ private startedAt: number | null = null++ constructor(+ pin: string | null,+ private readonly onHopUsage?: (r: EngineHopReport) => void,+ ) {+ this.model = pin+ }++ /** Feed one event. Returns true when the event terminates the turn. */+ observe(ev: CursorEvent): boolean {+ if (typeof ev.session_id === 'string' && ev.session_id) this.sessionId = ev.session_id+ if (ev.type === 'system' && ev.subtype === 'init') {+ // init's model is what Cursor actually opened the session on — it wins+ // over the pin (which is only what we asked for).+ if (typeof ev.model === 'string' && ev.model) this.model = ev.model+ if (this.startedAt == null) this.startedAt = Date.now()+ return false+ }+ if (ev.type === 'assistant') {+ this.text += cursorTextOf(ev.message?.content)+ return false+ }+ if (ev.type === 'result') {+ this.sawResult = true+ this.usage = cursorUsageToEngineUsage(ev.usage)+ if (ev.is_error === true) {+ this.error = typeof ev.result === 'string' && ev.result+ ? ev.result+ : `cursor turn error${typeof ev.subtype === 'string' ? ` (${ev.subtype})` : ''}`+ }+ // The single turn-level hop — Cursor has no per-message usage, so this+ // is the honest granularity (same contract as Codex's turn-completed).+ if (ev.is_error !== true && this.usage && this.model && this.onHopUsage) {+ const startedAt = this.startedAt+ try {+ this.onHopUsage({+ model: this.model,+ usage: this.usage,+ latencyMs: startedAt != null ? Date.now() - startedAt : undefined,+ hopIndex: 1,+ textChars: this.text.length,+ })+ } catch { /* ledger best-effort — never break the stream */ }+ }+ return true+ }+ return false+ }+}++/** Parse one stdout line of Cursor's stream-json. Non-JSON lines (banners,+ * warnings that land on stdout) come back null and are logged verbatim. */+function parseCursorLine(line: string): CursorEvent | null {+ if (!line.startsWith('{')) return null+ try { return JSON.parse(line) as CursorEvent } catch { return null }+}++/** One-shot `cursor-agent -p --output-format stream-json …`: spawn, fold the+ * stream through a CursorTurnTracker, resolve on exit. The tracker's error is+ * folded into the result because a Cursor stream reports failure via+ * `is_error:true` regardless of the process exit code. Text is the+ * concatenated assistant text — what classify()/probe() want. */+function spawnCursorStream(+ command: string,+ args: string[],+ opts: {+ cwd: string+ env: NodeJS.ProcessEnv+ signal: AbortSignal+ onLog?: (line: string) => void+ shell: boolean+ stdinText?: string+ onHopUsage?: (r: EngineHopReport) => void+ /** Model pin, used as the tracker's model until system/init names one. */+ pin?: string | null+ /** Fail a clean-exiting stream that never emitted its terminal `result`+ * event (run(): a turn that never finished is not a success). classify()+ * and probe() settle for whatever text arrived. */+ requireResult?: boolean+ },+): Promise<EngineRunResult & { text: string }> {+ return new Promise((resolve) => {+ const tracker = new CursorTurnTracker(opts.pin ?? null, opts.onHopUsage)+ const child = spawn(command, args, {+ cwd: opts.cwd, env: opts.env,+ stdio: [opts.stdinText != null ? 'pipe' : 'ignore', 'pipe', 'pipe'],+ shell: opts.shell,+ })+ if (opts.stdinText != null) {+ try { child.stdin?.write(opts.stdinText); child.stdin?.end() } catch { /* the 'error' handler resolves */ }+ }+ const onAbort = (): void => { child.kill('SIGTERM') }+ opts.signal.addEventListener('abort', onAbort, { once: true })+ if (opts.signal.aborted) onAbort()+ const stderrTail: string[] = []+ const stdoutTail: string[] = []+ const decoder: Record<'stdout' | 'stderr', StringDecoder> = {+ stdout: new StringDecoder('utf8'),+ stderr: new StringDecoder('utf8'),+ }+ const carry: Record<'stdout' | 'stderr', string> = { stdout: '', stderr: '' }+ const takeLine = (stream: 'stdout' | 'stderr', raw: string): void => {+ const line = cleanLine(raw)+ if (!line) return+ pushTail(stream === 'stderr' ? stderrTail : stdoutTail, line)+ opts.onLog?.(line)+ if (stream === 'stdout') {+ const ev = parseCursorLine(line)+ if (ev) tracker.observe(ev)+ }+ }+ const pump = (stream: 'stdout' | 'stderr', buf: Buffer | null): void => {+ const text = buf === null ? decoder[stream].end() : decoder[stream].write(buf)+ const lines = (carry[stream] + text).split('\n')+ carry[stream] = buf === null ? '' : (lines.pop() ?? '')+ for (const line of lines) takeLine(stream, line)+ }+ child.stdout?.on('data', (buf: Buffer) => pump('stdout', buf))+ child.stderr?.on('data', (buf: Buffer) => pump('stderr', buf))+ let settled = false+ child.on('error', (err) => {+ if (settled) return+ settled = true+ opts.signal.removeEventListener('abort', onAbort)+ resolve({ exitCode: 1, error: err instanceof Error ? err.message : String(err), sessionId: null, text: '' })+ })+ child.on('close', (code, signalName) => {+ if (settled) return+ settled = true+ opts.signal.removeEventListener('abort', onAbort)+ pump('stdout', null)+ pump('stderr', null)+ const procExit = code ?? (signalName ? 128 : 1)+ // The stream is the truth: is_error:true fails the turn even on exit 0.+ const streamError = tracker.error+ ? `engine turn error: ${tracker.error.slice(0, MAX_FAILURE_CHARS)}`+ : (opts.requireResult && !tracker.sawResult+ ? 'engine stream ended without a result event (cursor-agent exited early)'+ : null)+ const exitCode = procExit !== 0 ? procExit : (streamError ? 1 : 0)+ const error = procExit !== 0+ ? failurePreview({ exitCode: procExit, signalName, stderr: stderrTail, stdout: stdoutTail })+ : streamError ?? undefined+ resolve({ exitCode, error, sessionId: tracker.sessionId, usage: tracker.usage, model: tracker.model, text: tracker.text })+ })+ })+}++class CursorAdapter implements EngineAdapter {+ readonly id = 'cursor' as const+ readonly bin = 'cursor-agent'++ /** A turn: full-tools one-shot (`--force` auto-approves the agent's tool use+ * inside its isolated, user-owned home — the Cursor analogue of Claude's+ * --dangerously-skip-permissions), `--trust` skips the workspace-trust+ * prompt a headless spawn can't answer. The prompt is the LAST argv element+ * (Cursor takes it positionally); on Windows it travels via stdin instead. */+ private turn(prompt: string, args: {+ cwd: string+ env: NodeJS.ProcessEnv+ signal: AbortSignal+ onLog?: (line: string) => void+ model?: string | null+ resumeSessionId?: string | null+ onHopUsage?: (r: EngineHopReport) => void+ }): Promise<EngineRunResult & { text: string }> {+ const { command, shell, wantsStdinPrompt } = resolveSpawn(this.bin)+ const model = args.model ? ['--model', args.model] : []+ // Continuous context across wakes: --resume re-opens the prior session in+ // this fresh one-shot process (Cursor has no persistent protocol to keep+ // warm instead).+ const resume = args.resumeSessionId ? ['--resume', args.resumeSessionId] : []+ const base = ['-p', ...resume, ...model, '--output-format', 'stream-json', '--force', '--trust']+ return spawnCursorStream(command, wantsStdinPrompt ? base : [...base, prompt], {+ cwd: args.cwd, env: args.env, signal: args.signal, onLog: args.onLog, shell,+ stdinText: wantsStdinPrompt ? prompt : undefined,+ onHopUsage: args.onHopUsage,+ pin: args.model ?? null,+ requireResult: true,+ })+ }++ /** The READ-ONE triage/probe shape: `--mode ask` keeps the agent Q&A-only+ * (no edits, no shell), so classification can never mutate anything. Never+ * `--force` here. */+ 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, wantsStdinPrompt } = resolveSpawn(this.bin)+ const model = args.model ? ['--model', args.model] : []+ const base = ['--mode', 'ask', '-p', '--output-format', 'stream-json', ...model, '--trust']+ return spawnCursorStream(command, wantsStdinPrompt ? base : [...base, prompt], {+ cwd: args.cwd, env: args.env, signal: args.signal, onLog: args.onLog, shell,+ stdinText: wantsStdinPrompt ? prompt : undefined,+ pin: args.model ?? null,+ })+ }++ async classify(args: EngineClassifyArgs): Promise<EngineClassifyResult> {+ const flags = extraArgs('CUMORA_TRIAGE_ARGS')+ if (flags.length) {+ // User-owned triage flag set → plain print mode, raw text back (the same+ // override discipline the other engines share; no stream to fold).+ const { command, shell, wantsStdinPrompt } = resolveSpawn(this.bin)+ const base = [...flags, '-p']+ return spawnCapture(command, wantsStdinPrompt ? base : [...base, args.prompt], {+ cwd: args.cwd, env: args.env, signal: args.signal, onLog: args.onLog, shell,+ stdinText: wantsStdinPrompt ? args.prompt : undefined,+ })+ }+ // Cursor has no fixed cheap cerebellum id (its models are account-gated+ // aliases); unset CUMORA_TRIAGE_MODEL → Cursor's default ('Auto'), honestly+ // reported back by the stream's system/init for the ledger.+ const r = await this.ask(args.prompt, { cwd: args.cwd, env: args.env, signal: args.signal, onLog: args.onLog, model: args.model })+ return { text: r.text, error: r.error, usage: r.usage, model: r.model }+ }++ async probe(args: EngineProbeArgs): Promise<EngineClassifyResult> {+ // 'small' → whatever triage runs on (CUMORA_TRIAGE_MODEL, else Cursor's+ // default — the same model as 'big', honestly reported as such); 'big' →+ // Cursor's default. Read-only ask mode either way.+ const model = args.tier === 'small' ? (process.env.CUMORA_TRIAGE_MODEL || null) : null+ const r = await this.ask(DOCTOR_PROMPT, { cwd: args.cwd, env: args.env, signal: args.signal, model })+ return { text: r.text, error: r.error, usage: r.usage, model: r.model }+ }++ probeWake(_args: EngineWakeProbeArgs): Promise<EngineWakeProbeResult> {+ // There is no distinct wake path to probe: no persistent protocol in this+ // cursor-agent version, so the wake is the SAME one-shot spawn probe()+ // already exercises. Mark skipped so doctor hides the redundant line.+ return Promise.resolve({ ok: true, detail: '', skipped: true })+ }++ async seedHome(home: string, persona: EnginePersona): Promise<void> {+ await ensureCommonHome(home)+ await mkdir(join(home, '.cursor', 'skills'), { recursive: true })+ // Always rewrite AGENTS.md so persona edits land without requiring a fresh+ // home (matches Claude and Codex). Cursor discovers AGENTS.md from its cwd.+ await writeFile(+ join(home, 'AGENTS.md'),+ PERSONA_HEADER(persona, { personaFile: 'AGENTS.md', skillsDir: '.cursor/skills/' }),+ 'utf8',+ )+ }++ async run(args: EngineRunArgs): Promise<EngineRunResult> {+ const flags = extraArgs('CUMORA_CURSOR_ARGS')+ if (flags.length) {+ // Whole user-owned flag override → opaque print mode (same escape hatch+ // as CUMORA_CLAUDE_ARGS / CUMORA_CODEX_ARGS / CUMORA_GROK_ARGS): we can't+ // assume the stream-json shape, so no usage/hop ledger — but keep+ // --resume + -p + prompt so session continuity survives the override.+ const resume = args.resumeSessionId ? ['--resume', args.resumeSessionId] : []+ const { command, shell, wantsStdinPrompt } = resolveSpawn(this.bin)+ const base = [...flags, ...resume, '-p']+ return spawnEngine(command, wantsStdinPrompt ? base : [...base, args.prompt], args, { shell, stdinText: wantsStdinPrompt ? args.prompt : undefined })+ }+ 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: Cursor exposes no persistent stdio protocol in this+ // version — the daemon runs the one-shot path above per wake and resumes+ // the session id it reports (see the section note).+}+const ADAPTERS: Record<EngineId, EngineAdapter> = {claude: new ClaudeAdapter(),codex: new CodexAdapter(),grok: new GrokAdapter(),+ cursor: new CursorAdapter(),}export function getAdapter(id: EngineId): EngineAdapter {diff --git a/server/src/agents/computer/registry.ts b/server/src/agents/computer/registry.tsindex baa451e..9522cee 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).+ * engine (Claude Code / Codex / Grok Build / Cursor Agent).** 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'+export type EngineId = 'managed' | 'claude' | 'codex' | 'grok' | 'cursor'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'])+const PAIRABLE_ENGINES: ReadonlySet<string> = new Set(['claude', 'codex', 'grok', 'cursor'])export interface ComputerRow {id: string@@ -349,9 +349,10 @@ export async function mintAgentRuntimeToken(args: {* overrides so the daemon can pass them to the engine.** When a row has no explicit model, fall back to the deploy-level default- * (CUMORA_DEFAULT_CLAUDE_MODEL / CUMORA_DEFAULT_CODEX_MODEL) so every BYOA+ * (CUMORA_DEFAULT_CLAUDE_MODEL / CUMORA_DEFAULT_CODEX_MODEL /+ * CUMORA_DEFAULT_GROK_MODEL / CUMORA_DEFAULT_CURSOR_MODEL) so every BYOA* daemon gets a consistent pin — independent of whatever model the local- * `claude` / `codex` CLI happens to default to today. Critical: a model+ * engine CLI happens to default to today. Critical: a model* upgrade in the underlying CLI (e.g. claude 4.7 → 4.8) silently changes* agent behavior on every user's machine unless we pin here. */export async function listAgentsForComputer(computerId: string): Promise<@@ -366,9 +367,10 @@ export async function listAgentsForComputer(computerId: string): Promise<const claudeDefault = process.env.CUMORA_DEFAULT_CLAUDE_MODEL?.trim() || nullconst codexDefault = process.env.CUMORA_DEFAULT_CODEX_MODEL?.trim() || nullconst grokDefault = process.env.CUMORA_DEFAULT_GROK_MODEL?.trim() || null+ const cursorDefault = process.env.CUMORA_DEFAULT_CURSOR_MODEL?.trim() || nullreturn rows.map((r) => {if (r.model) return r- const dflt = r.engine === 'codex' ? codexDefault : r.engine === 'claude' ? claudeDefault : r.engine === 'grok' ? grokDefault : null+ const dflt = r.engine === 'codex' ? codexDefault : r.engine === 'claude' ? claudeDefault : r.engine === 'grok' ? grokDefault : r.engine === 'cursor' ? cursorDefault : nullreturn dflt ? { ...r, model: dflt } : r})}diff --git a/server/src/agents/llm-ledger.ts b/server/src/agents/llm-ledger.tsindex dfa9da7..af8fb9b 100644--- a/server/src/agents/llm-ledger.ts+++ b/server/src/agents/llm-ledger.ts@@ -29,7 +29,7 @@* different timing. The CI guard's allowlist documents these exceptions.** What this is NOT for:- * - BYOA-local LLM calls (the operator's paired claude / codex CLI). Those+ * - BYOA-local LLM calls (the operator's paired engine CLI). Those* are billed against the operator's own subscription, not Cumora's sub2api,* and are already accounted for in `agent_triages` (BYOA triage rows) +* `agent_runs` (BYOA turn rows) with `source='byoa-*'`. Putting them into@@ -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'+export type LlmCallSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor'/** 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 d39510a..2383fee 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'+export type TriageSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor'export type AgentEventLevel = 'debug' | 'info' | 'warn' | 'error'const MAX_STRING_CHARS = 24_000diff --git a/server/src/agents/runtime/server.ts b/server/src/agents/runtime/server.tsindex 713b0e8..535dfcf 100644--- a/server/src/agents/runtime/server.ts+++ b/server/src/agents/runtime/server.ts@@ -413,7 +413,7 @@ 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'). Fire-and-forget; a DB hiccup must never break the wake.+// 'byoa-codex' | 'byoa-grok' | 'byoa-cursor'). 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@@ -433,7 +433,7 @@ 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-claude'+ const source = (body?.source === 'byoa-claude' || body?.source === 'byoa-codex' || body?.source === 'byoa-grok' || body?.source === 'byoa-cursor') ? body.source : 'byoa-claude'const daemonVersion = typeof body?.daemonVersion === 'string' && body.daemonVersion.trim() ? body.daemonVersion.trim().slice(0, 32) : nullconst 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.tsindex 5972ea7..a629c11 100644--- a/server/src/api/router.ts+++ b/server/src/api/router.ts@@ -1098,7 +1098,7 @@ 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] : 'claude'+ const engine = (engines[0] === 'claude' || engines[0] === 'codex' || engines[0] === 'grok' || engines[0] === 'cursor') ? 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. Agentsdiff --git a/server/src/db/migrate.ts b/server/src/db/migrate.tsindex c50cf26..f307f2a 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+ source TEXT NOT NULL, -- cloud | byoa-claude | byoa-codex | byoa-grok | byoa-cursormodel 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 — almost always 'cloud' here; BYOA local triages still+-- byoa-codex|byoa-grok|byoa-cursor — 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 rowname 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']; ['managed'] for cloud+ available_engines JSONB NOT NULL DEFAULT '[]'::jsonb, -- ['claude','codex','grok','cursor']; ['managed'] for cloudstatus 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'+ALTER TABLE participants ADD COLUMN IF NOT EXISTS engine TEXT; -- 'managed' | 'claude' | 'codex' | 'grok' | 'cursor'-- 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/ObservabilityPage.tsx b/src/admin/ObservabilityPage.tsxindex dbb8ca6..524a9b0 100644--- a/src/admin/ObservabilityPage.tsx+++ b/src/admin/ObservabilityPage.tsx@@ -157,7 +157,7 @@ const REFRESH_INTERVALS: Array<{ label: string; ms: number }> = [// filter is here so the operator can isolate either side when investigating// a spike: "did cloud cost spike, or just BYOA token usage?"-// One BYOA pill covering BOTH engines (byoa-claude + byoa-codex). The rollup+// One BYOA pill covering every local engine. The rollup// table still shows them as separate rows (different engine/model); this is// just the filter — the operator rarely wants to isolate a single BYOA engine,// and "Cloud vs BYOA" is the split that matters.@@ -167,7 +167,7 @@ const SOURCE_FILTERS: Array<{ key: SourceFilter; label: string }> = [{ key: 'cloud', label: 'Cloud' },{ key: 'byoa', label: 'BYOA' },]-const isByoaSource = (s: string): boolean => s === 'byoa-claude' || s === 'byoa-codex' || s === 'byoa-grok'+const isByoaSource = (s: string): boolean => s.startsWith('byoa-')// ─── Component ───────────────────────────────────────────────────────────diff --git a/src/admin/api.ts b/src/admin/api.tsindex ffebf48..403d4ad 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'+export type LlmCallSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor'export interface LlmSummary {sinceDays: numberdiff --git a/src/api/client.ts b/src/api/client.tsindex 8076648..b6a3b6a 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'+export type ApiTriageSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor'export interface ApiTriageAgentRow {agentId: stringdiff --git a/src/components/AgentEditor.tsx b/src/components/AgentEditor.tsxindex 8b500ee..ed6484c 100644--- a/src/components/AgentEditor.tsx+++ b/src/components/AgentEditor.tsx@@ -239,7 +239,7 @@ export function AgentEditor({ agent, onClose }: Props) {<Fieldlabel={isByoa ? 'Big-brain model (大脑)' : 'Model'}hint={isByoa- ? `Main reasoning model passed to the engine as --model. ${engine === 'codex' ? 'A model name (e.g. gpt-5.5, o3).' : engine === 'grok' ? 'A Grok model (e.g. grok-4.6).' : "A Claude alias or full name (e.g. opus, sonnet, claude-sonnet-4-6)."} Blank = engine default.`+ ? `Main reasoning model passed to the engine as --model. ${engine === 'codex' ? 'A model name (e.g. gpt-5.5, o3).' : engine === 'grok' ? 'A Grok model (e.g. grok-4.6).' : engine === 'cursor' ? 'A Cursor model id or alias; blank = Auto.' : "A Claude alias or full name (e.g. opus, sonnet, claude-sonnet-4-6)."} Blank = engine default.`: '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).'}><Input@@ -259,7 +259,9 @@ export function AgentEditor({ agent, onClose }: Props) {? 'Cheaper model for light auxiliary tasks (e.g. gpt-5.4-mini). Blank = same as big-brain.': engine === 'grok'? 'Cheaper/faster Grok model for light auxiliary tasks (e.g. grok-4.5). Blank = engine default.'- : "Cheaper/faster model for light auxiliary tasks — maps to Claude's ANTHROPIC_SMALL_FAST_MODEL. Blank = engine default."}+ : engine === 'cursor'+ ? 'Not used by Cursor; triage follows CUMORA_TRIAGE_MODEL on the computer. Blank = Auto.'+ : "Cheaper/faster model for light auxiliary tasks — maps to Claude's ANTHROPIC_SMALL_FAST_MODEL. Blank = engine default."}><Inputtype="text"@@ -274,7 +276,7 @@ export function AgentEditor({ agent, onClose }: Props) {<Fieldlabel="Runs on"- hint="Which computer executes this agent. Cumora Cloud is managed; a computer you've paired runs it on your local Claude Code, Codex, or Grok Build."+ hint="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."><SelectariaLabel="Runs on"@@ -307,7 +309,7 @@ export function AgentEditor({ agent, onClose }: Props) {options={(selectedComputer.availableEngines.length? selectedComputer.availableEngines: (['claude'] as EngineId[])- ).map((en) => ({ value: en, label: en === 'claude' ? 'Claude Code' : en === 'codex' ? 'Codex' : en === 'grok' ? 'Grok Build' : en }))}+ ).map((en) => ({ value: en, label: en === 'claude' ? 'Claude Code' : en === 'codex' ? 'Codex' : en === 'grok' ? 'Grok Build' : en === 'cursor' ? 'Cursor' : en }))}/></div>)}diff --git a/src/desktop/MeView.tsx b/src/desktop/MeView.tsxindex b2171af..0eae033 100644--- a/src/desktop/MeView.tsx+++ b/src/desktop/MeView.tsx@@ -695,7 +695,7 @@ function SkypeSoundSection() {)}-const ENGINE_LABEL: Record<string, string> = { managed: 'Cumora', claude: 'Claude Code', codex: 'Codex', grok: 'Grok Build' }+const ENGINE_LABEL: Record<string, string> = { managed: 'Cumora', claude: 'Claude Code', codex: 'Codex', grok: 'Grok Build', cursor: 'Cursor' }const KIND_ICON: Record<string, string> = { cloud: '☁', local: '💻', vps: '🖥' }const STATUS_COLOR: Record<string, string> = { online: '#3BB273', busy: '#E6A23C', offline: 'var(--ink-300)' }@@ -710,7 +710,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'>('claude')+ const [engine, setEngine] = useState<'claude' | 'codex' | 'grok' | 'cursor'>('claude')// Default on: install the always-on service (auto-start/restart/update).// --install-service is macOS/Linux only (daemon throws on Windows) → off + hidden there.const [asService, setAsService] = useState(!isWindows)@@ -776,8 +776,10 @@ function ComputersTab() {<p className="text-[13px] text-ink-500 mb-4 max-w-[640px]">Every agent runs on a <strong>Computer</strong>. <em>Cumora Cloud</em> is built in andalways on. Pair your own machine or a VPS to run agents on your local- <span className="font-mono text-[12px]"> Claude Code</span> or- <span className="font-mono text-[12px]"> Codex</span> — each agent gets its own isolated+ <span className="font-mono text-[12px]"> Claude Code</span>,+ <span className="font-mono text-[12px]"> Codex</span>,+ <span className="font-mono text-[12px]"> Grok Build</span>, or+ <span className="font-mono text-[12px]"> Cursor</span> — each agent gets its own isolatedworkspace, memory and skills there.</p>@@ -858,12 +860,12 @@ function ComputersTab() {Run this on the machine you want to host agents:</div><div className="text-[11.5px] text-ink-500 mb-2.5 italic font-display">- Needs <span className="font-mono not-italic">claude</span>, <span className="font-mono not-italic">codex</span>, or <span className="font-mono not-italic">grok</span> installed. The computer names itself after that machine and appears here once paired. This token stays valid.+ Needs <span className="font-mono not-italic">claude</span>, <span className="font-mono not-italic">codex</span>, <span className="font-mono not-italic">grok</span>, or <span className="font-mono not-italic">cursor-agent</span> installed. The computer names itself after that machine and appears here once paired. This token stays valid.</div><div className="flex items-center gap-2.5 mb-2.5"><span className="text-[12px] text-ink-500">Engine</span><div className="inline-flex rounded-[9px] p-0.5" style={{ background: 'var(--ink-100)' }}>- {([['claude', 'Claude Code'], ['codex', 'Codex'], ['grok', 'Grok Build']] as const).map(([id, label]) => (+ {([['claude', 'Claude Code'], ['codex', 'Codex'], ['grok', 'Grok Build'], ['cursor', 'Cursor']] 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 === iddiff --git a/src/desktop/ObservabilityView.tsx b/src/desktop/ObservabilityView.tsxindex 8e3b034..532f869 100644--- a/src/desktop/ObservabilityView.tsx+++ b/src/desktop/ObservabilityView.tsx@@ -631,9 +631,9 @@ function StatCard({ label, value, sub, tone }: {* (haiku/mini = cerebellum/small; everything else = main/big). */function PriceMenuTable({ rows }: { rows: { model: string; inPer1M: number; cachedInPer1M: number; outPer1M: number; estimated: boolean }[] }) {if (rows.length === 0) return null- // Each engine's cerebellum: claude→haiku, codex→gpt-5.4-mini, grok→grok-4.5- // (see the daemon's triageModel). Without grok-4.5 here every Grok triage hop- // renders as "big brain" and the brain-tier split reads wrong.+ // 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.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">@@ -817,7 +817,7 @@ function TriageEconomicsPanel(props: {{data.byoaShare > 0 && (<div className="rounded-[10px] border border-gold bg-cloud px-3.5 py-2.5 text-[11px] leading-[1.6] text-gold-deep">- <b>{fmtPct(data.byoaShare)} of these run on BYOA</b> (your own Claude/Codex). If that's a flat-rate plan (e.g. Claude Max), these dollars are <b>meter-equivalent</b> — what the same tokens would cost on the pay-as-you-go API, <b>NOT your real bill</b> (which is ≈ $0 marginal until you hit your plan's rate limit). For a flat-rate plan the real, plan-independent cost is the <b>tokens / quota</b>, not the $. The $ is still a faithful RELATIVE measure of triage-vs-turn.+ <b>{fmtPct(data.byoaShare)} of these run on BYOA</b> (your own local engine). If that's a flat-rate plan (e.g. Claude Max), these dollars are <b>meter-equivalent</b> — what the same tokens would cost on the pay-as-you-go API, <b>NOT your real bill</b> (which is ≈ $0 marginal until you hit your plan's rate limit). For a flat-rate plan the real, plan-independent cost is the <b>tokens / quota</b>, not the $. The $ is still a faithful RELATIVE measure of triage-vs-turn.</div>)}diff --git a/src/desktop/Onboarding.tsx b/src/desktop/Onboarding.tsxindex 8f4968a..227c887 100644--- a/src/desktop/Onboarding.tsx+++ b/src/desktop/Onboarding.tsx@@ -20,7 +20,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'>('claude')+ const [engine, setEngine] = useState<'claude' | 'codex' | 'grok' | 'cursor'>('claude')// Default to installing the always-on service: it auto-starts on boot,// 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.@@ -67,8 +67,10 @@ export function Onboarding() {</div><p className="text-[14.5px] text-ink-600 leading-relaxed mb-6 max-w-[560px]">Your agents run on <strong>your own machine</strong> (or a VPS), powered by your local- <span className="font-mono text-[13px]"> Claude Code</span> or- <span className="font-mono text-[13px]"> Codex</span>. Pair a computer to get started —+ <span className="font-mono text-[13px]"> Claude Code</span>,+ <span className="font-mono text-[13px]"> Codex</span>,+ <span className="font-mono text-[13px]"> Grok Build</span>, or+ <span className="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.</p>@@ -77,7 +79,7 @@ export function Onboarding() {<><div className="text-[13px] text-ink-600 mb-4">On the machine you want to host your agents, you'll run one command. It needs- <span className="font-mono"> claude</span>, <span className="font-mono">codex</span>, or <span className="font-mono">grok</span> installed.+ <span className="font-mono"> claude</span>, <span className="font-mono">codex</span>, <span className="font-mono">grok</span>, or <span className="font-mono">cursor-agent</span> installed.</div>{err && <div className="text-[12px] text-coral-deep bg-coral-soft rounded-[8px] p-2 mb-3">{err}</div>}<button onClick={getCode} disabled={busy}@@ -94,7 +96,7 @@ export function Onboarding() {<div className="flex items-center gap-2.5 mb-2.5"><span className="text-[12px] text-ink-500">Engine</span><div className="inline-flex rounded-[9px] p-0.5" style={{ background: 'var(--ink-100)' }}>- {([['claude', 'Claude Code'], ['codex', 'Codex'], ['grok', 'Grok Build']] as const).map(([id, label]) => (+ {([['claude', 'Claude Code'], ['codex', 'Codex'], ['grok', 'Grok Build'], ['cursor', 'Cursor']] 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 === iddiff --git a/src/types.ts b/src/types.tsindex f26e3be..7272681 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'+export type EngineId = 'managed' | 'claude' | 'codex' | 'grok' | 'cursor'export interface Computer {id: string