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): run agents on Gemini CLI (#99)
Xialie Zhuangf1eafc1d96f6
diff --git a/agent-cli/README.md b/agent-cli/README.mdindex 75a982b..be18b48 100644--- a/agent-cli/README.md+++ b/agent-cli/README.md@@ -21,5 +21,5 @@ npx cumora agent computer --server <your-server-url>```Requires **Node ≥ 18** and `claude` (Claude Code), `codex`, `grok` (Grok Build),-`cursor-agent` (Cursor), `opencode`, or `pi` on your `PATH`. The daemon talks to the Cumora server over HTTPS only — it needs no+`cursor-agent` (Cursor), `opencode`, `pi`, or `gemini` (Gemini CLI) on your `PATH`. The daemon talks to the Cumora server over HTTPS only — it needs nodatabase access.diff --git a/agent-cli/src/cli.ts b/agent-cli/src/cli.tsindex 2a98864..dc9fe58 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), `cursor-agent` (Cursor), `opencode`, or `pi` on PATH. Get a pairing code from\n' ++ 'Needs `claude` (Claude Code), `codex`, `grok` (Grok Build), `cursor-agent` (Cursor), `opencode`, `pi`, or `gemini` (Gemini CLI) on PATH. Get a pairing code from\n' +'Cumora → You → Computers → Add a computer.\n',)process.exit(argv.length ? 1 : 0)diff --git a/docs/BYOA.md b/docs/BYOA.mdindex 158bc71..f4c95ba 100644--- a/docs/BYOA.md+++ b/docs/BYOA.md@@ -1,4 +1,4 @@-# BYOA — Bring Your Own Agent (local Claude Code / Codex / Grok Build / Cursor Agent / OpenCode / pi as the engine)+# BYOA — Bring Your Own Agent (local Claude Code / Codex / Grok Build / Cursor Agent / OpenCode / pi / Gemini CLI as the engine)Every Cumora agent has a "brain" and a host. The managed path isserver-side: `runAgentTurn` in `server/src/agents/turn.ts` runs a@@ -8,7 +8,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**, **Grok Build** (`grok`), **Cursor Agent** (`cursor-agent`),-**OpenCode** (`opencode`), or **pi** (`pi`) as the reasoning engine, on the user's own provider+**OpenCode** (`opencode`), **pi** (`pi`), or **Gemini CLI** (`gemini`) as the reasoning engine, on the user's own provideraccount — the server never holds the user's provider credentials.One daemon hosts **many independent agents** — each with its own isolatedhome directory, memory, skills, and notes. In Cumora these still appear@@ -39,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 / OpenCode / pi). Agents you place here are BYOA agents.+ Codex / Grok Build / Cursor Agent / OpenCode / pi / Gemini CLI). Agents you place here are BYOA agents.```Computers@@ -184,13 +184,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`, `opencode`). Persistent per-agent+engine (`claude`, `codex`, `grok`, `cursor`, `opencode`, `gemini`). Persistent per-agentsessions are preferred when the CLI exposes one; Cursor and OpenCode useone-shot `run()` for every wake and resume the session id reported by the CLI.```tsinterface EngineAdapter {- id: 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode'+ id: 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode' | 'gemini'seedHome(home, persona) // lay out CLAUDE.md/AGENTS.md, skills, dirsstartSession?(args): EngineSession | null // persistent session (primary)run(args): Promise<…> // one-shot fallback@@ -205,20 +205,31 @@ interface EngineSession {}```-| Concern | Claude Code | Codex CLI | Grok Build | Cursor Agent | OpenCode | pi |-| --- | --- | --- | --- | --- | --- | --- |-| Persistent session | `claude -p --input-format stream-json --output-format stream-json --verbose [--resume <id>] [--model X]` | `codex app-server --listen stdio://`, driven over JSON-RPC (`thread/start` / `thread/resume`) | `grok agent --always-approve --no-leader … stdio`, driven over ACP | none in Cursor Agent `2026.08.11-e8db854` | none in the supported OpenCode `v1.18.20` contract; a new process resumes with `--session <id>` | `pi --mode rpc --session-id <id> --skill <home>/.pi/skills`; a turn is a `prompt` command, done at `agent_settled`; steering is pi's native `steer` |-| Standing prompt | `--append-system-prompt-file <home>/.cumora-standing-prompt.md` | `developerInstructions` on `thread/start` | ACP `_meta.rules` | inlined into each wake | inlined into each wake | `--append-system-prompt <home>/.cumora-standing-prompt.md` |-| One-shot fallback | `claude -p … --output-format stream-json` | `codex exec … --skip-git-repo-check` | `grok -p … --output-format streaming-messages-json` | `cursor-agent -p --output-format stream-json --force --trust [--resume <id>]` | `opencode run --format json --auto [--session <id>] [--model provider/model]` (prompt on stdin) | `pi <CUMORA_PI_ARGS> --session-id <id> -p` (print mode) |-| Fallback triggers | `CUMORA_CLAUDE_ARGS` set | `CUMORA_CODEX_ARGS` set, `CUMORA_CODEX_NO_APP_SERVER=1`, Windows, or git-init failure | `CUMORA_GROK_ARGS` set, `CUMORA_GROK_NO_ACP=1`, or Windows | always one-shot; `CUMORA_CURSOR_ARGS` overrides flags | always one-shot; `CUMORA_OPENCODE_ARGS` overrides run flags | `CUMORA_PI_ARGS` set |-| Memory / persona file | `CLAUDE.md` | `AGENTS.md` | `AGENTS.md` | `AGENTS.md` | `AGENTS.md` plus `.opencode/skills/` | `AGENTS.md` plus `.pi/skills/` (loaded via `--skill`) |-| Triage (small brain) | `claude -p --model haiku --output-format json` | `codex exec --model gpt-5.4-mini` | `grok -p --model grok-4.5 --output-format json` | `cursor-agent --mode ask -p --output-format stream-json --trust` | `opencode run --format json --agent cumora-triage`; the injected agent denies every tool permission | `pi --mode json --no-session --no-tools --no-extensions --no-skills --no-context-files [--model $CUMORA_TRIAGE_MODEL]` (multi-provider — no fixed cheap model; unset → pi's default) |+| Concern | Claude Code | Codex CLI | Grok Build | Cursor Agent | OpenCode | pi | Gemini CLI |+| --- | --- | --- | --- | --- | --- | --- | --- |+| Persistent session | `claude -p --input-format stream-json --output-format stream-json --verbose [--resume <id>] [--model X]` | `codex app-server --listen stdio://`, driven over JSON-RPC (`thread/start` / `thread/resume`) | `grok agent --always-approve --no-leader … stdio`, driven over ACP | none in Cursor Agent `2026.08.11-e8db854` | none in the supported OpenCode `v1.18.20` contract; a new process resumes with `--session <id>` | `pi --mode rpc --session-id <id> --skill <home>/.pi/skills`; a turn is a `prompt` command, done at `agent_settled`; steering is pi's native `steer` | none — Gemini CLI `0.57.0` has no stream-json INPUT mode, so there is no way to feed turn N+1 into a live process |+| Standing prompt | `--append-system-prompt-file <home>/.cumora-standing-prompt.md` | `developerInstructions` on `thread/start` | ACP `_meta.rules` | inlined into each wake | inlined into each wake | `--append-system-prompt <home>/.cumora-standing-prompt.md` | inlined into each wake |+| One-shot fallback | `claude -p … --output-format stream-json` | `codex exec … --skip-git-repo-check` | `grok -p … --output-format streaming-messages-json` | `cursor-agent -p --output-format stream-json --force --trust [--resume <id>]` | `opencode run --format json --auto [--session <id>] [--model provider/model]` (prompt on stdin) | `pi <CUMORA_PI_ARGS> --session-id <id> -p` (print mode) | `gemini --output-format stream-json --yolo [--resume <uuid>] [--model X]` (prompt on stdin; `GEMINI_CLI_TRUST_WORKSPACE=true`) |+| Fallback triggers | `CUMORA_CLAUDE_ARGS` set | `CUMORA_CODEX_ARGS` set, `CUMORA_CODEX_NO_APP_SERVER=1`, Windows, or git-init failure | `CUMORA_GROK_ARGS` set, `CUMORA_GROK_NO_ACP=1`, or Windows | always one-shot; `CUMORA_CURSOR_ARGS` overrides flags | always one-shot; `CUMORA_OPENCODE_ARGS` overrides run flags | `CUMORA_PI_ARGS` set | always one-shot; `CUMORA_GEMINI_ARGS` overrides run flags |+| Memory / persona file | `CLAUDE.md` | `AGENTS.md` | `AGENTS.md` | `AGENTS.md` | `AGENTS.md` plus `.opencode/skills/` | `AGENTS.md` plus `.pi/skills/` (loaded via `--skill`) | `GEMINI.md` plus `.gemini/skills/` |+| Triage (small brain) | `claude -p --model haiku --output-format json` | `codex exec --model gpt-5.4-mini` | `grok -p --model grok-4.5 --output-format json` | `cursor-agent --mode ask -p --output-format stream-json --trust` | `opencode run --format json --agent cumora-triage`; the injected agent denies every tool permission | `pi --mode json --no-session --no-tools --no-extensions --no-skills --no-context-files [--model $CUMORA_TRIAGE_MODEL]` (multi-provider — no fixed cheap model; unset → pi's default) | `gemini --output-format stream-json --model gemini-2.5-flash-lite` with a system-settings file setting `tools.core: []`, which registers no tool at all |Sessions carry a resume id (`~/.cumora/sessions/<agentId>.session`); afailed resume falls back to a fresh thread instead of wedging the agent.++Two Gemini-specific hazards are handled in the adapter rather than left to the+operator. In a folder it does not trust, `gemini` silently downgrades `--yolo`+to interactive approval — an unattended daemon then stalls on a prompt nobody+answers — so the daemon marks the home it created and seeded as trusted via+`GEMINI_CLI_TRUST_WORKSPACE`, an env var rather than the equivalent+`--skip-trust` flag because older builds ignore an unknown env var but treat an+unknown flag as fatal. And Gemini's `stats.input_tokens` is the whole prompt+INCLUDING cache reads, while `stats.input` is the fresh remainder; the ledger+bills `input` and reports `cached` separately, so a cached prefix is not+charged twice.Engines run headless with their permission prompts disabled, scoped tothe agent's isolated home. On Windows the daemon resolves the real-`claude`/`codex`/`grok`/`cursor-agent`/`opencode`/`pi` `.cmd` shims and routes large+`claude`/`codex`/`grok`/`cursor-agent`/`opencode`/`pi`/`gemini` `.cmd` shims and routes largeprompts via stdin. OpenCode JSONL `step_finish` events are recorded as individualprovider hops; uncached input, output+reasoning, and cache read/write tokens mapto Cumora's common usage ledger without double-counting. OpenCode may race its@@ -267,6 +278,7 @@ CUMORA_ENGINE_MODEL=local CUMORA_TRIAGE_MODEL=local-small cumora agent computer.claude/skills/<name>/SKILL.md ← this agent's skills (Claude).cursor/skills/ ← Cursor-native skill directory.opencode/skills/ ← OpenCode-native skill directory+ .gemini/skills/ ← Gemini-native skill directory.pi/skills/ ← pi-native skill directory (via --skill).claude/settings.json ← permissions (allow Bash)bin/cumora ← the shim (see below); bin/.runtime-token@@ -297,7 +309,7 @@ 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` / `~/.pi/agent`, Cursor's login store, or OpenCode's config/auth store).+`~/.codex` / `~/.grok` / `~/.pi/agent` / `~/.gemini`, Cursor's login store, or OpenCode's config/auth store).Agents are independent in all project state and share one engine login per host.---@@ -311,7 +323,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','grok','cursor','opencode','pi'] (daemon-detected)+ available_engines JSONB, -- ['claude','codex','grok','cursor','opencode','pi','gemini'] (daemon-detected)status TEXT NOT NULL, -- 'online' | 'offline' | 'busy'last_seen_at TIMESTAMP,credential_hash TEXT, -- SHA256 of the device tokendiff --git a/electron/main.cjs b/electron/main.cjsindex 2b407b9..82b345b 100644--- a/electron/main.cjs+++ b/electron/main.cjs@@ -1394,7 +1394,7 @@ ipcMain.handle('app:is-focused', () => {})// Keep in sync with src/lib/engines.ts. Official daemon detectEngines() only-// probes engines with adapters (claude/cursor/codex/grok/opencode/pi). The rest+// probes engines with adapters (claude/cursor/codex/grok/opencode/pi/gemini). The rest// are listed so the Me page can diagnose what is installed on THIS machine.const LOCAL_CLIS = [{diff --git a/scripts/guard-big-brain.mjs b/scripts/guard-big-brain.mjsindex c59e4cc..7bb4ba0 100644--- a/scripts/guard-big-brain.mjs+++ b/scripts/guard-big-brain.mjs@@ -80,7 +80,7 @@ export function lineViolations(rel, raw) {out.push('big-brain engine spawn (adapter.run) outside the gated daemon path')}// R4 — a supported engine binary spawned directly, outside the adapter.- if (/(?:spawn|execFile\w*|exec)\s*\(\s*['"`](claude|codex|grok|cursor-agent|opencode|pi)['"`]/.test(code) && !ALLOW.engineSpawn.includes(rel)) {+ if (/(?:spawn|execFile\w*|exec)\s*\(\s*['"`](claude|codex|grok|cursor-agent|opencode|pi|gemini)['"`]/.test(code) && !ALLOW.engineSpawn.includes(rel)) {out.push('engine binary spawned outside the engine adapter (bypasses the classify=small / run=big split)')}return outdiff --git a/server/src/__tests__/agents-computer-engine-gemini.test.ts b/server/src/__tests__/agents-computer-engine-gemini.test.tsnew file mode 100644index 0000000..f120680--- /dev/null+++ b/server/src/__tests__/agents-computer-engine-gemini.test.ts@@ -0,0 +1,397 @@+/**+ * Contract tests for the BYOA Gemini CLI adapter.+ *+ * Gemini is not installed in CI. Each test puts a fake `gemini` first on PATH+ * and replays the JSONL that `gemini --output-format stream-json` actually+ * emits — the envelope was taken from a real @google/gemini-cli 0.57.0 run and+ * from its shipped StreamJsonFormatter, not from the docs (which do not+ * describe the event shapes at all).+ *+ * Run: node --import tsx --test server/src/__tests__/agents-computer-engine-gemini.test.ts+ */+import { existsSync } from 'node:fs'+import { chmod, mkdtemp, mkdir, readFile, readdir, realpath, 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_GEMINI_ARGS+ delete process.env.CUMORA_TRIAGE_ARGS+ delete process.env.CUMORA_TRIAGE_MODEL+ process.env.PATH = ORIGINAL_PATH+ await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })))+})++const FAKE_GEMINI = `#!/usr/bin/env node+'use strict'+const fs = require('node:fs')+const argv = process.argv.slice(2)+const scenario = process.env.FAKE_GEMINI_SCENARIO || 'ok'+let stdin = ''+process.stdin.setEncoding('utf8')+process.stdin.on('data', (chunk) => { stdin += chunk })+process.stdin.on('end', () => {+ const at = (flag) => { const i = argv.indexOf(flag); return i >= 0 ? argv[i + 1] : null }+ const sid = at('--resume') || '557c5bc6-d970-46c1-a90b-b0c33cdeff29'+ const model = at('--model') || 'gemini-2.5-pro'+ if (process.env.FAKE_GEMINI_LOG) {+ fs.appendFileSync(process.env.FAKE_GEMINI_LOG, JSON.stringify({+ argv, stdin, cwd: process.cwd(),+ trust: process.env.GEMINI_CLI_TRUST_WORKSPACE || null,+ settingsPath: process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH || null,+ settingsOk: (() => {+ const p = process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH+ if (!p) return null+ try { JSON.parse(fs.readFileSync(p, 'utf8')); return true } catch { return false }+ })(),+ }) + '\\n')+ }+ const out = (event) => process.stdout.write(JSON.stringify({ timestamp: new Date().toISOString(), ...event }) + '\\n')+ out({ type: 'init', session_id: sid, model })++ if (scenario === 'auth-error') {+ // Verbatim shape of a real 0.57.0 failure before the first API call: a+ // result event whose every counter is zero.+ out({+ type: 'result', status: 'error',+ error: { type: 'unknown', message: '[API Error: API key not valid. Please pass a valid API key.]' },+ stats: {+ total_tokens: 0, input_tokens: 0, output_tokens: 0, cached: 0, input: 0,+ duration_ms: 0, tool_calls: 0, models: { 'gemini-2.5-flash': { total_tokens: 0, input_tokens: 0, output_tokens: 0, cached: 0, input: 0 } },+ },+ })+ process.exitCode = 1+ return+ }++ if (scenario === 'soft-error') {+ // A failed turn whose process still exits 0 — quota and safety refusals+ // arrive this way, so the stream, not the exit code, is the verdict.+ out({+ type: 'result', status: 'error',+ error: { type: 'quota', message: 'Quota exceeded for this model.' },+ stats: { total_tokens: 30, input_tokens: 30, output_tokens: 0, cached: 10, input: 20, duration_ms: 5, tool_calls: 0, models: {} },+ })+ return+ }+ if (scenario === 'stale-session') {+ process.stderr.write('Error resuming session: No previous sessions found for this project.\\n')+ process.exitCode = 1+ return+ }++ out({ type: 'message', role: 'user', content: stdin })+ if (scenario === 'tools') {+ out({ type: 'tool_use', tool_name: 'run_shell_command', tool_id: 'call-1', parameters: { command: 'ls' } })+ out({ type: 'tool_result', tool_id: 'call-1', status: 'success', output: 'a.ts' })+ out({ type: 'error', severity: 'warning', message: 'Loop detected, stopping execution' })+ }+ // Assistant text arrives as deltas, not one message.+ out({ type: 'message', role: 'assistant', content: 'echo:', delta: true })+ out({ type: 'message', role: 'assistant', content: stdin.trim(), delta: true })+ out({+ type: 'result', status: 'success',+ stats: {+ total_tokens: 152, input_tokens: 100, output_tokens: 12, cached: 40, input: 60,+ duration_ms: 1234, tool_calls: scenario === 'tools' ? 1 : 0,+ models: { [model]: { total_tokens: 152, input_tokens: 100, output_tokens: 12, cached: 40, input: 60 } },+ },+ })+})+`++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-gemini-'))+ 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, 'gemini')+ await writeFile(fake, FAKE_GEMINI, 'utf8')+ await chmod(fake, 0o755)+ return {+ root,+ home,+ log,+ env: {+ ...process.env,+ ...extraEnv,+ PATH: `${binDir}${delimiter}${ORIGINAL_PATH ?? ''}`,+ FAKE_GEMINI_LOG: log,+ FAKE_GEMINI_SCENARIO: scenario,+ },+ }+}++async function fakeLog(f: Fixture): Promise<Array<{+ argv: string[]+ stdin: string+ cwd: string+ trust: string | null+ settingsPath: string | null+ settingsOk: boolean | null+}>> {+ if (!existsSync(f.log)) return []+ return (await readFile(f.log, 'utf8')).split('\n').filter(Boolean).map((line) => JSON.parse(line))+}++const noop = { onLog: () => {}, signal: new AbortController().signal }++// ── the turn ────────────────────────────────────────────────────────────────++test('gemini run streams a turn, keeps the session id, and sends the prompt on stdin', { skip: IS_WIN }, async () => {+ const f = await fixture()+ const res = await getAdapter('gemini').run({+ home: f.home, prompt: 'hello there', env: f.env, model: 'gemini-2.5-pro', ...noop,+ })++ assert.equal(res.exitCode, 0)+ assert.equal(res.error, undefined)+ assert.equal(res.sessionId, '557c5bc6-d970-46c1-a90b-b0c33cdeff29')+ assert.equal(res.model, 'gemini-2.5-pro')++ const [call] = await fakeLog(f)+ // The prompt never rides in argv: `gemini` reads it from stdin when no -p is+ // given, which is also what keeps a Windows .cmd shim able to carry it.+ assert.equal(call.stdin, 'hello there')+ assert.ok(!call.argv.includes('hello there'))+ assert.deepEqual(call.argv.slice(0, 2), ['--output-format', 'stream-json'])+ assert.ok(call.argv.includes('--yolo'))+ // realpath: macOS resolves /var to /private/var inside the child.+ assert.equal(call.cwd, await realpath(f.home))+})++test('the assistant deltas are joined and the echo of our own prompt is not', { skip: IS_WIN }, async () => {+ // A `message` event carries role user OR assistant. Folding the user echo in+ // would hand triage its own prompt back as the classification.+ const f = await fixture()+ const res = await getAdapter('gemini').classify({+ cwd: f.home, prompt: 'ping', env: f.env, ...noop,+ })+ assert.equal(res.text, 'echo:ping')+})++test('gemini run resumes by session UUID', { skip: IS_WIN }, async () => {+ const f = await fixture()+ const res = await getAdapter('gemini').run({+ home: f.home, prompt: 'again', env: f.env, resumeSessionId: 'b4cb9d1e-d37e-42aa-8769-e47cf186523f', ...noop,+ })+ const [call] = await fakeLog(f)+ // --resume also accepts "latest" and a 1-based index, but only the UUID is+ // stable across wakes: an index shifts as sessions accumulate.+ assert.ok(call.argv.includes('--resume'))+ assert.equal(call.argv[call.argv.indexOf('--resume') + 1], 'b4cb9d1e-d37e-42aa-8769-e47cf186523f')+ assert.equal(res.sessionId, 'b4cb9d1e-d37e-42aa-8769-e47cf186523f')+})++test('the workspace is trusted through the environment, not a flag', { skip: IS_WIN }, async () => {+ // Gemini silently downgrades --yolo to interactive approval in an untrusted+ // folder, which strands an unattended daemon. The env var does the same job+ // as --skip-trust but is IGNORED by builds that predate it, where an unknown+ // flag would instead be a fatal argv error.+ const f = await fixture()+ await getAdapter('gemini').run({ home: f.home, prompt: 'x', env: f.env, ...noop })+ const [call] = await fakeLog(f)+ assert.equal(call.trust, 'true')+ assert.ok(!call.argv.includes('--skip-trust'))+})++// ── usage, and the field that must not be billed ────────────────────────────++test('cache reads are not billed twice', { skip: IS_WIN }, async () => {+ // THE trap in this envelope. Gemini's `stats.input_tokens` is the FULL prompt+ // (uiTelemetryService sets tokens.prompt from input_token_count, cached+ // segment included) and `stats.input` is prompt − cached. Billing the+ // similarly-named field while also reporting `cached` charges the cached+ // prefix twice — and a BYOA agent re-sends a large stable prefix every wake.+ const f = await fixture()+ const res = await getAdapter('gemini').run({ home: f.home, prompt: 'x', env: f.env, ...noop })+ assert.deepEqual(res.usage, {+ input_tokens: 60, // stats.input, NOT stats.input_tokens (100)+ output_tokens: 12,+ cache_read_input_tokens: 40,+ })+ // 60 + 40 is the 100 the CLI called the prompt — counted once.+ assert.equal((res.usage?.input_tokens ?? 0) + (res.usage?.cache_read_input_tokens ?? 0), 100)+})++test('a turn that died before its first API call reports no usage at all', { skip: IS_WIN }, async () => {+ // The auth-failure shape is a full stats block of zeros. Passing it through+ // would put a row in the cost ledger for work that never happened.+ const f = await fixture('auth-error')+ const res = await getAdapter('gemini').run({ home: f.home, prompt: 'x', env: f.env, ...noop })+ assert.equal(res.usage, undefined)+ assert.notEqual(res.exitCode, 0)+ assert.match(res.error ?? '', /API key not valid/)+})++test('a failed result event fails the turn even when the process exits 0', { skip: IS_WIN }, async () => {+ // Quota and safety refusals arrive as status:'error' on a cleanly-exiting+ // process. Trusting the exit code alone would record the turn as a success+ // that simply said nothing.+ const f = await fixture('soft-error')+ const res = await getAdapter('gemini').run({ home: f.home, prompt: 'x', env: f.env, ...noop })+ assert.equal(res.exitCode, 1)+ assert.match(res.error ?? '', /Quota exceeded/)+ // The tokens it DID burn before failing are still billed.+ assert.deepEqual(res.usage, { input_tokens: 20, output_tokens: 0, cache_read_input_tokens: 10 })+})++test('the resolved model wins over the requested one', { skip: IS_WIN }, async () => {+ // `-m` takes aliases (`pro`, `flash-lite`), and a mid-turn fallback can move+ // the turn to another model. The stats key is the id that was really used,+ // and the one cost must be priced on.+ const f = await fixture()+ const res = await getAdapter('gemini').run({+ home: f.home, prompt: 'x', env: f.env, model: 'gemini-2.5-flash', ...noop,+ })+ assert.equal(res.model, 'gemini-2.5-flash')+})++test('the turn total is reported as one hop', { skip: IS_WIN }, async () => {+ // Gemini publishes token stats only at the end of a turn, so — as with codex+ // exec — there is one hop carrying the whole turn rather than a trajectory.+ const hops: EngineHopReport[] = []+ const f = await fixture('tools')+ await getAdapter('gemini').run({+ home: f.home, prompt: 'x', env: f.env, model: 'gemini-2.5-pro',+ onHopUsage: (h) => hops.push(h), ...noop,+ })+ assert.equal(hops.length, 1)+ assert.equal(hops[0].model, 'gemini-2.5-pro')+ assert.deepEqual(hops[0].usage, { input_tokens: 60, output_tokens: 12, cache_read_input_tokens: 40 })+ assert.equal(hops[0].toolUses, 1)+ assert.equal(hops[0].hopIndex, 1)+})++test('a warning-severity event does not fail the turn', { skip: IS_WIN }, async () => {+ // Loop detection and blocked tools arrive as `error` events with+ // severity:'warning'; the run survives them and the result event decides.+ const f = await fixture('tools')+ const res = await getAdapter('gemini').run({ home: f.home, prompt: 'x', env: f.env, ...noop })+ assert.equal(res.exitCode, 0)+ assert.equal(res.error, undefined)+})++// ── triage ──────────────────────────────────────────────────────────────────++test('triage runs tool-free on the cheap model', { skip: IS_WIN }, async () => {+ const f = await fixture()+ await getAdapter('gemini').classify({ cwd: f.home, prompt: 'classify this', env: f.env, ...noop })+ const [call] = await fakeLog(f)++ assert.equal(call.argv[call.argv.indexOf('--model') + 1], 'gemini-2.5-flash-lite')+ assert.ok(call.settingsPath, 'triage must point gemini at a settings file')+ // `tools.core` is an allowlist applied per tool as `coreTools.some(...)`. An+ // empty array is truthy and matches nothing, so NO core tool is registered —+ // and with no tool to confirm, a headless approval prompt that nothing would+ // answer cannot arise.+ const settings = JSON.parse(await readFile(call.settingsPath as string, 'utf8'))+ assert.deepEqual(settings, { tools: { core: [] } })+})++test('concurrent triage shares one cwd cleanly and leaves no staging files', { skip: IS_WIN }, async () => {+ // The triage cwd is SHARED — the doctor hands the same dir to every engine's+ // probe, and concurrent classifies land there too. The adapter stages the+ // settings file and renames it into place rather than writeFile-ing onto the+ // live path, because writeFile truncates first and a reader can land in that+ // window; identical content is no defence against a zero-length read.+ //+ // That window is far too narrow to provoke deterministically (spawn latency+ // dwarfs a 22-byte write), so this pins what IS observable: every concurrent+ // caller gets a parseable file, and nothing is left behind.+ const f = await fixture()+ const adapter = getAdapter('gemini')+ await Promise.all(Array.from({ length: 12 }, () =>+ adapter.classify({ cwd: f.home, prompt: 'x', env: f.env, ...noop })))++ const calls = await fakeLog(f)+ assert.equal(calls.length, 12)+ for (const call of calls) assert.equal(call.settingsOk, true, call.settingsPath ?? 'no settings path')+ const stray = (await readdir(f.home)).filter((n) => n.startsWith('.cumora-gemini-triage.') && n !== '.cumora-gemini-triage.json')+ assert.deepEqual(stray, [], 'a rename was skipped and left a staging file behind')+})++test('CUMORA_TRIAGE_MODEL overrides the triage model', { skip: IS_WIN }, async () => {+ process.env.CUMORA_TRIAGE_MODEL = 'gemini-2.5-flash'+ const f = await fixture()+ await getAdapter('gemini').classify({ cwd: f.home, prompt: 'x', env: f.env, ...noop })+ const [call] = await fakeLog(f)+ assert.equal(call.argv[call.argv.indexOf('--model') + 1], 'gemini-2.5-flash')+})++test('the small doctor probe runs the SAME model triage does', { skip: IS_WIN }, async () => {+ // Otherwise doctor reports a red small brain for an operator whose triage+ // model is configured correctly.+ process.env.CUMORA_TRIAGE_MODEL = 'gemini-2.5-flash'+ const f = await fixture()+ await getAdapter('gemini').probe({ tier: 'small', cwd: f.home, env: f.env, signal: noop.signal })+ const [call] = await fakeLog(f)+ assert.equal(call.argv[call.argv.indexOf('--model') + 1], 'gemini-2.5-flash')+})++test('the wake probe is skipped because the wake IS the one-shot path', { skip: IS_WIN }, async () => {+ const res = await getAdapter('gemini').probeWake({+ cwd: tmpdir(), env: process.env, signal: noop.signal,+ })+ assert.deepEqual(res, { ok: true, detail: '', skipped: true })+})++// ── home layout and overrides ───────────────────────────────────────────────++test('gemini seedHome writes GEMINI.md, native skills, and common directories', { skip: IS_WIN }, async () => {+ const f = await fixture()+ await getAdapter('gemini').seedHome(f.home, {+ id: 'gemini', name: 'Gem', role: 'Reviewer', systemPrompt: 'Review only.',+ })++ const persona = await readFile(join(f.home, 'GEMINI.md'), 'utf8')+ assert.match(persona, /^# Gem — Reviewer/)+ assert.match(persona, /Review only\./)+ assert.match(persona, /`GEMINI\.md` \(this file\)/)+ assert.match(persona, /`\.gemini\/skills\/` — your skills/)+ assert.doesNotMatch(persona, /CLAUDE\.md|AGENTS\.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, '.gemini', 'skills')))+})++test('CUMORA_GEMINI_ARGS takes over argv but keeps resume and the stdin prompt', { skip: IS_WIN }, async () => {+ process.env.CUMORA_GEMINI_ARGS = '--output-format json --debug'+ const f = await fixture()+ await getAdapter('gemini').run({+ home: f.home, prompt: 'override me', env: f.env, resumeSessionId: 'sid-42', ...noop,+ })+ const [call] = await fakeLog(f)+ assert.deepEqual(call.argv, ['--output-format', 'json', '--debug', '--resume', 'sid-42'])+ assert.equal(call.stdin, 'override me')+ // Continuity and the untrusted-folder stall are not the user's to opt out of.+ assert.equal(call.trust, 'true')+})++test('gemini is detected on PATH', { skip: IS_WIN }, async () => {+ const f = await fixture()+ const before = process.env.PATH+ process.env.PATH = f.env.PATH as string+ try {+ assert.ok((await detectEngines()).includes('gemini'))+ } finally {+ process.env.PATH = before+ }+})diff --git a/server/src/agents/computer/engine.ts b/server/src/agents/computer/engine.tsindex c485a41..14a351a 100644--- a/server/src/agents/computer/engine.ts+++ b/server/src/agents/computer/engine.ts@@ -22,7 +22,7 @@*/import { spawn as nodeSpawn, execFileSync, type ChildProcess, type SpawnOptions } from 'node:child_process'import { randomUUID } from 'node:crypto'-import { mkdir, writeFile, access, mkdtemp } from 'node:fs/promises'+import { mkdir, writeFile, access, mkdtemp, rename } from 'node:fs/promises'import { existsSync, writeFileSync } from 'node:fs'import { homedir, tmpdir } from 'node:os'import { join, delimiter as PATH_DELIMITER } from 'node:path'@@ -110,10 +110,10 @@ export function resolveSpawn(bin: string): { command: string; shell: boolean; wareturn { command: bin, shell: true, wantsStdinPrompt: true }}-export type EngineId = 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode' | 'pi'+export type EngineId = 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode' | 'pi' | 'gemini'/** The pairable engine ids, in the daemon's default detection order. */-export const ENGINE_IDS: EngineId[] = ['claude', 'codex', 'grok', 'cursor', 'opencode', 'pi']+export const ENGINE_IDS: EngineId[] = ['claude', 'codex', 'grok', 'cursor', 'opencode', 'pi', 'gemini']export interface EnginePersona {id: string@@ -3329,6 +3329,416 @@ class PiAdapter implements EngineAdapter {}}+// ── Gemini CLI ───────────────────────────────────────────────────────────────+//+// `gemini -o stream-json` emits JSONL, but NOT Claude Code's stream-json: the+// envelope below is what its own StreamJsonFormatter writes (verified against+// the shipped 0.57.0 bundle and by running the binary). Sibling forks are not+// safe to assume compatible either — Qwen Code shares Gemini's flags and emits+// Claude's envelope instead.++interface GeminiTokenStats {+ /** Gemini's PROMPT total. Cache reads are INCLUDED here — see geminiUsage. */+ input_tokens?: number+ output_tokens?: number+ cached?: number+ /** prompt − cached. The fresh input, and the one the ledger wants. */+ input?: number+}++interface GeminiStats extends GeminiTokenStats {+ total_tokens?: number+ duration_ms?: number+ tool_calls?: number+ /** Per-model breakdown, keyed by the model the CLI RESOLVED (`-m flash` and a+ * mid-turn fallback both land here under their real ids). */+ models?: Record<string, GeminiTokenStats>+}++interface GeminiEvent {+ type?: string+ session_id?: string+ model?: string+ role?: string+ content?: unknown+ status?: string+ severity?: string+ message?: string+ error?: { type?: string; message?: string }+ stats?: GeminiStats+}++/** Map Gemini's token stats onto the common (Anthropic-shaped) usage record.+ *+ * The field named `input_tokens` is NOT the one to bill. uiTelemetryService+ * sets `tokens.prompt` from the API's `input_token_count`, which already+ * contains the cached prefix, and then derives `tokens.input = prompt −+ * cached`; `convertToStreamStats` publishes the first as `input_tokens` and+ * the second as `input`. Billing `input_tokens` while ALSO reporting `cached`+ * charges the cached prefix twice — and a BYOA agent re-sends a large stable+ * prefix on every wake, so that prefix is most of the prompt. */+function geminiUsage(stats: GeminiStats | undefined): EngineUsage | undefined {+ if (!stats || typeof stats !== 'object') return undefined+ const num = (value: unknown): number =>+ typeof value === 'number' && Number.isFinite(value) ? Math.max(0, value) : 0+ const cached = num(stats.cached)+ const fresh = stats.input != null ? num(stats.input) : Math.max(0, num(stats.input_tokens) - cached)+ const output = num(stats.output_tokens)+ // A turn that died before its first API call reports every counter as 0 (the+ // auth-failure shape). Reporting that as usage would put a zero-token row in+ // the ledger for work that never happened.+ if (!fresh && !output && !cached) return undefined+ return {+ input_tokens: fresh,+ output_tokens: output,+ cache_read_input_tokens: cached,+ // Gemini's implicit caching is not billed as a separate write, and its+ // stats carry no creation counter — leave it absent rather than invent 0.+ }+}++/** The model a turn actually ran on. `init` reports what was REQUESTED; the+ * stats key reports what the CLI resolved (an alias like `flash`, or a+ * mid-turn fallback, differ). Prefer the resolved id when it is unambiguous —+ * cost is priced on it — and keep the requested one when several models ran. */+function geminiResolvedModel(stats: GeminiStats | undefined, seen: string | null): string | null {+ const names = stats?.models ? Object.keys(stats.models) : []+ return names.length === 1 ? names[0] : seen+}++class GeminiTurnTracker {+ text = ''+ sessionId: string | null = null+ model: string | null = null+ usage: EngineUsage | undefined+ error: string | null = null+ private startedAt: number | null = null+ private toolUses = 0+ private textChars = 0++ constructor(+ pin: string | null,+ private readonly onHopUsage?: (report: EngineHopReport) => void,+ ) {+ this.model = pin+ }++ observe(event: GeminiEvent): void {+ if (typeof event.session_id === 'string' && event.session_id) this.sessionId = event.session_id++ if (event.type === 'init') {+ if (typeof event.model === 'string' && event.model) this.model = event.model+ this.startedAt = Date.now()+ return+ }++ if (event.type === 'message') {+ // Assistant text arrives as deltas; the user echo of our own prompt must+ // never be folded into the reply triage reads.+ if (event.role === 'assistant' && typeof event.content === 'string') {+ this.text += event.content+ this.textChars += event.content.length+ }+ return+ }++ if (event.type === 'tool_use') { this.toolUses += 1; return }++ if (event.type === 'error') {+ // `severity: 'warning'` is a loop-detection / blocked-tool notice the run+ // survives. Only an error ends the turn, and the terminating `result`+ // event carries the authoritative verdict anyway.+ if (event.severity !== 'warning' && typeof event.message === 'string') this.error = event.message+ return+ }++ if (event.type !== 'result') return+ if (event.status === 'error') {+ const detail = event.error?.message ?? event.message+ if (typeof detail === 'string' && detail) this.error = detail+ else if (!this.error) this.error = 'gemini reported a failed turn with no detail'+ }+ this.model = geminiResolvedModel(event.stats, this.model)+ const usage = geminiUsage(event.stats)+ if (!usage) return+ this.usage = usage+ if (this.onHopUsage) {+ // Gemini publishes token stats only at the end of the turn, so — as with+ // codex exec — this is ONE hop carrying the turn's whole usage rather+ // than a per-round-trip trajectory. Reporting it is what keeps BYOA+ // spend visible in the same ledger as everything else.+ try {+ this.onHopUsage({+ model: this.model ?? 'gemini',+ usage,+ latencyMs: this.startedAt == null ? undefined : Date.now() - this.startedAt,+ hopIndex: 1,+ toolUses: this.toolUses,+ textChars: this.textChars,+ })+ } catch { /* ledger reporting is best-effort */ }+ }+ }+}++function parseGeminiLine(line: string): GeminiEvent | null {+ if (!line.startsWith('{')) return null+ try { return JSON.parse(line) as GeminiEvent } catch { return null }+}++/** Gemini refuses to act on an untrusted folder, and — worse for an unattended+ * daemon — SILENTLY downgrades `--yolo` to interactive approval there+ * ("Approval mode overridden to 'default' because the current folder is not+ * trusted"), so the turn stalls waiting for a human who is not present.+ *+ * The env var, not the equivalent `--skip-trust` flag: an unknown env var is+ * ignored by older builds, while an unknown flag is a fatal argv error. The+ * home really is ours to trust — the daemon created and seeded it. */+function geminiEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {+ return { ...env, GEMINI_CLI_TRUST_WORKSPACE: 'true' }+}++async function spawnGeminiStream(+ 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 GeminiTurnTracker(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 = parseGeminiLine(line)+ if (event) tracker.observe(event)+ opts.onLog?.(line)+ },+ signal: opts.signal,+ },+ // The prompt goes on stdin on EVERY platform: `gemini` reads it there+ // when no -p is given, which sidesteps both argv length limits and the+ // Windows .cmd shim's inability to carry a multi-line argument.+ { 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 exitCode = processResult.exitCode !== 0 ? processResult.exitCode : (eventError ? 1 : 0)+ return {+ exitCode,+ // Same precedence as the other stream adapters: a real process failure+ // (auth, quota, bad flag, abort) explains more than the secondary fact that+ // the stream reported a failed turn. Keep the event's prose alongside it so+ // stale-session recovery can match on it without parsing JSON.+ error: processResult.exitCode !== 0+ ? [processResult.error, eventError].filter(Boolean).join('\n')+ : (eventError ?? undefined),+ sessionId: tracker.sessionId,+ usage: tracker.usage,+ model: tracker.model,+ text: tracker.text,+ }+}++/** Settings that leave the triage process with NO tools at all.+ *+ * `tools.core` is an allowlist, and the registry applies it as+ * `coreTools.some(...)` per tool — an EMPTY array is truthy, matches nothing,+ * and so registers nothing. That is a stronger guarantee than triage gets on+ * other engines: with no tool to confirm, a headless approval prompt (which+ * nothing would answer) cannot arise, and the classifier stays a one-shot. */+const GEMINI_TRIAGE_SETTINGS = JSON.stringify({ tools: { core: [] } })+const GEMINI_TRIAGE_SETTINGS_FILE = '.cumora-gemini-triage.json'++class GeminiAdapter implements EngineAdapter {+ readonly id = 'gemini' as const+ readonly bin = 'gemini'++ /** stream-json on BOTH paths, including triage. `-o json` writes nothing to+ * stdout when the turn fails before the model answers (the auth-failure+ * case) and reports it only on stderr, while stream-json still emits a+ * `result` event carrying the reason. */+ private static readonly STREAM = ['--output-format', 'stream-json']++ 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] : []+ // `--resume` takes "latest", a 1-based index, or a full session UUID —+ // findSession() matches the UUID first, which is the only stable handle+ // across wakes (an index shifts as sessions accumulate).+ const resume = args.resumeSessionId ? ['--resume', args.resumeSessionId] : []+ return spawnGeminiStream(+ command,+ [...GeminiAdapter.STREAM, '--yolo', ...resume, ...model],+ {+ cwd: args.cwd,+ env: geminiEnv(args.env),+ prompt,+ signal: args.signal,+ onLog: args.onLog,+ shell,+ onHopUsage: args.onHopUsage,+ pin: args.model ?? null,+ },+ )+ }++ private async 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 = ['--model', args.model || triageModel('gemini-2.5-flash-lite')]+ const settings = join(args.cwd, GEMINI_TRIAGE_SETTINGS_FILE)+ let env = geminiEnv(args.env)+ try {+ // Write-then-rename, not writeFile onto the live path. The triage cwd is+ // shared — the doctor hands the SAME dir to every engine's probe, and+ // concurrent classifies land there too — and writeFile truncates before+ // it writes, so a second caller can be mid-truncate while gemini is+ // reading. Identical content does not save us from a zero-length read;+ // rename is atomic, so a reader sees one whole file or the other.+ const staged = `${settings}.${process.pid}.${randomUUID().slice(0, 8)}`+ await writeFile(staged, GEMINI_TRIAGE_SETTINGS, 'utf8')+ await rename(staged, settings)+ // System scope so it wins over any user/workspace settings the operator+ // has; it MERGES with them, so their auth config is untouched.+ env = { ...env, GEMINI_CLI_SYSTEM_SETTINGS_PATH: settings }+ } catch {+ // Triage still works with tools present — the cwd is neutral and the+ // prompt asks for a direct answer. Losing the guarantee is not worth+ // losing the classification.+ }+ return spawnGeminiStream(+ command,+ [...GeminiAdapter.STREAM, '--yolo', ...model],+ {+ cwd: args.cwd,+ env,+ prompt,+ signal: args.signal,+ onLog: args.onLog,+ shell,+ pin: model[1],+ },+ )+ }++ async classify(args: EngineClassifyArgs): Promise<EngineClassifyResult> {+ const flags = extraArgs('CUMORA_TRIAGE_ARGS')+ if (flags.length) {+ // Whole user-owned override: output becomes opaque, but the prompt still+ // travels on stdin so a Windows shim and a long prompt both survive.+ const { command, shell } = resolveSpawn(this.bin)+ return spawnCapture(command, flags, {+ cwd: args.cwd,+ env: geminiEnv(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> {+ // Concrete ids rather than Gemini's `pro` / `flash-lite` aliases: the+ // aliases only exist in recent builds, and an operator running an older+ // `gemini` would get a model-not-found from the doctor probe itself — a+ // red brain that says nothing about their actual configuration.+ const model = args.tier === 'small' ? triageModel('gemini-2.5-flash-lite') : 'gemini-2.5-pro'+ 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 process probe() already exercises;+ // --resume re-opens a conversation inside it, it is 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, '.gemini', 'skills'), { recursive: true })+ await writeFile(+ join(home, 'GEMINI.md'),+ PERSONA_HEADER(persona, { personaFile: 'GEMINI.md', skillsDir: '.gemini/skills/' }),+ 'utf8',+ )+ }++ async run(args: EngineRunArgs): Promise<EngineRunResult> {+ const flags = extraArgs('CUMORA_GEMINI_ARGS')+ if (flags.length) {+ const resume = args.resumeSessionId ? ['--resume', args.resumeSessionId] : []+ const { command, shell } = resolveSpawn(this.bin)+ return spawnEngine(command, [...flags, ...resume], { ...args, env: geminiEnv(args.env) }, { 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: gemini has no stream-json INPUT mode, so there is no way+ // to feed turn N+1 into a live process. --resume re-opens the conversation in+ // a fresh one, which is what the one-shot path already does.+}+const ADAPTERS: Record<EngineId, EngineAdapter> = {claude: new ClaudeAdapter(),codex: new CodexAdapter(),@@ -3336,6 +3746,7 @@ const ADAPTERS: Record<EngineId, EngineAdapter> = {cursor: new CursorAdapter(),opencode: new OpenCodeAdapter(),pi: new PiAdapter(),+ gemini: new GeminiAdapter(),}export function getAdapter(id: EngineId): EngineAdapter {diff --git a/server/src/agents/computer/registry.ts b/server/src/agents/computer/registry.tsindex b525e4e..9574f22 100644--- a/server/src/agents/computer/registry.ts+++ b/server/src/agents/computer/registry.ts@@ -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' | 'opencode' | 'pi'+export type EngineId = 'managed' | 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode' | 'pi' | 'gemini'export type ComputerStatus = 'online' | 'offline' | 'busy'/** How long a paired computer can go without a heartbeat before the sweepdiff --git a/server/src/agents/llm-ledger.ts b/server/src/agents/llm-ledger.tsindex 7a4606b..cc06400 100644--- a/server/src/agents/llm-ledger.ts+++ b/server/src/agents/llm-ledger.ts@@ -74,7 +74,7 @@ export type LlmCallPurpose =| 'agent-image'export type LlmCallStatus = 'ok' | 'rate_limited' | 'timeout' | 'failed'-export type LlmCallSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode' | 'byoa-pi'+export type LlmCallSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode' | 'byoa-pi' | 'byoa-gemini'/** 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 447b97d..8e039e2 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' | 'byoa-opencode' | 'byoa-pi'+export type TriageSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode' | 'byoa-pi' | 'byoa-gemini'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 9f54362..a26a685 100644--- a/server/src/agents/runtime/server.ts+++ b/server/src/agents/runtime/server.ts@@ -448,7 +448,8 @@ runtimeRouter.post('/llm-calls', withAgent(async (c, req, res) => {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-pi'+ body?.source === 'byoa-opencode' || body?.source === 'byoa-pi' ||+ body?.source === 'byoa-gemini') ? 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 : []diff --git a/server/src/api/router.ts b/server/src/api/router.tsindex d06e5e1..369c98e 100644--- a/server/src/api/router.ts+++ b/server/src/api/router.ts@@ -1115,7 +1115,8 @@ api.post('/computers/pair', safe(async (req, res) => {if ((await companyTier(paired.companyId)) === 'free') {const engine = (engines[0] === 'claude' || engines[0] === 'codex' || engines[0] === 'grok' ||- engines[0] === 'cursor' || engines[0] === 'opencode' || engines[0] === 'pi'+ engines[0] === 'cursor' || engines[0] === 'opencode' || engines[0] === 'pi' ||+ engines[0] === 'gemini') ? engines[0] : 'claude'// Adopt only agents that are stranded on the managed Cumora Cloud (or// unassigned) onto the just-paired machine — earlier builds' boot backfilldiff --git a/server/src/db/migrate.ts b/server/src/db/migrate.tsindex c55f382..310c0ec 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 | byoa-opencode | byoa-pi+ source TEXT NOT NULL, -- cloud | byoa-claude | byoa-codex | byoa-grok | byoa-cursor | byoa-opencode | byoa-pi | byoa-geminimodel TEXT,actionable BOOLEAN NOT NULL DEFAULT FALSE, -- verdict: woke the big brain?reason TEXT,@@ -1496,7 +1496,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','grok','cursor','opencode','pi']; ['managed'] for cloud+ available_engines JSONB NOT NULL DEFAULT '[]'::jsonb, -- ['claude','codex','grok','cursor','opencode','pi','gemini']; ['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@@ -1518,7 +1518,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' | 'opencode' | 'pi'+ALTER TABLE participants ADD COLUMN IF NOT EXISTS engine TEXT; -- 'managed' | 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode' | 'pi' | 'gemini'-- 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.tsindex 8679c57..224dfce 100644--- a/src/admin/api.ts+++ b/src/admin/api.ts@@ -120,7 +120,7 @@ export type LlmCallPurpose =| 'palette' | 'gender' | 'avatar-image' | 'agent-image'export type LlmCallStatus = 'ok' | 'rate_limited' | 'timeout' | 'failed'-export type LlmCallSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode' | 'byoa-pi'+export type LlmCallSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode' | 'byoa-pi' | 'byoa-gemini'export interface LlmSummary {sinceDays: numberdiff --git a/src/api/client.ts b/src/api/client.tsindex e560204..cbfadd3 100644--- a/src/api/client.ts+++ b/src/api/client.ts@@ -404,7 +404,7 @@ export interface ApiAgentRun {}// ── Triage cost-effectiveness ledger ──-export type ApiTriageSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode' | 'byoa-pi'+export type ApiTriageSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode' | 'byoa-pi' | 'byoa-gemini'export interface ApiTriageAgentRow {agentId: stringdiff --git a/src/lib/engines.ts b/src/lib/engines.tsindex 95a0fca..80b0bda 100644--- a/src/lib/engines.ts+++ b/src/lib/engines.ts@@ -26,7 +26,7 @@ export const ENGINE_BIN: Record<string, string> = {}/** Engines Cumora can actually wake. Everything else is detect-only. */-export const RUNNABLE_ENGINE_IDS = new Set(['claude', 'codex', 'grok', 'cursor', 'opencode', 'pi'])+export const RUNNABLE_ENGINE_IDS = new Set(['claude', 'codex', 'grok', 'cursor', 'opencode', 'pi', 'gemini'])export function engineLabel(id: string): string {return ENGINE_LABEL[id] ?? iddiff --git a/src/types.ts b/src/types.tsindex 69605b8..e9ba3e0 100644--- a/src/types.ts+++ b/src/types.ts@@ -7,7 +7,7 @@ export type Status = 'avail' | 'working' | 'thinking' | 'waiting' | 'resting'export type ComputerKind = 'cloud' | 'local' | 'vps'export type ComputerStatus = 'online' | 'offline' | 'busy'/** Engine an agent's host runs it on. 'managed' = Cumora's server-side loop. */-export type EngineId = 'managed' | 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode' | 'pi'+export type EngineId = 'managed' | 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode' | 'pi' | 'gemini'export interface Computer {id: string