Skip to content

Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.

Run agents on OpenCode V2 (#2)

paulo-oliveira-ifood64a162e7ce8f
diff --git a/src/core/engines/detect.ts b/src/core/engines/detect.ts
index 271f902..cf36959 100644
--- a/src/core/engines/detect.ts
+++ b/src/core/engines/detect.ts
@@ -5,6 +5,7 @@ import { L } from '../../shared/lang'
import type { EngineId, EngineStatus } from '../../shared/types'
import { userProvider } from './claude'
import { codexEnv, userCodexProvider } from './codex'
+import { opencodeMajor } from './opencode-v2'
function run(bin: string, args: string[], timeout = 15_000, env: NodeJS.ProcessEnv = process.env): Promise<{ code: number; stdout: string; stderr: string }> {
return new Promise((resolve) => {
@@ -118,7 +119,10 @@ function listedStatus(path: string, v: string, models: string[], login: string):
export async function detectOpenCode(): Promise<{ status: EngineStatus; models: string[] }> {
const path = await which('opencode')
if (!path) return { status: { installed: false, loggedIn: false }, models: [] }
- const [v, list] = await Promise.all([run(path, ['--version']), run(path, ['models'], 30_000)])
+ const v = await run(path, ['--version'])
+ // V2's commands talk to a background service and start it when it isn't running;
+ // --standalone (V2 only) answers from a private server that ends with the command.
+ const list = await run(path, opencodeMajor(version(v.stdout)) >= 2 ? ['models', '--standalone'] : ['models'], 30_000)
const models = list.stdout.split('\n').map((l) => l.trim()).filter((l) => /^[\w.-]+\/\S+$/.test(l))
return { status: listedStatus(path, v.stdout, models, 'opencode auth login'), models }
}
diff --git a/src/core/engines/opencode-v2.ts b/src/core/engines/opencode-v2.ts
new file mode 100644
index 0000000..7198e41
--- /dev/null
+++ b/src/core/engines/opencode-v2.ts
@@ -0,0 +1,158 @@
+import { execFile, spawn } from 'node:child_process'
+import { randomBytes, randomUUID } from 'node:crypto'
+import { existsSync, mkdirSync } from 'node:fs'
+import { join } from 'node:path'
+import { GATEWAY_NAME } from './claude'
+import { num, parseJson, runCli } from './cli'
+import { opencodeParser, userOpencodeProviders } from './opencode'
+import type { EngineEvent, Turn, Usage } from './types'
+import { L } from '../../shared/lang'
+
+// OpenCode 2 kept the `opencode` command and OPENCODE_CONFIG_CONTENT, but changed
+// the config to native V2 shapes (agents with system instead of the singular agent
+// with prompt, mcp.servers, update, snapshots) and moved to a client-server model.
+// The same OpenCode engine runs both: the installed version picks the way.
+export const opencodeMajor = (version: string | undefined): number => (version && parseInt(version, 10)) || 1
+
+export function opencodeV2Config(turn: Pick<Turn, 'system' | 'mcpUrl' | 'web'>, providers: Record<string, unknown> = {}): Record<string, unknown> {
+ return {
+ $schema: 'https://opencode.ai/config.json',
+ ...providers,
+ share: 'disabled',
+ update: 'disable',
+ snapshots: false,
+ mcp: turn.mcpUrl ? { servers: { [GATEWAY_NAME]: { type: 'remote', url: turn.mcpUrl, disabled: false } } } : {},
+ tools: { '*': false, [`${GATEWAY_NAME}_*`]: true, webfetch: !!turn.web, websearch: !!turn.web },
+ agents: { tucano: { system: turn.system } }
+ }
+}
+
+// The turn runs on a private server of its own (see runOpencodeV2), so it never starts or
+// fights over the person's background service. The app picks the session id, so the
+// session can be read and deleted even when the turn is stopped early.
+export function opencodeV2Args(turn: Pick<Turn, 'model' | 'images'>, session: string, server: string): string[] {
+ return ['run', '--server', server, '--format', 'json', '--agent', 'tucano', '-m', turn.model, '--session', session, ...(turn.images ?? []).filter((i) => existsSync(i.path)).flatMap((i) => ['-f', i.path])]
+}
+
+// V2 keeps its logins in its database, in the data dir, so the data dir stays the
+// person's (V1 linked auth.json instead). What would change the agent's behavior stays
+// out: the config dir (AGENTS.md, plugins, agents, MCP servers) and the state are the
+// app's own, and Claude Code's files and the project's config aren't read.
+export function opencodeV2Env(appDir: string): Record<string, string> {
+ const config = join(appDir, 'v2', 'config')
+ const state = join(appDir, 'v2', 'state')
+ for (const d of [config, state]) mkdirSync(join(d, 'opencode'), { recursive: true })
+ return {
+ XDG_CONFIG_HOME: config,
+ OPENCODE_CONFIG_DIR: join(config, 'opencode'),
+ XDG_STATE_HOME: state,
+ OPENCODE_DISABLE_CLAUDE_CODE: '1',
+ OPENCODE_DISABLE_CLAUDE_CODE_SKILLS: '1',
+ OPENCODE_DISABLE_PROJECT_CONFIG: '1',
+ OPENCODE_DISABLE_AUTOUPDATE: '1'
+ }
+}
+
+// What a session used, from `opencode session export`: V2's stream leaves out the
+// step_finish of the last step, so the stream alone undercounts the turn.
+export function sessionUsage(exported: string): Usage | undefined {
+ const info = parseJson(exported)?.['info'] as Record<string, unknown> | undefined
+ const t = info?.['tokens'] as Record<string, unknown> | undefined
+ if (!t) return undefined
+ const cache = (t['cache'] ?? {}) as Record<string, unknown>
+ const cost = num(info!['cost'])
+ return {
+ inputTokens: num(t['input']) + num(cache['read']) + num(cache['write']),
+ cacheReadTokens: num(cache['read']),
+ outputTokens: num(t['output']) + num(t['reasoning']),
+ ...(cost ? { apiCostUsd: cost } : {})
+ }
+}
+
+const cli = (bin: string, args: string[], env: NodeJS.ProcessEnv, cwd: string): Promise<string> =>
+ new Promise((resolve) => execFile(bin, args, { env, cwd, timeout: 20_000 }, (_err, stdout) => resolve(String(stdout))))
+
+// `opencode serve` on a free local port, with a password of the turn's own.
+async function startServer(bin: string, env: NodeJS.ProcessEnv, cwd: string): Promise<{ url?: string; stop: () => Promise<void> }> {
+ const child = spawn(bin, ['serve', '--hostname', '127.0.0.1', '--port', '0'], { env, cwd, stdio: ['ignore', 'pipe', 'pipe'] })
+ const exited = new Promise<void>((resolve) => child.on('close', () => resolve()))
+ // With the app's MCP connection open it can linger on SIGTERM; the turn waits for it to end.
+ const stop = async (): Promise<void> => {
+ if (child.exitCode !== null || child.signalCode !== null) return
+ child.kill('SIGTERM')
+ const kill = setTimeout(() => child.kill('SIGKILL'), 2_000)
+ await exited
+ clearTimeout(kill)
+ }
+ const url = await new Promise<string | undefined>((resolve) => {
+ let out = ''
+ const done = (u: string | undefined): void => {
+ clearTimeout(timer)
+ child.stdout.removeAllListeners('data')
+ child.stderr.removeAllListeners('data')
+ child.stdout.resume()
+ child.stderr.resume()
+ resolve(u)
+ }
+ const read = (chunk: Buffer): void => {
+ out = (out + chunk.toString()).slice(-4000)
+ const m = /listening on (http:\/\/127\.0\.0\.1:\d+)/.exec(out)
+ if (m) done(m[1])
+ }
+ const timer = setTimeout(() => done(undefined), 20_000)
+ child.stdout.on('data', read)
+ child.stderr.on('data', read)
+ child.on('close', () => done(undefined))
+ })
+ return { url, stop }
+}
+
+// Until the app's MCP server is connected (or failed): V2 doesn't wait for it before the
+// first step, so a turn started right away often doesn't see the app's tools. "Connected"
+// comes a moment before the tools reach the turn's list; against v2.2.0, 300 ms after it
+// was enough in every try, so the turn waits a little more than that.
+const MCP_SETTLE_MS = 500
+async function mcpReady(server: string, password: string, cwd: string, signal: AbortSignal): Promise<void> {
+ const auth = `Basic ${Buffer.from(`opencode:${password}`).toString('base64')}`
+ for (let i = 0; i < 70 && !signal.aborted; i++) {
+ try {
+ const res = await fetch(`${server}/api/mcp?directory=${encodeURIComponent(cwd)}`, { headers: { authorization: auth }, signal })
+ const body = (await res.json()) as { data?: { name?: string; status?: { status?: string } }[] }
+ const status = body.data?.find((s) => s.name === GATEWAY_NAME)?.status?.status
+ if (status === 'connected') return void (await new Promise((r) => setTimeout(r, MCP_SETTLE_MS)))
+ if (status === 'failed') return
+ } catch {
+ // not answering yet
+ }
+ await new Promise((r) => setTimeout(r, 150))
+ }
+}
+
+export async function* runOpencodeV2(path: string, turn: Turn, appDir: string, shellEnv: NodeJS.ProcessEnv): AsyncIterable<EngineEvent> {
+ const password = randomBytes(24).toString('hex')
+ const env = { ...process.env, ...shellEnv, ...opencodeV2Env(appDir), PWD: turn.cwd, OPENCODE_SERVER_PASSWORD: password, OPENCODE_CONFIG_CONTENT: JSON.stringify(opencodeV2Config(turn, userOpencodeProviders(undefined, true))) }
+ const session = `ses_tucano${randomUUID().replaceAll('-', '')}`
+ const server = await startServer(path, env, turn.cwd)
+ try {
+ if (!server.url) {
+ yield { type: 'error', message: L('O OpenCode não abriu o servidor dele para a resposta.', "OpenCode didn't start its server for the reply.") }
+ return
+ }
+ if (turn.mcpUrl) await mcpReady(server.url, password, turn.cwd, turn.signal)
+ if (turn.signal.aborted) return
+ let done: Extract<EngineEvent, { type: 'done' }> | undefined
+ for await (const ev of runCli({ bin: path, args: opencodeV2Args(turn, session, server.url), stdin: turn.prompt, cwd: turn.cwd, signal: turn.signal, parser: opencodeParser(), env })) {
+ if (ev.type === 'done') done = ev
+ // Stopped, V2 reports the dropped connection to its server: not the turn's error.
+ else if (!(ev.type === 'error' && turn.signal.aborted)) yield ev
+ }
+ const usage = sessionUsage(await cli(path, ['session', 'export', session, '--server', server.url], env, turn.cwd))
+ if (done) yield usage ? { ...done, usage } : done
+ // Stopped mid-turn: what it used so far still counts against the limit.
+ else if (usage) yield { type: 'progress', tokens: usage.inputTokens + usage.outputTokens, cacheRead: usage.cacheReadTokens }
+ } finally {
+ // The turn is the app's, not the person's: it leaves nothing in their OpenCode history.
+ if (server.url) await cli(path, ['session', 'delete', session, '--server', server.url], env, turn.cwd)
+ await server.stop()
+ }
+}
diff --git a/src/core/engines/opencode.ts b/src/core/engines/opencode.ts
index 9e8184d..641b903 100644
--- a/src/core/engines/opencode.ts
+++ b/src/core/engines/opencode.ts
@@ -3,6 +3,7 @@ import { homedir } from 'node:os'
import { join } from 'node:path'
import { GATEWAY_NAME } from './claude'
import { lastLines, num, parseJson, runCli, type Parser } from './cli'
+import { opencodeMajor, runOpencodeV2 } from './opencode-v2'
import type { Engine, EngineEvent, Turn } from './types'
import { L } from '../../shared/lang'
@@ -22,13 +23,16 @@ export function opencodeHome(appDir: string, userData = join(process.env['XDG_DA
}
// The providers block of the user's opencode.json(c): where their models come
-// from. The rest (agents, plugins, MCP servers, instructions) stays out.
-export function userOpencodeProviders(dir = join(process.env['XDG_CONFIG_HOME'] || join(homedir(), '.config'), 'opencode')): Record<string, unknown> {
+// from. The rest (agents, plugins, MCP servers, instructions) stays out. V2 also
+// reads its own shape: `providers`, and `policies` on which providers to use.
+export function userOpencodeProviders(dir = join(process.env['XDG_CONFIG_HOME'] || join(homedir(), '.config'), 'opencode'), v2 = false): Record<string, unknown> {
for (const name of ['opencode.jsonc', 'opencode.json']) {
try {
const c = JSON.parse(stripJsonComments(readFileSync(join(dir, name), 'utf8'))) as Record<string, unknown>
const out: Record<string, unknown> = {}
- for (const k of ['provider', 'enabled_providers', 'disabled_providers']) if (c[k] !== undefined) out[k] = c[k]
+ for (const k of ['provider', 'enabled_providers', 'disabled_providers', ...(v2 ? ['providers'] : [])]) if (c[k] !== undefined) out[k] = c[k]
+ const policies = v2 && Array.isArray(c['policies']) ? c['policies'].filter((p) => (p as Record<string, unknown> | null)?.['action'] === 'provider.use') : []
+ if (policies.length) out['policies'] = policies
return out
} catch {
// not there, or not readable: next
@@ -86,6 +90,7 @@ export function opencodeParser(): Parser {
let input = 0
let output = 0
let cacheRead = 0
+ let cost = 0
let failed = false
return {
@@ -108,6 +113,7 @@ export function opencodeParser(): Parser {
cacheRead += num(cache['read'])
input += num(t['input']) + num(cache['read']) + num(cache['write'])
output += num(t['output']) + num(t['reasoning'])
+ cost += num(part['cost'])
out.push({ type: 'progress', tokens: input + output, cacheRead })
} else if (ev['type'] === 'error' && !failed) {
failed = true
@@ -119,15 +125,16 @@ export function opencodeParser(): Parser {
},
end(code, stderr) {
if (failed) return []
- if (code === 0) return [{ type: 'done', text, usage: { inputTokens: input, cacheReadTokens: cacheRead, outputTokens: output } }]
+ if (code === 0) return [{ type: 'done', text, usage: { inputTokens: input, cacheReadTokens: cacheRead, outputTokens: output, ...(cost ? { apiCostUsd: cost } : {}) } }]
const detail = lastLines(stderr)
return [{ type: 'error', message: L(`O OpenCode saiu sem resposta (código ${code ?? '?'}).`, `OpenCode exited without a reply (code ${code ?? '?'}).`) + (detail ? `\n${detail}` : '') }]
}
}
}
-// The model is "<provider>/<model>", as `opencode models` lists it.
-export function opencodeEngine(bin: () => string | undefined, appDir: string, shellEnv: () => Promise<NodeJS.ProcessEnv> = async () => ({})): Engine {
+// The model is "<provider>/<model>", as `opencode models` lists it. The installed
+// version picks V1's way or V2's (see opencode-v2.ts), so an upgrade keeps the agents running.
+export function opencodeEngine(bin: () => string | undefined, appDir: string, shellEnv: () => Promise<NodeJS.ProcessEnv> = async () => ({}), version: () => string | undefined = () => undefined): Engine {
return {
id: 'opencode',
async *run(turn) {
@@ -137,6 +144,10 @@ export function opencodeEngine(bin: () => string | undefined, appDir: string, sh
return
}
// Provider keys may live in the user's shell, which an app opened from Finder doesn't get.
+ if (opencodeMajor(version()) >= 2) {
+ yield* runOpencodeV2(path, turn, appDir, await shellEnv())
+ return
+ }
const env = { ...process.env, ...(await shellEnv()), ...opencodeHome(appDir), OPENCODE_CONFIG_CONTENT: JSON.stringify(opencodeConfig(turn, userOpencodeProviders())), OPENCODE_DISABLE_CLAUDE_CODE: '1', OPENCODE_DISABLE_AUTOUPDATE: '1' }
yield* runCli({ bin: path, args: opencodeArgs(turn), stdin: turn.prompt, cwd: turn.cwd, signal: turn.signal, parser: opencodeParser(), env })
}
diff --git a/src/core/index.ts b/src/core/index.ts
index d8402df..4d4d070 100644
--- a/src/core/index.ts
+++ b/src/core/index.ts
@@ -103,7 +103,7 @@ const engineImpls: Record<EngineId, Engine> = fake
: {
claude: claudeEngine(() => engines.claude.path, async () => quietClaude(userProvider())),
codex: codexEngine(() => engines.codex.path, codexHome, loginEnv, async () => quietCodex(userCodexProvider())),
- opencode: opencodeEngine(() => engines.opencode.path, join(dataDir, 'opencode-home'), loginEnv),
+ opencode: opencodeEngine(() => engines.opencode.path, join(dataDir, 'opencode-home'), loginEnv, () => engines.opencode.version),
pi: piEngine(() => engines.pi.path, join(dataDir, 'pi'), loginEnv)
}
diff --git a/src/renderer/src/components/Harness.tsx b/src/renderer/src/components/Harness.tsx
index 10dd97e..3500f6f 100644
--- a/src/renderer/src/components/Harness.tsx
+++ b/src/renderer/src/components/Harness.tsx
@@ -8,6 +8,7 @@ import {
ENGINES,
ENGINE_IDS,
MODELS,
+ startsPicked,
customModel,
engineModels,
harnessMcps,
@@ -149,8 +150,8 @@ const ROUTE = (): Record<NonNullable<EngineStatus['route']>, { label: string; to
export function HarnessList(): ReactNode {
const engines = useStore((s) => s.settings.engines)
const chosen = useStore((s) => s.settings.harnesses)
- // Unpicked: all that can run. Picking one off keeps the rest as they are.
- const picked = (e: EngineId): boolean => !engines[e].soon && (chosen ? chosen.includes(e) : true)
+ // Unpicked: the ones ready to run. Picking one off keeps the rest as they are.
+ const picked = (e: EngineId): boolean => (chosen ? chosen.includes(e) : startsPicked(engines[e]))
const toggle = (e: EngineId): void => {
const now = ENGINE_IDS.filter(picked)
updateSettings({ harnesses: now.includes(e) ? now.filter((x) => x !== e) : [...now, e] })
diff --git a/src/shared/types.ts b/src/shared/types.ts
index aabbec2..ec72745 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -272,6 +272,10 @@ export const ENGINES: Record<EngineId, { label: string; cli: string; login: stri
}
export const ENGINE_IDS = Object.keys(ENGINES) as EngineId[]
+// A harness starts picked only when it can actually run: one not installed or not
+// signed in yet starts off.
+export const startsPicked = (st: EngineStatus): boolean => !st.soon && st.loggedIn
+
// Hints and labels read the language when shown (getters), so a list made once still switches.
const model = (id: string, engine: EngineId, label: string, pt: string, en: string): Model => ({
id,
diff --git a/test/harness.test.ts b/test/harness.test.ts
index 014caa5..2a09f69 100644
--- a/test/harness.test.ts
+++ b/test/harness.test.ts
@@ -1,12 +1,21 @@
import { describe, expect, it } from 'vitest'
import { parsePiModels } from '../src/core/engines/detect'
import { listModels, quietClaude, quietCodex, withChoice } from '../src/core/harness'
+import { startsPicked } from '../src/shared/types'
import type { EngineId, EngineStatus } from '../src/shared/types'
const ready: EngineStatus = { installed: true, loggedIn: true, route: 'plan' }
const engines: Record<EngineId, EngineStatus> = { claude: ready, codex: ready, opencode: { ...ready, route: 'providers' }, pi: { ...ready, route: 'providers' } }
describe('harnesses', () => {
+ it('defaults the pick to the harnesses that can actually run', () => {
+ expect(startsPicked(ready)).toBe(true)
+ expect(startsPicked({ installed: false, loggedIn: false })).toBe(false)
+ // installed, but the person has not logged in yet
+ expect(startsPicked({ installed: true, loggedIn: false })).toBe(false)
+ expect(startsPicked({ ...ready, soon: true })).toBe(false)
+ })
+
it('runs every ready harness the app supports when none was picked', () => {
const out = withChoice(engines, undefined)
expect(out.claude.loggedIn).toBe(true)
diff --git a/test/opencode-v2.test.ts b/test/opencode-v2.test.ts
new file mode 100644
index 0000000..d4e6ca6
--- /dev/null
+++ b/test/opencode-v2.test.ts
@@ -0,0 +1,123 @@
+import { chmodSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { describe, expect, it } from 'vitest'
+import { opencodeEngine } from '../src/core/engines/opencode'
+import { opencodeMajor, opencodeV2Args, opencodeV2Config, opencodeV2Env, sessionUsage } from '../src/core/engines/opencode-v2'
+import type { EngineEvent, Turn } from '../src/core/engines/types'
+
+// Trimmed from a real OpenCode v2.2.0 run: the stream has no step_finish for the last step,
+// and `session export` has the session's totals.
+const STEP = '{"type":"step_start","sessionID":"ses_x","part":{"type":"step-start"}}'
+const TEXT = '{"type":"text","sessionID":"ses_x","part":{"type":"text","text":"oi"}}'
+const EXPORT = JSON.stringify({ info: { id: 'ses_x', cost: 0, tokens: { input: 403, output: 5, reasoning: 0, cache: { read: 0, write: 0 } } }, messages: [] })
+
+describe('opencode v2', () => {
+ it('emits the native V2 config', () => {
+ const c = opencodeV2Config({ system: 'Você é a Iris.', mcpUrl: 'http://127.0.0.1:1/mcp/x', web: false }, { provider: { acme: {} } })
+ expect(c['tools']).toEqual({ '*': false, 'tucano_*': true, webfetch: false, websearch: false })
+ expect(c['mcp']).toEqual({ servers: { tucano: { type: 'remote', url: 'http://127.0.0.1:1/mcp/x', disabled: false } } })
+ expect(c['agents']).toEqual({ tucano: { system: 'Você é a Iris.' } })
+ expect(c['update']).toBe('disable')
+ expect(c['snapshots']).toBe(false)
+ expect(c['share']).toBe('disabled')
+ expect(c['provider']).toEqual({ acme: {} })
+ })
+
+ it('omits the mcp block when there is no gateway', () => {
+ const c = opencodeV2Config({ system: 's', web: true })
+ expect(c['mcp']).toEqual({})
+ expect(c['tools']).toEqual({ '*': false, 'tucano_*': true, webfetch: true, websearch: true })
+ })
+
+ it("runs on the turn's own server, in a session the app names", () => {
+ expect(opencodeV2Args({ model: 'acme/gpt-9' }, 'ses_tucano1', 'http://127.0.0.1:5')).toEqual(['run', '--server', 'http://127.0.0.1:5', '--format', 'json', '--agent', 'tucano', '-m', 'acme/gpt-9', '--session', 'ses_tucano1'])
+ })
+
+ it("keeps the person's data dir, where V2 keeps the logins, and isolates the rest", () => {
+ const dir = mkdtempSync(join(tmpdir(), 'oc2-'))
+ const env = opencodeV2Env(dir)
+ expect(env['XDG_DATA_HOME']).toBeUndefined()
+ expect(env['XDG_CONFIG_HOME']).toBe(join(dir, 'v2', 'config'))
+ expect(env['OPENCODE_CONFIG_DIR']).toBe(join(dir, 'v2', 'config', 'opencode'))
+ expect(env['XDG_STATE_HOME']).toBe(join(dir, 'v2', 'state'))
+ expect(env).toMatchObject({ OPENCODE_DISABLE_CLAUDE_CODE: '1', OPENCODE_DISABLE_CLAUDE_CODE_SKILLS: '1', OPENCODE_DISABLE_PROJECT_CONFIG: '1' })
+ })
+
+ it("reads the session's usage from its export", () => {
+ expect(sessionUsage(EXPORT)).toEqual({ inputTokens: 403, cacheReadTokens: 0, outputTokens: 5 })
+ const cached = JSON.stringify({ info: { cost: 0.01, tokens: { input: 100, output: 20, reasoning: 5, cache: { read: 50, write: 10 } } } })
+ expect(sessionUsage(cached)).toEqual({ inputTokens: 160, cacheReadTokens: 50, outputTokens: 25, apiCostUsd: 0.01 })
+ expect(sessionUsage('Session not found')).toBeUndefined()
+ })
+
+ it('reads the major version, V1 when unknown', () => {
+ expect(opencodeMajor('2.2.0')).toBe(2)
+ expect(opencodeMajor('1.15.10')).toBe(1)
+ expect(opencodeMajor(undefined)).toBe(1)
+ expect(opencodeMajor('tomorrow')).toBe(1)
+ })
+})
+
+// A stand-in `opencode` that logs every call and answers like v2.2.0 does.
+function fakeOpencode(opts: { hang?: boolean } = {}): { bin: string; calls: () => string[] } {
+ const dir = mkdtempSync(join(tmpdir(), 'oc2-bin-'))
+ const log = join(dir, 'calls.log')
+ const bin = join(dir, 'opencode')
+ writeFileSync(
+ bin,
+ `#!/bin/sh
+echo "$* | data=$XDG_DATA_HOME | claude=$OPENCODE_DISABLE_CLAUDE_CODE" >> "${log}"
+STOPPED='{"type":"error","error":{"message":"Transport: ECONNRESET"}}'
+case "$1 $2" in
+ "serve --hostname") echo "server listening on http://127.0.0.1:9"; exec sleep 30 ;;
+ "session export") echo '${EXPORT}' ;;
+ "session delete") echo "Session $3 deleted" ;;
+ *) cat > /dev/null; echo '${STEP}'; echo '${TEXT}'; ${opts.hang ? `trap 'echo "$STOPPED"; kill $!; exit 1' TERM; sleep 30 >/dev/null 2>&1 & wait` : 'true'} ;;
+esac
+`
+ )
+ chmodSync(bin, 0o755)
+ return { bin, calls: () => readFileSync(log, 'utf8').trim().split('\n') }
+}
+
+const turn = (signal = new AbortController().signal): Turn => ({ model: 'openai/gpt-5.6-luna', effort: 'low', system: 's', prompt: 'Diga só: oi', cwd: tmpdir(), signal })
+const collect = async (it: AsyncIterable<EngineEvent>): Promise<EngineEvent[]> => {
+ const out: EngineEvent[] = []
+ for await (const ev of it) out.push(ev)
+ return out
+}
+
+describe('the OpenCode engine on V2', () => {
+ it("takes the turn's usage from the export and deletes the session", async () => {
+ const oc = fakeOpencode()
+ const events = await collect(opencodeEngine(() => oc.bin, mkdtempSync(join(tmpdir(), 'oc2-app-')), async () => ({}), () => '2.2.0').run(turn()))
+ expect(events.at(-1)).toEqual({ type: 'done', text: 'oi', usage: { inputTokens: 403, cacheReadTokens: 0, outputTokens: 5 } })
+ const [serve, run, exported, deleted] = oc.calls()
+ const session = /--session (\S+)/.exec(run!)![1]!
+ expect(serve).toMatch(/^serve --hostname 127\.0\.0\.1 --port 0/)
+ expect(run).toContain('run --server http://127.0.0.1:9')
+ expect(run).toContain('claude=1')
+ expect(exported).toMatch(new RegExp(`^session export ${session} --server http://127.0.0.1:9`))
+ expect(deleted).toMatch(new RegExp(`^session delete ${session} --server http://127.0.0.1:9`))
+ })
+
+ it('counts what a stopped turn used and still deletes its session', async () => {
+ const oc = fakeOpencode({ hang: true })
+ const stop = new AbortController()
+ setTimeout(() => stop.abort(), 500)
+ const events = await collect(opencodeEngine(() => oc.bin, mkdtempSync(join(tmpdir(), 'oc2-app-')), async () => ({}), () => '2.2.0').run(turn(stop.signal)))
+ expect(events.find((e) => e.type === 'done' || e.type === 'error')).toBeUndefined()
+ expect(events.at(-1)).toEqual({ type: 'progress', tokens: 408, cacheRead: 0 })
+ expect(oc.calls().map((c) => c.split(' ').slice(0, 2).join(' '))).toEqual(['serve --hostname', 'run --server', 'session export', 'session delete'])
+ })
+
+ it('keeps running V1 the way it always did', async () => {
+ const oc = fakeOpencode()
+ await collect(opencodeEngine(() => oc.bin, mkdtempSync(join(tmpdir(), 'oc2-app-')), async () => ({}), () => '1.15.10').run(turn()))
+ const calls = oc.calls()
+ expect(calls).toHaveLength(1)
+ expect(calls[0]).toContain('run --pure')
+ expect(calls[0]).not.toContain('--session')
+ })
+})
diff --git a/test/opencode.test.ts b/test/opencode.test.ts
index 4ca9d7c..898f6b8 100644
--- a/test/opencode.test.ts
+++ b/test/opencode.test.ts
@@ -36,6 +36,20 @@ describe('opencode', () => {
expect(opencodeArgs({ model: 'openai/gpt-5.6-luna' })).toEqual(['run', '--pure', '--format', 'json', '--agent', 'tucano', '-m', 'openai/gpt-5.6-luna'])
})
+ it('accumulates the cost V2 reports per step', () => {
+ const p = opencodeParser()
+ const withCost = '{"type":"step_finish","part":{"type":"step-finish","reason":"tool-calls","cost":0.0005,"tokens":{"total":222,"input":204,"output":18,"reasoning":0,"cache":{"write":0,"read":0}}}}'
+ p.line(withCost)
+ const [done] = p.end(0, '')
+ expect(done).toMatchObject({ usage: { apiCostUsd: 0.0005 } })
+ })
+
+ it('still ends done when V2 emits no step_finish at all', () => {
+ const p = opencodeParser()
+ p.line(TEXT)
+ expect(p.end(0, '')).toEqual([{ type: 'done', text: 'São 13:37 no Tucano.', usage: { inputTokens: 0, cacheReadTokens: 0, outputTokens: 0 } }])
+ })
+
it("takes only the providers from the user's opencode.jsonc", () => {
const dir = mkdtempSync(join(tmpdir(), 'oc-'))
mkdirSync(dir, { recursive: true })
@@ -43,4 +57,13 @@ describe('opencode', () => {
expect(userOpencodeProviders(dir)).toEqual({ provider: { acme: { options: { baseURL: 'https://llm.acme.com/v1' } } } })
expect(stripJsonComments('{"url": "http://x//y" /* c */}')).toBe('{"url": "http://x//y" }')
})
+
+ it("takes V2's providers shape too, for V2 only, and only the policies about providers", () => {
+ const dir = mkdtempSync(join(tmpdir(), 'oc-'))
+ const providers = { empresa: { package: 'aisdk:@ai-sdk/openai-compatible', settings: { baseURL: 'https://llm.acme.com/v1' } } }
+ const policies = [{ action: 'provider.use', resource: 'empresa', effect: 'allow' }, { action: 'tool.use', resource: 'shell', effect: 'allow' }]
+ writeFileSync(join(dir, 'opencode.json'), JSON.stringify({ provider: { acme: {} }, providers, policies, mcp: { servers: {} } }))
+ expect(userOpencodeProviders(dir, true)).toEqual({ provider: { acme: {} }, providers, policies: [policies[0]] })
+ expect(userOpencodeProviders(dir)).toEqual({ provider: { acme: {} } })
+ })
})