The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(cli): OpenCode 2.0 — switch models without -m, and continue the same session
Timc08ce932fb46
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex 0e838b386..71ecfc9c7 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -20,6 +20,7 @@ import * as projectFolder from './lib/projectFolder.js'import * as claudeTrust from './lib/claudeTrust.js'import * as projectPreview from './lib/projectPreview.js'import * as storeCatalog from './dsh/catalog.js'+import * as opencodeVersion from './engines/opencode/version.js'import { randomUUID } from 'node:crypto'import { fakeGridAnswers, installFakeGrid, type FakeGrid } from './lib/__fixtures__/fakeGrid.js'import { clearGridMcpUrlCache } from './lib/gridMcpUrl.js'@@ -2559,6 +2560,8 @@ describe('agent_create with a prompt, a name and a named agent', () => {})it('passes the named agent through for opencode, and null when none was given', async () => {+ // v1 — pinned, so the answer does not depend on the OpenCode installed where the suite runs.+ vi.spyOn(opencodeVersion, 'opencodeMajorVersion').mockReturnValue(1)const { seen, reply } = await create({ agent: 'harness-compute', name: 'Local model' })expect(seen).toEqual([expect.objectContaining({ engine: 'opencode', agent: 'harness-compute', name: 'Local model', prompt: null })])expect(reply).toMatchObject({ agent: expect.objectContaining({ id: 'named-1' }) })@@ -2566,6 +2569,13 @@ describe('agent_create with a prompt, a name and a named agent', () => {expect((await create({ agent: null })).seen).toEqual([expect.objectContaining({ agent: null })])})+ it('refuses a named agent for opencode v2, whose TUI exits 1 on --agent, before any pane exists', async () => {+ vi.spyOn(opencodeVersion, 'opencodeMajorVersion').mockReturnValue(2)+ const { seen, reply } = await create({ agent: 'harness-compute' })+ expect(reply).toMatchObject({ error: 'AGENT_UNSUPPORTED', detail: expect.stringContaining('opencode') })+ expect(seen).toHaveLength(0)+ })+it('refuses a named agent for an engine with no documented mechanism, naming the engine, before any pane exists', async () => {for (const engine of ['claude', 'codex', 'cursor']) {const { seen, reply } = await create({ engine, agent: 'harness-compute' })diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex c64db04a5..2a9aeaa28 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -48,6 +48,7 @@ import type { GridAttachResult } from './lib/gridAttach.js'import { parseNewAgentModel, resolveNewAgentModel } from './lib/newAgentModel.js'import { deriveHarnessGridName } from './lib/gridDerive.js'import { AGENT_NAME_RE, FirstPromptUnsupportedError, MAX_FIRST_PROMPT_CHARS, NamedAgentUnsupportedError, permissionModeApproves, permissionModeFlags, supportsFirstPrompt, supportsNamedAgent } from './lib/engineLaunch.js'+import { opencodeMajorVersion } from './engines/opencode/version.js'import { readAccountUsage, type AccountUsageReading } from './lib/accountUsage.js'import { probeEngines } from './lib/engineProbe.js'import { readMachineResources } from './lib/machineResources.js'@@ -2786,7 +2787,8 @@ export class BackendSocket {if (typeof payload.agent !== 'string' || !AGENT_NAME_RE.test(payload.agent)) {reply(type, requestId, { error: 'INVALID_AGENT', detail: 'agent must be 1-64 letters, digits, `-` or `_`' }); return}- if (!supportsNamedAgent(engine)) {+ // OpenCode v2 counts as no way: its TUI exits 1 on `--agent` (engineLaunch.ts).+ if (!supportsNamedAgent(engine, engine === 'opencode' ? opencodeMajorVersion() : null)) {reply(type, requestId, { error: 'AGENT_UNSUPPORTED', detail: new NamedAgentUnsupportedError(engine).message }); return}agent = payload.agentdiff --git a/cli/src/cli.ts b/cli/src/cli.tsindex bc2c8cb81..0e988859d 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -126,7 +126,7 @@ import { ensureBuiltinPair } from './dsh/builtins.js'import { DEFAULT_AUTONOMY, isAutonomy, type Autonomy } from './pair/floor.js'import { createHash, randomUUID } from 'node:crypto'import { engineInstallRecipe } from './lib/engineInstall.js'-import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell, dropPermissionFlagIfUnsupported, namedAgentArgs, permissionModeApproves, permissionModeFlags, refusePermissionFlagIfUnsupported, supportsFirstPrompt } from './lib/engineLaunch.js'+import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell, dropPermissionFlagIfUnsupported, namedAgentArgs, permissionModeApproves, permissionModeFlags, refusePermissionFlagIfUnsupported, supportsFirstPrompt, supportsNamedAgent } from './lib/engineLaunch.js'import { workspaceMissing } from './lib/workspaceCheck.js'import { buildGridEngineLaunch, describeGridLaunch, gridConflictingEnvToClear, gridEnvVarNames, isApiLaunch, type GridLaunchMachine, type GridWebSearchStatus } from './lib/gridLaunch.js'import { HERMES_SYSTEM_MANAGED_DIR } from './lib/gridWebMcp.js'@@ -262,7 +262,8 @@ import { CursorSubagentManager } from './engines/cursor/subagent.js'import { CursorTaskHookQueue } from './engines/cursor/taskHookQueue.js'import { loadCursorPendingTasks, removeCursorPendingTasks } from './engines/cursor/pendingTasks.js'import { OpencodeReader, readOpencodeMessages } from './engines/opencode/reader.js'-import { opencodeModelFromArgv, setOpencodeSessionModel } from './engines/opencode/sessionModel.js'+import { applyOpencodeSessionModel, parseOpencodeModelId } from './engines/opencode/sessionModel.js'+import { isOpencodeV2, opencodeMajorVersion } from './engines/opencode/version.js'import { lastOpencodeTurnText, opencodeMessagesToEvents } from './engines/opencode/normalizer.js'import { KiloReader, readKiloMessages } from './engines/kilo/reader.js'import { kiloMessagesToEvents, lastKiloTurnText } from './engines/kilo/normalizer.js'@@ -5559,8 +5560,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {* machine: a `build()` that stats the filesystem answers differently on two of them, and its spec* would follow. What is DONE with the fact lives in the builder, so create, retarget and restore* cannot disagree about it.+ *+ * The other is which OpenCode is installed: v2's TUI exits 1 on v1's `-m` / `--agent`. Cached per+ * installed file (`engines/opencode/version.ts`), so this costs a `stat` after the first read.*/- const gridLaunchMachine = (): GridLaunchMachine => ({ hermesSystemManaged: existsSync(HERMES_SYSTEM_MANAGED_DIR) })+ const gridLaunchMachine = (): GridLaunchMachine => ({+ hermesSystemManaged: existsSync(HERMES_SYSTEM_MANAGED_DIR),+ opencodeMajor: opencodeMajorVersion(),+ })/*** What a relaunch of `session` must be given, beyond the engine's argv, to come back where it was —@@ -6248,8 +6255,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {const clearEnv = [...(gridLaunch ? gridConflictingEnvToClear(gridLaunch) : []), ...harnessEnvToClear(dshEnv)]// The named agent takes the same argv slot on every relaunch (`buildLaunchOverrides` appends it// from the row's `agent`, after the grid's and the DSH's argv, exactly as here). The engine was- // checked for a contract at the wire (AGENT_UNSUPPORTED), so this cannot throw.- const extraArgs = [...(gridLaunch?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent) : []), ...resumeArgs]+ // checked for a contract at the wire (AGENT_UNSUPPORTED, opencode v2 included), so this cannot throw.+ const extraArgs = [...(gridLaunch?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent, opencodeMajorVersion()) : []), ...resumeArgs]// The first prompt is a launch option only — never part of `extraArgs`, which the registry row// carries into a relaunch (engineLaunch.ts, `firstPrompt`).// Stopped mid-turn, the resumed conversation is told to carry on — by an engine that can open@@ -6377,7 +6384,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {dshLabel = installed.manifest.name}const installIfMissing = enginePathOverride(engine) ? undefined : engineInstallRecipe(engine)- const extraArgs = [...dshArgs, ...(source.agent ? namedAgentArgs(engine, source.agent) : [])]+ // Same guard as a relaunch (`buildLaunchOverrides`): an opencode agent recorded on v1 forks on v2+ // as a general session rather than handing the v2 TUI an `--agent` it exits on.+ const forkMajor = opencodeMajorVersion()+ const extraArgs = [...dshArgs, ...(source.agent && supportsNamedAgent(engine, forkMajor) ? namedAgentArgs(engine, source.agent, forkMajor) : [])]const firstPrompt = plan.level === 'native' ? (prompt ?? undefined) : plan.firstPromptconst launchOptions = {clearEnv: harnessEnvToClear(dshEnv),@@ -6597,10 +6607,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {// the failure this handler exists to refuse — so it is refused here, before the pane is touched.// Only when the launch will name a model: a grid launch always does; a move home does only when// the remembered model carries its provider (`subscriptionModel.ts`), and otherwise the engine- // decides, as it always did.+ // decides, as it always did. v2 switches the model through OpenCode's own API instead and needs no+ // sqlite3 (`applyOpencodeSessionModel`).const rewritesOpencodeSession = session.engine === 'opencode' && !!session.sessionId&& (!!grid || !!remembered?.includes('/'))- if (rewritesOpencodeSession && !binaryOnPath('sqlite3')) {+ const opencodeMajor = session.engine === 'opencode' ? opencodeMajorVersion() : null+ if (rewritesOpencodeSession && !isOpencodeV2(opencodeMajor) && !binaryOnPath('sqlite3')) {return {ok: false,error: 'OPENCODE_SQLITE_MISSING',@@ -6666,11 +6678,22 @@ async function runForeground(session: AuthSession | null): Promise<void> {// already on it, with nothing typed into the pane. Before the live process is touched, so a// write that fails refuses the move with that process still on its old target. A session with// no user message yet has nothing to restore from and takes `-m` on launch, so it is skipped.+ //+ // OpenCode 2.0 has no `-m` on its TUI, keeps sessions in tables the SQL above never reads (it+ // used to answer SESSION_NOT_FOUND there, read as success, and then respawn with `-m` into+ // `Unrecognized flag: -m` and a dead pane), and ships its own writer: the service's+ // `session.switchModel`. `applyOpencodeSessionModel` picks per version, and on v2 every+ // failure refuses the move — with the live process still untouched.if (rewritesOpencodeSession) {- const model = opencodeModelFromArgv(built.overrides.extraArgs)+ const model = built.overrides.sessionModel ? parseOpencodeModelId(built.overrides.sessionModel) : nullif (model) {- const written = await setOpencodeSessionModel(OPENCODE_DB, session.sessionId, model)- if (!written.ok && written.code !== 'OPENCODE_SESSION_NOT_FOUND') {+ const written = await applyOpencodeSessionModel({+ opencodeMajor, dbPath: OPENCODE_DB, sessionId: session.sessionId, model, cwd: session.cwd ?? undefined,+ // (A model of opencode's own is looked for in its catalogue; a grid's provider lives in+ // the pane's own config, which the service never reads.)+ checkCatalog: !grid,+ })+ if (!written.ok) {console.warn(`[grid] retarget ${sid(session.agentId)} refused · ${written.code} · ${written.detail}`)return { ok: false, error: written.code, detail: written.detail }}diff --git a/cli/src/engines/opencode/sessionModel.spec.ts b/cli/src/engines/opencode/sessionModel.spec.tsindex 9aa168e05..3705af8a7 100644--- a/cli/src/engines/opencode/sessionModel.spec.ts+++ b/cli/src/engines/opencode/sessionModel.spec.ts@@ -3,7 +3,14 @@ import { execFileSync } from 'child_process'import { mkdtempSync, rmSync } from 'fs'import { tmpdir } from 'os'import { join } from 'path'-import { opencodeModelFromArgv, setOpencodeSessionModel } from './sessionModel.js'+import {+ applyOpencodeSessionModel,+ opencodeModelFromArgv,+ parseOpencodeModelId,+ setOpencodeSessionModel,+ switchOpencodeSessionModel,+ type OpencodeApiRun,+} from './sessionModel.js'const hasSqlite = (() => {try { execFileSync('sqlite3', ['-version'], { stdio: 'ignore' }); return true } catch { return false }@@ -179,3 +186,186 @@ describe('opencodeModelFromArgv', () => {expect(opencodeModelFromArgv(['-m', 'x/'])).toBeNull()})})++describe('parseOpencodeModelId', () => {+ it('splits at the first slash, the way opencode does', () => {+ expect(parseOpencodeModelId('vibe/minimax/minimax-m3')).toEqual({ providerID: 'vibe', modelID: 'minimax/minimax-m3' })+ expect(parseOpencodeModelId('bare')).toBeNull()+ expect(parseOpencodeModelId('/x')).toBeNull()+ })+})++/** A stand-in for `opencode api …`, answering the way 2.0.18 does. */+function fakeApi(answers: { switch?: () => string; get?: () => string; list?: () => string } = {}) {+ const calls: string[][] = []+ const run: OpencodeApiRun = async (args) => {+ calls.push(args)+ if (args[1] === 'model.list') {+ return { stdout: answers.list ? answers.list() : JSON.stringify({ data: [{ id: NEW.modelID, providerID: NEW.providerID }, { id: OLD.modelID, providerID: OLD.providerID }] }) }+ }+ if (args[1] === 'session.switchModel') return { stdout: answers.switch ? answers.switch() : '' }+ if (args[1] === 'session.get') {+ return { stdout: answers.get ? answers.get() : JSON.stringify({ data: { id: SID, model: { id: NEW.modelID, providerID: NEW.providerID, variant: 'default' } } }) }+ }+ throw new Error(`unexpected ${args.join(' ')}`)+ }+ return { run, calls }+}+/** What execFile rejects with when `opencode api` exits 1. */+function exitError(stdout: string, stderr = ''): Error {+ return Object.assign(new Error('Command failed'), { code: 1, stdout, stderr })+}++describe('switchOpencodeSessionModel (opencode v2, `opencode api`)', () => {+ it('switches through the running service, then reads the session back to prove it', async () => {+ const { run, calls } = fakeApi()+ await expect(switchOpencodeSessionModel(SID, NEW, { run })).resolves.toEqual({ ok: true })+ expect(calls).toEqual([+ ['api', 'session.switchModel', '--param', `sessionID=${SID}`, '-d', JSON.stringify({ model: { id: NEW.modelID, providerID: NEW.providerID } })],+ ['api', 'session.get', '--param', `sessionID=${SID}`],+ ])+ })++ it('refuses a session the service does not know, with the code the retarget reports', async () => {+ // 2.0.18 prints the body on stdout and the status on stderr, and exits 1.+ const { run } = fakeApi({ switch: () => { throw exitError('{"_tag":"SessionNotFoundError","message":"Session not found: ses_testABC123"}\n', 'HTTP 404 Not Found\n') } })+ await expect(switchOpencodeSessionModel(SID, NEW, { run }))+ .resolves.toMatchObject({ ok: false, code: 'OPENCODE_SESSION_NOT_FOUND', detail: expect.stringContaining('Session not found') })+ })++ it('refuses when the session still reads back on another model after a second try', async () => {+ const { run, calls } = fakeApi({ get: () => JSON.stringify({ data: { id: SID, model: { id: OLD.modelID, providerID: OLD.providerID } } }) })+ await expect(switchOpencodeSessionModel(SID, NEW, { run, retryDelayMs: 0 }))+ .resolves.toMatchObject({ ok: false, code: 'OPENCODE_MODEL_SWITCH_FAILED', detail: expect.stringContaining('opencode/big-pickle') })+ expect(calls.filter((c) => c[1] === 'session.switchModel')).toHaveLength(2)+ })++ // `provider/model#variant` is opencode's own way to name an effort (`opencode run -m`): on v2 the+ // variant goes in the switch, and the session must read back on it.+ it('switches the variant too when the model names one, and reads it back', async () => {+ const { run, calls } = fakeApi({ get: () => JSON.stringify({ data: { id: SID, model: { id: NEW.modelID, providerID: NEW.providerID, variant: 'high' } } }) })+ await expect(switchOpencodeSessionModel(SID, { ...NEW, modelID: `${NEW.modelID}#high` }, { run })).resolves.toEqual({ ok: true })+ expect(calls[0]).toEqual(['api', 'session.switchModel', '--param', `sessionID=${SID}`, '-d', JSON.stringify({ model: { id: NEW.modelID, providerID: NEW.providerID, variant: 'high' } })])+ const low = fakeApi({ get: () => JSON.stringify({ data: { id: SID, model: { id: NEW.modelID, providerID: NEW.providerID, variant: 'default' } } }) })+ await expect(switchOpencodeSessionModel(SID, { ...NEW, modelID: `${NEW.modelID}#high` }, { run: low.run, retryDelayMs: 0 }))+ .resolves.toMatchObject({ ok: false, code: 'OPENCODE_MODEL_SWITCH_FAILED' })+ })++ it('tries once more when the first switch did not land, and is done when the second does', async () => {+ let reads = 0+ const { run, calls } = fakeApi({ get: () => {+ reads += 1+ const m = reads === 1 ? OLD : NEW+ return JSON.stringify({ data: { id: SID, model: { id: m.modelID, providerID: m.providerID } } })+ } })+ await expect(switchOpencodeSessionModel(SID, NEW, { run, retryDelayMs: 0 })).resolves.toEqual({ ok: true })+ expect(calls.filter((c) => c[1] === 'session.switchModel')).toHaveLength(2)+ })++ it('does not try again where a second try cannot help (no such session)', async () => {+ const { run, calls } = fakeApi({ switch: () => { throw exitError('{"_tag":"SessionNotFoundError"}', 'HTTP 404 Not Found') } })+ await expect(switchOpencodeSessionModel(SID, NEW, { run, retryDelayMs: 0 })).resolves.toMatchObject({ ok: false, code: 'OPENCODE_SESSION_NOT_FOUND' })+ expect(calls.filter((c) => c[1] === 'session.switchModel')).toHaveLength(1)+ })++ // Measured on 2.0.18: the service stores any id — `opencode/does-not-exist` reads back as set —+ // so a model of opencode's own catalogue is checked against it first.+ it('refuses a model the service does not list, before switching, when asked to check', async () => {+ const { run, calls } = fakeApi({ list: () => JSON.stringify({ data: [{ id: OLD.modelID, providerID: OLD.providerID }] }) })+ await expect(switchOpencodeSessionModel(SID, NEW, { run, checkCatalog: true }))+ .resolves.toMatchObject({ ok: false, code: 'OPENCODE_MODEL_UNKNOWN', detail: expect.stringContaining('opencode models') })+ expect(calls.map((c) => c[1])).toEqual(['model.list'])+ })++ it('switches without the check when the catalogue cannot be read, or was not asked for (a grid declared per pane)', async () => {+ const { run, calls } = fakeApi({ list: () => { throw exitError('', 'HTTP 500') } })+ await expect(switchOpencodeSessionModel(SID, NEW, { run, checkCatalog: true })).resolves.toEqual({ ok: true })+ const plain = fakeApi({ list: () => JSON.stringify({ data: [] }) })+ await expect(switchOpencodeSessionModel(SID, NEW, { run: plain.run })).resolves.toEqual({ ok: true })+ expect(plain.calls.map((c) => c[1])).not.toContain('model.list')+ expect(calls.map((c) => c[1])).toContain('session.switchModel')+ })++ it('refuses when opencode is not installed, or the id is not a session id', async () => {+ const missing: OpencodeApiRun = async () => { throw Object.assign(new Error('spawn opencode ENOENT'), { code: 'ENOENT' }) }+ await expect(switchOpencodeSessionModel(SID, NEW, { run: missing })).resolves.toMatchObject({ ok: false, code: 'OPENCODE_MISSING' })+ const { run, calls } = fakeApi()+ await expect(switchOpencodeSessionModel("ses_x'; rm", NEW, { run })).resolves.toMatchObject({ ok: false, code: 'OPENCODE_SESSION_NOT_FOUND' })+ expect(calls).toEqual([])+ })+})++/**+ * The store as 2.0.18 leaves it: v1's `session` / `message` tables still exist (empty for new+ * sessions), and the sessions live in `session_v2` / `session_message`.+ */+function schemaV2(db: string): void {+ schema(db)+ run(db,+ 'CREATE TABLE session_v2 (id TEXT PRIMARY KEY, directory TEXT, model TEXT, agent TEXT);' ++ 'CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT, type TEXT, seq INTEGER, data TEXT);')+ run(db, `INSERT INTO session_v2 VALUES ('${SID}', '/w', '${esc({ id: OLD.modelID, providerID: OLD.providerID })}', 'build');`)+ run(db, `INSERT INTO session_message VALUES ('m1', '${SID}', 'user', 1, '${esc({ text: 'hi' })}');`)+}++d('applyOpencodeSessionModel', () => {+ let dir = ''+ let db = ''+ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'oc-apply-model-'))+ db = join(dir, 'opencode.db')+ vi.spyOn(console, 'log').mockImplementation(() => {})+ })+ afterEach(() => {+ vi.restoreAllMocks()+ rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })+ })++ it('reproduces the false success: the v1 writer finds nothing in a v2 store', async () => {+ // What the retarget used to read as "nothing to rewrite, -m applies on launch" — on a version+ // whose TUI rejects -m outright.+ schemaV2(db)+ await expect(setOpencodeSessionModel(db, SID, NEW)).resolves.toMatchObject({ ok: false, code: 'OPENCODE_SESSION_NOT_FOUND' })+ })++ it('on v2 refuses, rather than reporting success, when the model could not be switched', async () => {+ schemaV2(db)+ const failing: OpencodeApiRun = async () => { throw exitError('', 'connect ECONNREFUSED') }+ await expect(applyOpencodeSessionModel({ opencodeMajor: 2, dbPath: db, sessionId: SID, model: NEW }, { run: failing }))+ .resolves.toMatchObject({ ok: false, code: 'OPENCODE_MODEL_SWITCH_FAILED' })+ })++ it('on v2 switches through the API and leaves the store to opencode', async () => {+ schemaV2(db)+ const { run: api, calls } = fakeApi()+ await expect(applyOpencodeSessionModel({ opencodeMajor: 2, dbPath: db, sessionId: SID, model: NEW, cwd: '/w' }, { run: api }))+ .resolves.toEqual({ ok: true })+ expect(calls.map((args) => args[1])).toEqual(['session.switchModel', 'session.get'])+ expect(JSON.parse(run(db, `SELECT model FROM session_v2 WHERE id = '${SID}';`).trim())).toEqual({ id: OLD.modelID, providerID: OLD.providerID })+ })++ it('on v1 keeps its meaning: a session with no user message yet takes -m on launch', async () => {+ schema(db)+ insertSession(db, SID, null)+ const { run: api, calls } = fakeApi()+ await expect(applyOpencodeSessionModel({ opencodeMajor: 1, dbPath: db, sessionId: SID, model: NEW }, { run: api }))+ .resolves.toEqual({ ok: true })+ expect(calls).toEqual([])+ })++ it('on v1 writes a `#variant` id as it always did — no API, no variant split', async () => {+ schema(db)+ seed(db)+ const { run: api, calls } = fakeApi()+ const withVariant = { ...NEW, modelID: `${NEW.modelID}#high` }+ await expect(applyOpencodeSessionModel({ opencodeMajor: 1, dbPath: db, sessionId: SID, model: withVariant, checkCatalog: true }, { run: api }))+ .resolves.toEqual({ ok: true })+ expect(calls).toEqual([])+ expect(sessionModel(db, SID)).toEqual({ id: withVariant.modelID, providerID: NEW.providerID, variant: 'default' })+ })++ it('on v1 still refuses a write that failed', async () => {+ await expect(applyOpencodeSessionModel({ opencodeMajor: 1, dbPath: join(dir, 'missing', 'opencode.db'), sessionId: SID, model: NEW }))+ .resolves.toMatchObject({ ok: false, code: 'OPENCODE_DB_WRITE_FAILED' })+ })+})diff --git a/cli/src/engines/opencode/sessionModel.ts b/cli/src/engines/opencode/sessionModel.tsindex 4825c9dba..e0f39542c 100644--- a/cli/src/engines/opencode/sessionModel.ts+++ b/cli/src/engines/opencode/sessionModel.ts@@ -29,10 +29,25 @@* messages, `event` rows and every other session are left alone. A session with no user message yet* has nothing to rewrite — and does not need it: with no message to restore from, the TUI takes `-m`* on the respawn. That case is reported as `OPENCODE_SESSION_NOT_FOUND` and the caller proceeds.+ *+ * ## v2+ *+ * Everything above is 1.x. OpenCode 2.0 keeps its sessions in `session_v2` / `session_message` (the+ * v1 tables are still there, and empty for every new session — so the SQL above finds nothing and+ * answers `OPENCODE_SESSION_NOT_FOUND`, which the retarget used to read as fine), its TUI has no+ * `-m`, and one background service owns the store. It also ships a writer: the service's+ * `session.switchModel` operation, reachable as `opencode api session.switchModel`. Measured on+ * 2.0.18 against a scratch session: the row's model changed, a `model-switched` message was+ * appended, a TUI attached to the session switched live, and `opencode -s <id>` (with or without+ * `--standalone`) reopened on the new model. So on v2 this goes through the API and never touches+ * the DB — [switchOpencodeSessionModel]. The service accepts a model it does not know without+ * complaint, so success is read back with `session.get` rather than assumed.*/import { execFile } from 'child_process'import { promisify } from 'util'+import { opencodeBin } from '../../lib/engineBin.js'+import { isOpencodeV2 } from './version.js'const execFileAsync = promisify(execFile)@@ -50,7 +65,13 @@ export type SetOpencodeSessionModelResult =| { ok: true }| {ok: false- code: 'OPENCODE_SQLITE_MISSING' | 'OPENCODE_SESSION_NOT_FOUND' | 'OPENCODE_DB_WRITE_FAILED'+ code:+ | 'OPENCODE_SQLITE_MISSING'+ | 'OPENCODE_SESSION_NOT_FOUND'+ | 'OPENCODE_DB_WRITE_FAILED'+ | 'OPENCODE_MISSING'+ | 'OPENCODE_MODEL_SWITCH_FAILED'+ | 'OPENCODE_MODEL_UNKNOWN'detail: string}@@ -72,7 +93,11 @@ export function opencodeModelFromArgv(args: readonly string[]): OpencodeSessionMif ((arg === '-m' || arg === '--model') && i + 1 < args.length) { id = args[i + 1]; i++ }else if (arg.startsWith('--model=')) id = arg.slice('--model='.length)}- if (!id) return null+ return id ? parseOpencodeModelId(id) : null+}++/** A `provider/model` id split the way opencode splits it, or null when it names no provider. */+export function parseOpencodeModelId(id: string): OpencodeSessionModel | null {const slash = id.indexOf('/')if (slash <= 0 || slash === id.length - 1) return nullreturn { providerID: id.slice(0, slash), modelID: id.slice(slash + 1) }@@ -152,3 +177,139 @@ export async function setOpencodeSessionModel()return { ok: true }}++/** Runs `opencode <args>`; resolves with stdout, rejects the way `execFile` does. A seam for specs. */+export type OpencodeApiRun = (args: string[], options: { cwd?: string }) => Promise<{ stdout: string }>++const runOpencode: OpencodeApiRun = async (args, options) => {+ // Bounded like the sqlite3 write: the service answers in well under a second (77ms measured).+ const { stdout } = await execFileAsync(opencodeBin(), args, {+ ...(options.cwd ? { cwd: options.cwd } : {}), timeout: 15_000, killSignal: 'SIGKILL',+ })+ return { stdout }+}++/** What a failed `opencode api` call said: the body is on stdout, the HTTP status on stderr. */+function apiFailure(err: unknown): { missing: boolean; text: string } {+ const error = err as NodeJS.ErrnoException & { stdout?: string; stderr?: string }+ if (error?.code === 'ENOENT') return { missing: true, text: String(error.message ?? err) }+ const text = [error?.stdout, error?.stderr].map((part) => String(part ?? '').trim()).filter(Boolean).join(' · ')+ return { missing: false, text: text || String(error?.message ?? err) }+}++/**+ * Put `sessionId` on `model` through OpenCode v2's own API — see "v2" in the header.+ *+ * Talks to the background service (`opencode api` with no `--standalone`), which owns the store.+ * Proved on 2.0.18 that a session last opened by a `--standalone` pane is switched just the same,+ * and that the next pane reads it from the store whichever server it runs on. Never touches the DB.+ *+ * Measured on 2.0.18 that the service stores any id (`opencode/does-not-exist` reads back as set),+ * so with `checkCatalog` the model is looked for in `model.list` first — for a model of opencode's+ * own; a grid's provider is declared in its pane's own config, which the service never reads. A+ * switch that did not land is tried once more, after `retryDelayMs`; one that cannot (no such+ * session, no opencode, an unknown model) is not.+ */+export async function switchOpencodeSessionModel(+ sessionId: string,+ model: OpencodeSessionModel,+ options: { cwd?: string; run?: OpencodeApiRun; checkCatalog?: boolean; retryDelayMs?: number } = {},+): Promise<SetOpencodeSessionModelResult> {+ if (!ID_RE.test(sessionId)) {+ return { ok: false, code: 'OPENCODE_SESSION_NOT_FOUND', detail: `not an opencode session id: ${sessionId}` }+ }+ const run = options.run ?? runOpencode+ if (options.checkCatalog) {+ const known = await listsModel(run, model, options.cwd)+ if (known === false) {+ return { ok: false, code: 'OPENCODE_MODEL_UNKNOWN', detail: `opencode has no ${model.providerID}/${model.modelID} — \`opencode models\` lists the ones it has` }+ }+ }+ let result = await switchOnce(run, sessionId, model, options.cwd)+ if (!result.ok && result.code === 'OPENCODE_MODEL_SWITCH_FAILED') {+ console.warn(`[opencode] switch to ${model.providerID}/${model.modelID} did not land (${result.detail}) · trying once more`)+ await new Promise((resolve) => setTimeout(resolve, options.retryDelayMs ?? 1_000))+ result = await switchOnce(run, sessionId, model, options.cwd)+ }+ return result+}++/**+ * A v2 model id and the effort it names: `model#high` is opencode's own way (`opencode run -m+ * provider/model#variant`). v1 never splits it — its `-m` and its rewrite take the id as written.+ */+function splitVariant(modelID: string): { id: string; variant?: string } {+ const at = modelID.lastIndexOf('#')+ return at > 0 && at < modelID.length - 1 ? { id: modelID.slice(0, at), variant: modelID.slice(at + 1) } : { id: modelID }+}++/** Whether the service's `model.list` has [model]; null when the list could not be read. */+async function listsModel(run: OpencodeApiRun, model: OpencodeSessionModel, cwd?: string): Promise<boolean | null> {+ try {+ const { stdout } = await run(['api', 'model.list'], { cwd })+ const parsed = JSON.parse(stdout) as { data?: unknown } | unknown[]+ const rows = (Array.isArray(parsed) ? parsed : (parsed as { data?: unknown }).data) as Array<{ id?: unknown; modelID?: unknown; providerID?: unknown }> | undefined+ if (!Array.isArray(rows)) return null+ const { id } = splitVariant(model.modelID)+ return rows.some((m) => m.providerID === model.providerID && (m.id === id || m.modelID === id))+ } catch {+ return null+ }+}++/** One switch through the service, read back. */+async function switchOnce(run: OpencodeApiRun, sessionId: string, model: OpencodeSessionModel, cwd?: string): Promise<SetOpencodeSessionModelResult> {+ const options = { cwd }+ const param = `sessionID=${sessionId}`+ const { id, variant } = splitVariant(model.modelID)+ const body = JSON.stringify({ model: { id, providerID: model.providerID, ...(variant ? { variant } : {}) } })+ try {+ await run(['api', 'session.switchModel', '--param', param, '-d', body], { cwd: options.cwd })+ } catch (err) {+ const failure = apiFailure(err)+ if (failure.missing) return { ok: false, code: 'OPENCODE_MISSING', detail: `opencode not found: ${failure.text}` }+ const code = /SessionNotFoundError|HTTP 404/.test(failure.text) ? 'OPENCODE_SESSION_NOT_FOUND' : 'OPENCODE_MODEL_SWITCH_FAILED'+ return { ok: false, code, detail: failure.text }+ }+ // Read back: the service answers 204 for any model, known or not, so only the session itself can+ // say the switch landed.+ let stdout: string+ try {+ ({ stdout } = await run(['api', 'session.get', '--param', param], { cwd: options.cwd }))+ } catch (err) {+ return { ok: false, code: 'OPENCODE_MODEL_SWITCH_FAILED', detail: `could not read the session back · ${apiFailure(err).text}` }+ }+ let now: { id?: unknown; providerID?: unknown; variant?: unknown } | undefined+ try {+ now = (JSON.parse(stdout) as { data?: { model?: { id?: unknown; providerID?: unknown; variant?: unknown } } }).data?.model+ } catch {+ now = undefined+ }+ // (A variant asked for must read back too; none asked for, the service's own is fine.)+ if (now?.id !== id || now?.providerID !== model.providerID || (variant && now?.variant !== variant)) {+ const seen = now ? `${String(now.providerID)}/${String(now.id)}${now.variant ? `#${String(now.variant)}` : ''}` : stdout.trim().slice(0, 200)+ return { ok: false, code: 'OPENCODE_MODEL_SWITCH_FAILED', detail: `session ${sessionId} is still on ${seen}` }+ }+ console.log(`[opencode] session model switched to ${model.providerID}/${model.modelID} through the service`)+ return { ok: true }+}++/**+ * Put a resumed session on `model` the way the installed OpenCode needs, BEFORE its pane is+ * relaunched. A failure here is the caller's refusal: the live process has not been touched yet.+ *+ * * v1 (or a version not read): the SQL rewrite above. A session with no user message yet is fine+ * there — the relaunch's `-m` applies to it — so that one answer is success.+ * * v2: the API. Every failure is a failure, `SESSION_NOT_FOUND` included: the relaunch carries no+ * `-m`, so a switch that did not land is a pane on the old model with the move reported done.+ */+export async function applyOpencodeSessionModel(+ input: { opencodeMajor: number | null | undefined; dbPath: string; sessionId: string; model: OpencodeSessionModel; cwd?: string; checkCatalog?: boolean },+ deps: { run?: OpencodeApiRun; retryDelayMs?: number } = {},+): Promise<SetOpencodeSessionModelResult> {+ if (isOpencodeV2(input.opencodeMajor)) {+ return switchOpencodeSessionModel(input.sessionId, input.model, { cwd: input.cwd, run: deps.run, checkCatalog: input.checkCatalog, retryDelayMs: deps.retryDelayMs })+ }+ const written = await setOpencodeSessionModel(input.dbPath, input.sessionId, input.model)+ return !written.ok && written.code === 'OPENCODE_SESSION_NOT_FOUND' ? { ok: true } : written+}diff --git a/cli/src/engines/opencode/tuiFlags.spec.ts b/cli/src/engines/opencode/tuiFlags.spec.tsnew file mode 100644index 000000000..e5724a849--- /dev/null+++ b/cli/src/engines/opencode/tuiFlags.spec.ts@@ -0,0 +1,62 @@+/**+ * Every flag this daemon hands the `opencode` TUI, checked against the INSTALLED binary's own help.+ *+ * OpenCode updated itself from 1.18 to 2.0 underneath a running daemon, and v2's TUI exits 1 on a+ * flag it does not list (`Unrecognized flag: -m in command opencode`) — the pane became a shell, and+ * every spec still passed because they all pinned v1. This one reads the real `--help`, so the next+ * flag a release drops fails here instead of in someone's pane. Skipped where opencode is not+ * installed.+ */+import { execFileSync } from 'node:child_process'+import { describe, expect, it } from 'vitest'+import { buildEngineCommandArgv, namedAgentArgs, supportsNamedAgent } from '../../lib/engineLaunch.js'+import { buildLaunchOverrides, type LaunchOverridesDeps, type LaunchSource } from '../../lib/launchOverrides.js'+import { binaryOnPath } from '../../lib/binaryOnPath.js'+import { opencodeMajorVersion } from './version.js'++const installed = binaryOnPath('opencode')++describe.skipIf(!installed)('the installed opencode TUI accepts every flag we pass it', () => {+ const help = installed ? execFileSync('opencode', ['--help'], { encoding: 'utf8', timeout: 15_000 }) : ''+ const major = installed ? opencodeMajorVersion() : null+ const deps: LaunchOverridesDeps = {+ machine: () => ({ hermesSystemManaged: false, opencodeMajor: major }),+ writeGridConfigDir: async (key) => `/state/grid-engine-config/${key}`,+ tmuxSupportsSessionEnv: async () => true,+ installCodexHooks: () => {},+ readCodexConfig: () => null,+ }+ const GRID = {+ networkId: 'grid-x', networkName: 'autonomous.ai', baseUrl: 'https://grid.example/grid-x/relay/v1', apiKey: 'k', model: 'Qwen',+ }+ /** `--flag` or `-f` listed as a token of the help text (`--session, -s string`, `-m, --model`). */+ const listed = (flag: string) => new RegExp(`(^|[\\s,])${flag.replace(/[-]/g, '\\-')}([\\s,=]|$)`, 'm').test(help)++ it.each<[string, LaunchSource]>([+ ['own login', {}],+ ['own login, back on a remembered model', { subscriptionModel: 'opencode/big-pickle' }],+ ['a grid', { gridLaunch: GRID }],+ ['a named agent', { agent: 'harness-compute' }],+ ])('%s', async (_, source) => {+ const built = await buildLaunchOverrides(deps, 'opencode', source, 'a')+ expect(built.ok).toBe(true)+ if (!built.ok) return+ const argv = buildEngineCommandArgv('opencode', {+ bypassPermission: true,+ resumeSessionId: 'ses_1',+ firstPrompt: 'hello',+ extraArgs: built.overrides.extraArgs,+ })+ const flags = argv.slice(1).filter((token) => token.startsWith('-'))+ expect(flags.length).toBeGreaterThan(0)+ for (const flag of flags) expect(listed(flag), `${flag} is not in \`opencode --help\` (v${major})`).toBe(true)+ })++ it('agrees with the named-agent contract', () => {+ // Where the contract says yes, the flag it hands over must exist; where it says no, nothing is passed.+ if (!supportsNamedAgent('opencode', major)) return+ for (const flag of namedAgentArgs('opencode', 'x', major).filter((token) => token.startsWith('-'))) {+ expect(listed(flag), `${flag} is not in \`opencode --help\``).toBe(true)+ }+ })+})diff --git a/cli/src/engines/opencode/version.spec.ts b/cli/src/engines/opencode/version.spec.tsnew file mode 100644index 000000000..0a8c65351--- /dev/null+++ b/cli/src/engines/opencode/version.spec.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from 'vitest'+import { isOpencodeV2, opencodeMajorVersion, parseOpencodeMajor } from './version.js'++describe('parseOpencodeMajor', () => {+ it('reads the major out of what each generation prints for --version', () => {+ // v2 prefixes a name and a `v`; v1 printed the bare number.+ expect(parseOpencodeMajor('opencode v2.0.18\n')).toBe(2)+ expect(parseOpencodeMajor('1.18.31\n')).toBe(1)+ })++ it('answers null for anything that is not a version', () => {+ expect(parseOpencodeMajor('')).toBeNull()+ expect(parseOpencodeMajor('command not found')).toBeNull()+ })+})++describe('isOpencodeV2', () => {+ it('is true from 2 up, and false for v1 or an unknown version', () => {+ expect(isOpencodeV2(2)).toBe(true)+ expect(isOpencodeV2(3)).toBe(true)+ expect(isOpencodeV2(1)).toBe(false)+ expect(isOpencodeV2(null)).toBe(false)+ expect(isOpencodeV2(undefined)).toBe(false)+ })+})++describe('opencodeMajorVersion', () => {+ it('runs --version once per installed binary, and again once the binary changes', () => {+ let calls = 0+ let stamp = 'a'+ const probe = { identity: () => stamp, read: () => { calls++; return stamp === 'a' ? '1.18.31' : 'opencode v2.0.18' } }+ const cache = new Map<string, number | null>()+ expect(opencodeMajorVersion(probe, cache)).toBe(1)+ expect(opencodeMajorVersion(probe, cache)).toBe(1)+ expect(calls).toBe(1)+ // OpenCode updates itself in place (1.18 → 2.0 happened under a running daemon): a new file is a+ // new answer.+ stamp = 'b'+ expect(opencodeMajorVersion(probe, cache)).toBe(2)+ expect(calls).toBe(2)+ })++ it('answers null, without throwing, when the binary is missing or will not answer', () => {+ const cache = new Map<string, number | null>()+ expect(opencodeMajorVersion({ identity: () => null, read: () => { throw new Error('ENOENT') } }, cache)).toBeNull()+ expect(opencodeMajorVersion({ identity: () => 'x', read: () => { throw new Error('timeout') } }, cache)).toBeNull()+ })+})diff --git a/cli/src/engines/opencode/version.ts b/cli/src/engines/opencode/version.tsnew file mode 100644index 000000000..5500598df--- /dev/null+++ b/cli/src/engines/opencode/version.ts@@ -0,0 +1,80 @@+/**+ * Which generation of OpenCode is installed, read from the binary itself.+ *+ * The two generations take different command lines and keep sessions in different places, and a v1+ * command line kills a v2 pane: 2.0's TUI accepts only `--standalone --server --auto -c -s --prompt`+ * and exits 1 on anything else (`Unrecognized flag: -m in command opencode`). `-m` and `--agent` live+ * on `opencode run` now. So every launch that hands the TUI a flag asks this first.+ *+ * Read once per installed file, not once per daemon: OpenCode updates itself in place, and 1.18 → 2.0+ * arrived that way, under a running daemon. The file's size and mtime key the cache, so the next+ * launch after an update asks again and every other launch costs a `stat`.+ *+ * Unknown (not installed, or an answer that is not a version) is `null`, and every caller treats it as+ * v1 — the behaviour it had before this module existed.+ */++import { execFileSync } from 'node:child_process'+import { statSync } from 'node:fs'+import { opencodeBin } from '../../lib/engineBin.js'+import { resolveBinaryOnPath } from '../../lib/binaryOnPath.js'++/** The first major whose TUI rejects `-m` / `--agent` and whose sessions live behind its API. */+const OPENCODE_V2_MAJOR = 2++/** The major in what `opencode --version` prints: `opencode v2.0.18` on v2, a bare `1.18.31` on v1. */+export function parseOpencodeMajor(output: string): number | null {+ const match = /(\d+)\.\d+\.\d+/.exec(output)+ return match ? Number(match[1]) : null+}++export function isOpencodeV2(major: number | null | undefined): boolean {+ return (major ?? 0) >= OPENCODE_V2_MAJOR+}++/** How the version is read. A seam so the cache can be specified without a binary. */+export interface OpencodeVersionProbe {+ /** Something that changes when the installed file does, or null when it cannot be found. */+ identity: () => string | null+ /** What `--version` prints. Throws when the binary will not answer. */+ read: () => string+}++const realProbe: OpencodeVersionProbe = {+ identity: () => {+ const bin = opencodeBin()+ const path = bin.includes('/') ? bin : resolveBinaryOnPath(bin)+ if (!path) return null+ try {+ const stat = statSync(path)+ return `${path}:${stat.size}:${stat.mtimeMs}`+ } catch {+ return null+ }+ },+ // Bounded: this runs on the daemon's thread, once per installed file. 2.0.18 answers in ~50ms.+ read: () => execFileSync(opencodeBin(), ['--version'], {+ encoding: 'utf8', timeout: 5_000, killSignal: 'SIGKILL', stdio: ['ignore', 'pipe', 'ignore'],+ }),+}++const cache = new Map<string, number | null>()++/** The installed OpenCode's major version, or null when it cannot be read. Never throws. */+export function opencodeMajorVersion(+ probe: OpencodeVersionProbe = realProbe,+ memo: Map<string, number | null> = cache,+): number | null {+ const identity = probe.identity()+ // No file to key on: nothing is installed where this daemon can see it, so nothing is cached — the+ // pane may install it, and the next launch should find out what it got.+ if (identity !== null && memo.has(identity)) return memo.get(identity) ?? null+ let major: number | null+ try {+ major = parseOpencodeMajor(probe.read())+ } catch {+ major = null+ }+ if (identity !== null) memo.set(identity, major)+ return major+}diff --git a/cli/src/lib/discoveryScripts.spec.ts b/cli/src/lib/discoveryScripts.spec.tsindex ba9ec83fb..6397a0568 100644--- a/cli/src/lib/discoveryScripts.spec.ts+++ b/cli/src/lib/discoveryScripts.spec.ts@@ -1,11 +1,14 @@-import { afterEach, describe, expect, it, vi } from 'vitest'-import { mkdtempSync, readFileSync, rmSync } from 'fs'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'import { tmpdir } from 'os'import { join } from 'path'+import { pathToFileURL } from 'url'/** Pi and OpenCode register through generated source, so pin its process-owned wire contract directly. */const dirs: string[] = []+beforeEach(() => { vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval', 'setTimeout', 'clearTimeout'] }) })afterEach(() => {+ vi.useRealTimers()for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })vi.resetModules()})@@ -45,4 +48,60 @@ describe('generated discovery scripts', () => {expect(src).not.toContain('launcherId')expect(src).toContain('if (!pane || !token')})++ // OpenCode 2.0 loads only `export default { id, setup }`, runs server plugins in one shared service+ // (no TMUX_PANE there), and scans `plugins/<dir>/tui.js` for plugins that run IN the pane's TUI. So+ // 2.0 gets a TUI plugin beside the 1.x file — which is left exactly as it was — posting the same+ // session-start the 1.x plugin posts, for the session the pane shows.+ it('adds an OpenCode 2.0 TUI plugin that posts the session the pane shows, and leaves the 1.x file as it was', async () => {+ const config = scratch()+ const data = scratch()+ const pluginDir = join(config, 'plugin')+ vi.resetModules()+ process.env.OPENCODE_PLUGIN_DIR = pluginDir+ process.env.ADAPTER_DATA_DIR = data+ writeFileSync(join(data, 'hook-credential'), 'tok-123\n')+ const { installOpencodePlugin } = await import('./hooks.js')+ installOpencodePlugin(18473)++ const v1 = readFileSync(join(pluginDir, 'launcher-register.js'), 'utf-8')+ expect(v1).toContain('export const MachineRegister')+ expect(v1).not.toContain('export default')+ const tuiPath = join(config, 'plugins', 'launcher-register', 'tui.js')+ expect(existsSync(tuiPath)).toBe(true)++ const posts: Array<{ url: string; body: Record<string, unknown>; token: string }> = []+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (url, init) => {+ posts.push({ url: String(url), body: JSON.parse(String(init?.body)), token: String((init?.headers as Record<string, string>)['x-harness-hook-token']) })+ return new Response(null, { status: 204 })+ })+ const pane = process.env.TMUX_PANE+ process.env.TMUX_PANE = '%60'+ try {+ const plugin = (await import(pathToFileURL(tuiPath).href)).default+ expect(plugin.id).toBeTruthy()+ let route: { type: string; sessionID?: string } = { type: 'home' }+ const sessions: Record<string, { parentID?: string; location: { directory: string } }> = {+ ses_main: { location: { directory: '/w/app' } },+ ses_child: { parentID: 'ses_main', location: { directory: '/w/app' } },+ ses_next: { location: { directory: '/w/app' } },+ }+ const ctx = { ui: { router: { current: () => route } }, data: { session: { get: (id: string) => sessions[id] }, on: () => () => {} } }+ const stop = plugin.setup(ctx)+ const tick = () => vi.advanceTimersByTimeAsync(1_100)+ route = { type: 'session', sessionID: 'ses_main' }+ await tick(); await tick()+ route = { type: 'session', sessionID: 'ses_child' }+ await tick()+ route = { type: 'session', sessionID: 'ses_next' }+ await tick()+ if (typeof stop === 'function') stop()+ expect(posts.map((p) => p.body.sessionId)).toEqual(['ses_main', 'ses_next'])+ expect(posts[0]).toMatchObject({ url: 'http://127.0.0.1:18473/api/hook/session-start', token: 'tok-123' })+ expect(posts[0].body).toMatchObject({ engine: 'opencode', sessionId: 'ses_main', tmuxPane: '%60', cwd: '/w/app', callerPid: process.pid })+ } finally {+ fetchSpy.mockRestore()+ if (pane === undefined) delete process.env.TMUX_PANE; else process.env.TMUX_PANE = pane+ }+ })})diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.tsindex ce55afc42..55c367c92 100644--- a/cli/src/lib/engineLaunch.spec.ts+++ b/cli/src/lib/engineLaunch.spec.ts@@ -533,6 +533,14 @@ describe('opening as a named agent', () => {.toEqual([engineBin('opencode'), '--session', 'ses_1', '--agent', 'harness-compute'])})+ it('refuses opencode v2, whose TUI has no --agent (only `opencode run` does)', () => {+ expect(supportsNamedAgent('opencode', 2)).toBe(false)+ expect(() => namedAgentArgs('opencode', 'harness-compute', 2)).toThrow(NamedAgentUnsupportedError)+ // v1, or a version not read, keeps the flag it always had.+ expect(supportsNamedAgent('opencode', 1)).toBe(true)+ expect(supportsNamedAgent('opencode', null)).toBe(true)+ })+it('refuses every other engine, naming it, rather than dropping the name', () => {for (const engine of ENGINES) {if (engine === 'opencode') continuediff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.tsindex e9290c7ab..1b9d24446 100644--- a/cli/src/lib/engineLaunch.ts+++ b/cli/src/lib/engineLaunch.ts@@ -2,6 +2,7 @@ import { execFile } from 'node:child_process'import { homedir, userInfo } from 'node:os'import { isAbsolute, basename, dirname, join } from 'node:path'import { isTerminalEngine, type AgentEngine } from '../engines/types.js'+import { isOpencodeV2 } from '../engines/opencode/version.js'import { binaryOnPath, resolveBinaryOnPath } from './binaryOnPath.js'import { engineBin } from './engineBin.js'import { engineInstallPaths, npmEnginePrefix, type EngineInstallRecipe } from './engineInstall.js'@@ -180,15 +181,20 @@ export class NamedAgentUnsupportedError extends Error {}}-export function supportsNamedAgent(engine: AgentEngine): boolean {+/**+ * `opencodeMajor` is the installed OpenCode's major version (`engines/opencode/version.ts`), absent+ * meaning v1. v2 moved `--agent` to `opencode run`; its TUI exits 1 on the flag, so v2 has no entry.+ */+export function supportsNamedAgent(engine: AgentEngine, opencodeMajor: number | null = null): boolean {+ if (engine === 'opencode' && isOpencodeV2(opencodeMajor)) return falsereturn NAMED_AGENT_ARGS[engine] !== null}/** The argv that opens `engine` as its named agent `agent`. Throws [NamedAgentUnsupportedError] for* an engine with no contract, so a caller cannot build an argv that silently drops the name. */-export function namedAgentArgs(engine: AgentEngine, agent: string): string[] {+export function namedAgentArgs(engine: AgentEngine, agent: string, opencodeMajor: number | null = null): string[] {const lead = NAMED_AGENT_ARGS[engine]- if (lead === null) throw new NamedAgentUnsupportedError(engine)+ if (lead === null || !supportsNamedAgent(engine, opencodeMajor)) throw new NamedAgentUnsupportedError(engine)return [...lead, agent]}diff --git a/cli/src/lib/gridLaunch.spec.ts b/cli/src/lib/gridLaunch.spec.tsindex dcb0f75d2..ff47057e9 100644--- a/cli/src/lib/gridLaunch.spec.ts+++ b/cli/src/lib/gridLaunch.spec.ts@@ -516,6 +516,54 @@ describe('opencode declares the grid as a provider', () => {expect(launch().configDir!.envVar).toBe('OPENCODE_CONFIG')expect(launch().configDir!.pointAt).toBe('opencode.json')})++ it('names the model a resumed session has to be put on, the same pair argv names', () => {+ expect(launch('DeepSeek-V4-Flash-0731').sessionModel).toBe('autonomous-ai/DeepSeek-V4-Flash-0731')+ expect(launch().sessionModel).toBe('autonomous-ai/Auto')+ })+})++describe('opencode v2 on a grid', () => {+ const base: GridLaunchOverride = {+ networkId: 'grid-x',+ networkName: 'autonomous.ai',+ baseUrl: 'https://grid.autonomous.ai/grid-x/relay/v1',+ apiKey: 'RELAY-KEY',+ }+ const V2: GridLaunchMachine = { hermesSystemManaged: false, opencodeMajor: 2 }+ const launch = (model?: string, machine = V2) => {+ const built = buildGridEngineLaunch('opencode', model ? { ...base, model } : base, machine)+ if (!built.ok) throw new Error('opencode refused')+ return built.launch+ }+ const config = (model?: string) => JSON.parse(launch(model).configDir!.files[0].content)++ it('never passes -m: the v2 TUI has no such flag and exits 1 on it', () => {+ // Measured on 2.0.18: `Unrecognized flag: -m in command opencode`, and the pane became a shell.+ expect(launch('DeepSeek-V4-Flash-0731').args).not.toContain('-m')+ expect(launch().args).not.toContain('-m')+ })++ it('runs its own server, the only one that reads the per-agent OPENCODE_CONFIG', () => {+ // The shared background service ignores a pane's OPENCODE_CONFIG; a private one reads it.+ expect(launch('DeepSeek-V4-Flash-0731').args).toEqual(['--standalone'])+ })++ it('selects the model for a NEW session in the config, which v2 accepts for a declared provider', () => {+ expect(config('DeepSeek-V4-Flash-0731').model).toBe('autonomous-ai/DeepSeek-V4-Flash-0731')+ expect(config().model).toBe('autonomous-ai/Auto')+ })++ it('still names the model a resumed session has to be switched to', () => {+ expect(launch('DeepSeek-V4-Flash-0731').sessionModel).toBe('autonomous-ai/DeepSeek-V4-Flash-0731')+ })++ it('leaves a v1 or unknown install exactly as it was', () => {+ for (const machine of [PLAIN_MACHINE, { hermesSystemManaged: false, opencodeMajor: 1 }, { hermesSystemManaged: false, opencodeMajor: null }]) {+ expect(launch('Qwen', machine).args).toEqual(['-m', 'autonomous-ai/Qwen'])+ expect(JSON.parse(launch('Qwen', machine).configDir!.files[0].content)).not.toHaveProperty('model')+ }+ })})describe('web tools (grid ADR 0041)', () => {diff --git a/cli/src/lib/gridLaunch.ts b/cli/src/lib/gridLaunch.tsindex 8b26b4dd7..a3d598936 100644--- a/cli/src/lib/gridLaunch.ts+++ b/cli/src/lib/gridLaunch.ts@@ -45,6 +45,7 @@import { homedir } from 'node:os'import { join } from 'node:path'import type { AgentEngine } from '../engines/types.js'+import { isOpencodeV2 } from '../engines/opencode/version.js'import {CLAUDE_ALLOW_WEB_TOOLS_ARG,CLAUDE_DISALLOW_WEB_TOOLS_ARG,@@ -306,10 +307,12 @@ function opencodeProviderId(override: GridLaunchOverride): string {** Four things here are load-bearing, each of which breaks the engine differently when got wrong:*- * 1. **No top-level `model` key.** OpenCode's schema `$ref`s a CLOSED enum of known public models- * with no wildcard branch, so naming a private grid's model there makes OpenCode refuse the- * whole config at startup — a failure that arrives as a dead pane, long after the launch looked- * fine. The model is selected on argv instead, which is not schema-validated.+ * 1. **No top-level `model` key on v1.** OpenCode 1.x's schema `$ref`s a CLOSED enum of known public+ * models with no wildcard branch, so naming a private grid's model there makes OpenCode refuse+ * the whole config at startup — a failure that arrives as a dead pane, long after the launch+ * looked fine. The model is selected on argv instead, which is not schema-validated. v2 is the+ * other way round: its TUI has no `-m`, and it accepts `model` naming the provider declared here+ * (measured on 2.0.18: a fresh `--standalone` pane opened on it), so on v2 the key is written.* 2. **`baseURL` is the relay root verbatim.** It already ends in `/relay/v1`; the SDK appends* `/chat/completions` itself, so any "normalising" here 404s every request.* 3. **`apiKey` is `{env:…}`, not the key.** Nothing written to disk by this module may contain a@@ -336,6 +339,7 @@ function opencodeGridConfig(provider: string,override: GridLaunchOverride,model: string,+ v2: boolean,): string {// EXACTLY ONE model, and that is deliberate: it is what the agent was created with.//@@ -356,6 +360,9 @@ function opencodeGridConfig(}return `${JSON.stringify({$schema: 'https://opencode.ai/config.json',+ // v2 only — see point 1 above. A resumed session keeps its own model whatever this says; the+ // caller switches that one through the API (`sessionModel`).+ ...(v2 ? { model: `${provider}/${model}` } : {}),provider: {[provider]: {npm: '@ai-sdk/openai-compatible',@@ -449,6 +456,11 @@ export interface GridLaunchMachine {* such a machine the overlay is dropped and the agent launches without web tools.*/hermesSystemManaged: boolean+ /**+ * The installed OpenCode's major version (`engines/opencode/version.ts`); absent or null reads as+ * v1. v2's TUI rejects `-m`, and only a private server (`--standalone`) reads `OPENCODE_CONFIG`.+ */+ opencodeMajor?: number | null}/** How one engine is launched against a grid. */@@ -459,6 +471,12 @@ export interface GridEngineLaunch {args: string[]/** What this launch gives the agent by way of web search. See [GridWebSearchStatus]. */webSearch: GridWebSearchStatus+ /**+ * The `provider/model` a RESUMED session has to be put on before the relaunch, for an engine whose+ * resume restores the session's own stored model whatever argv says. OpenCode only; the caller+ * applies it (`applyOpencodeSessionModel`).+ */+ sessionModel?: string/*** For an engine that reads its provider out of a config directory rather than an environment* variable: files the daemon writes into a directory IT owns, and the variable that points the@@ -738,30 +756,42 @@ const GRID_ENGINE_CONTRACTS: Partial<Record<AgentEngine, GridEngineContract>> =// So it takes the shape codex and pi take: DECLARE a provider. `OPENCODE_CONFIG` names a config// file, this daemon writes one into a directory it owns, and the grid arrives as a provider whose// models are the grid's own ids. The user's `~/.config/opencode/opencode.json` is never opened.+ //+ // ## v2 (2.0.18, measured)+ //+ // The TUI rejects `-m` and exits 1, so the model goes in the config file instead (see+ // `opencodeGridConfig`, point 1). And by default the TUI attaches to ONE background service shared+ // by every OpenCode on the machine, which never sees a pane's `OPENCODE_CONFIG`: a session put on a+ // provider declared only here showed the service's default model in its footer. `--standalone`+ // gives the pane its own server, which reads the file — the same session then showed the declared+ // model. A resumed session keeps its stored model either way, so `sessionModel` is what the caller+ // switches it to before the relaunch.opencode: {- build: (override) => {+ build: (override, machine) => {const provider = opencodeProviderId(override)// No model chosen means the grid routes — `Auto` is the router's own id, and the relay serves// it (verified: 200). It is a real id to OpenCode either way, which is what matters: the// provider block has to name something, and leaving the model out entirely puts OpenCode back// on its own catalogue and the 503 above.const model = override.model ?? GRID_ROUTER_MODEL+ const v2 = isOpencodeV2(machine.opencodeMajor)return {// The key travels in the environment and is REFERENCED from the file, never written into it// — the rule every config-file engine here follows.env: { [GRID_KEY_VAR]: override.apiKey },// Deliberately NOT `OPENAI_BASE_URL`/`OPENAI_API_KEY`. Setting them would re-arm the built-in// `openai` provider beside ours, and its catalogue is what chose the model the grid refused.- args: ['-m', `${provider}/${model}`],+ args: v2 ? ['--standalone'] : ['-m', `${provider}/${model}`],configDir: {envVar: 'OPENCODE_CONFIG',pointAt: OPENCODE_CONFIG_FILE,files: [{name: OPENCODE_CONFIG_FILE,- content: opencodeGridConfig(provider, override, model),+ content: opencodeGridConfig(provider, override, model, v2),}],},webSearch: webSearchWhenWired(override),+ sessionModel: `${provider}/${model}`,}},},diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.tsindex 1193f93d6..8c0d249d2 100644--- a/cli/src/lib/hooks.ts+++ b/cli/src/lib/hooks.ts@@ -399,6 +399,9 @@ export function installCursorHooks(port: number): void {}const OPENCODE_PLUGIN_PATH = join(env.OPENCODE_PLUGIN_DIR, 'launcher-register.js')+// OpenCode 2.0's TUI plugins: `<config>/plugins/<dir>/tui.js` (plural, a directory) — beside the 1.x+// `plugin/` file, which 1.x keeps reading as it always did.+const OPENCODE_TUI_PLUGIN_PATH = join(dirname(env.OPENCODE_PLUGIN_DIR), 'plugins', 'launcher-register', 'tui.js')const KILO_PLUGIN_PATH = join(env.KILO_PLUGIN_DIR, 'launcher-register.js')/**@@ -460,6 +463,69 @@ export const MachineRegister = async ({ directory, worktree, project }) => {`}+/**+ * OpenCode 2.0's discovery plugin: the same session-start the 1.x plugin posts, from where 2.0 still+ * knows the pane.+ *+ * Measured on 2.0.18 (upstream v2.0.18 source): a plugin must `export default { id, setup }` — the 1.x+ * named export fails to load ("Plugin must export a default definition"); server plugins run in ONE+ * background service shared by every TUI, whose environment has no `TMUX_PANE`, and whose events carry+ * no client — so no server plugin can say which pane a session is in. A TUI plugin runs in the pane's+ * own process: `process.env.TMUX_PANE` is the pane, and `ui.router.current()` is the session it shows.+ * It posts that session — and the next one, when the pane switches (`/sessions`, a tab) — skipping a+ * sub-agent's (it has a parent), each once. Polled: the router is a store, and a missed event costs a+ * second, not a binding. Without a pane, a token or the router (another 2.x), it does nothing.+ */+function opencodeTuiPluginSource(port: number): string {+ return `// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine+// daemon (127.0.0.1:${port}) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.+import { readFileSync } from "node:fs"+const hookToken = () => { try { return readFileSync(${JSON.stringify(join(env.ADAPTER_DATA_DIR, 'hook-credential'))}, "utf8").trim() } catch { return "" } }+export default {+ id: "harness-session-register",+ setup(ctx) {+ const pane = process.env.TMUX_PANE+ const router = ctx && ctx.ui && ctx.ui.router+ if (!pane || !router || typeof router.current !== "function") return+ const posted = new Set()+ let busy = false+ const post = async (sessionID) => {+ const token = hookToken()+ if (!token || !sessionID || posted.has(sessionID) || busy) return+ busy = true+ try {+ let info+ try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}+ if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card+ const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()+ const res = await fetch("http://127.0.0.1:${port}/api/hook/session-start", {+ method: "POST",+ headers: { "content-type": "application/json", "x-harness-hook-token": token },+ body: JSON.stringify({+ engine: "opencode",+ pluginVersion: ${JSON.stringify(VERSION)},+ sessionId: sessionID,+ cwd,+ tmuxPane: pane,+ callerPid: process.pid,+ runtimeHints: [{ backend: "tmux", paneId: pane }],+ }),+ })+ if (res && res.ok) posted.add(sessionID)+ } catch {} finally { busy = false }+ }+ const check = () => {+ try { const at = router.current(); if (at && at.type === "session" && at.sessionID) post(at.sessionID) } catch {}+ }+ check()+ const timer = setInterval(check, 1000)+ if (timer && typeof timer.unref === "function") timer.unref()+ return () => clearInterval(timer)+ },+}+`+}+const COMMANDCODE_SETTINGS_PATH = join(env.COMMANDCODE_HOME, 'settings.json')// Command Code exposes only SessionStart / PreToolUse / PostToolUse / Stop — there is NO// UserPromptSubmit (so no catch-hook re-register) and no SessionEnd (the tmux reaper covers that).@@ -1063,9 +1129,13 @@ export function installAmpPlugin(port: number): void {}}-/** Idempotently drop the OpenCode discovery plugin into ~/.config/opencode/plugin/. */+/**+ * Idempotently drop the OpenCode discovery plugin into ~/.config/opencode/plugin/ (1.x, as it always+ * was), and its 2.0 TUI form into ~/.config/opencode/plugins/launcher-register/ (1.x never looks there).+ */export function installOpencodePlugin(port: number): void {installForkPlugin('opencode', OPENCODE_PLUGIN_PATH, 'OpenCode', port)+ installPluginSource('opencode', OPENCODE_TUI_PLUGIN_PATH, 'OpenCode 2 TUI', opencodeTuiPluginSource(port))}/**@@ -1081,7 +1151,11 @@ export function installKiloPlugin(port: number): void {}function installForkPlugin(engine: 'opencode' | 'kilo', path: string, product: string, port: number): void {- const source = forkPluginSource(engine, port)+ installPluginSource(engine, path, product, forkPluginSource(engine, port))+}++/** Write [source] to [path] unless it is there already, atomically. */+function installPluginSource(engine: 'opencode' | 'kilo', path: string, product: string, source: string): void {try {if (existsSync(path) && readFileSync(path, 'utf-8') === source) {console.log(`[hooks] ${product} discovery plugin already installed`)diff --git a/cli/src/lib/launchOverrides.spec.ts b/cli/src/lib/launchOverrides.spec.tsindex 262575b1f..797ddae9f 100644--- a/cli/src/lib/launchOverrides.spec.ts+++ b/cli/src/lib/launchOverrides.spec.ts@@ -206,7 +206,7 @@ describe('buildLaunchOverrides — a pane opened as a named agent comes back asconst own = await buildLaunchOverrides(deps().d, 'opencode', { agent: 'harness-compute' }, 'a')expect(own).toEqual({ ok: true, overrides: { env: {}, extraArgs: ['--agent', 'harness-compute'], clearEnv: [...DSH_SESSION_ENV] } })const home = await buildLaunchOverrides(deps().d, 'opencode', { agent: 'harness-compute', subscriptionModel: 'anthropic/claude' }, 'a')- expect(home).toMatchObject({ ok: true, overrides: { extraArgs: ['-m', 'anthropic/claude', '--agent', 'harness-compute'] } })+ expect(home).toMatchObject({ ok: true, overrides: { extraArgs: ['-m', 'anthropic/claude', '--agent', 'harness-compute'], sessionModel: 'anthropic/claude' } })const grid = await buildLaunchOverrides(deps().d, 'opencode', { gridLaunch: GRID, agent: 'harness-compute' }, 'a')expect(grid.ok).toBe(true)if (!grid.ok) return@@ -220,6 +220,31 @@ describe('buildLaunchOverrides — a pane opened as a named agent comes back as})})+describe('buildLaunchOverrides — opencode v2', () => {+ const v2 = () => deps({ machine: () => ({ hermesSystemManaged: false, opencodeMajor: 2 }) }).d++ it('hands the v2 TUI neither -m nor --agent, on its own login or on a grid', async () => {+ // Both are `opencode run` flags in v2; the TUI exits 1 on them and the pane becomes a shell.+ for (const source of [+ { agent: 'harness-compute', subscriptionModel: 'anthropic/claude' },+ { gridLaunch: GRID, agent: 'harness-compute' },+ ]) {+ const built = await buildLaunchOverrides(v2(), 'opencode', source, 'a')+ expect(built.ok).toBe(true)+ if (!built.ok) return+ expect(built.overrides.extraArgs).not.toContain('-m')+ expect(built.overrides.extraArgs).not.toContain('--agent')+ }+ })++ it('carries the model the resumed session has to be switched to', async () => {+ const home = await buildLaunchOverrides(v2(), 'opencode', { subscriptionModel: 'anthropic/claude' }, 'a')+ expect(home).toMatchObject({ ok: true, overrides: { extraArgs: [], sessionModel: 'anthropic/claude' } })+ const grid = await buildLaunchOverrides(v2(), 'opencode', { gridLaunch: GRID }, 'a')+ expect(grid).toMatchObject({ ok: true, overrides: { extraArgs: ['--standalone'], sessionModel: 'team-grid/gpt-5' } })+ })+})+describe('buildLaunchOverrides — what the app is told about web search', () => {const WITH_MCP: GridLaunchOverride = { ...GRID, mcpUrl: 'https://api-grid.example/v1/grid/web-mcp/' }diff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.tsindex a6c20c8cc..bf3aab5b0 100644--- a/cli/src/lib/launchOverrides.ts+++ b/cli/src/lib/launchOverrides.ts@@ -42,6 +42,12 @@ export interface LaunchOverrides {* engine's own login has no such thing to say.*/gridLaunchRecord?: GridLaunchRecord+ /**+ * The `provider/model` a resumed OpenCode session has to be put on before this launch — OpenCode+ * restores a session's stored model whatever argv says. Present whenever the launch names one;+ * the caller applies it (`applyOpencodeSessionModel`).+ */+ sessionModel?: string}export type LaunchOverridesResult =@@ -166,9 +172,12 @@ export async function buildLaunchOverrides(// The named agent rides every relaunch, in the same argv slot `agent_create` put it in. Only an// engine with a contract could have had it recorded (create refuses the rest, AGENT_UNSUPPORTED),// so the guard is for a row edited by hand — it relaunches as a general session rather than- // handing the engine a flag it does not know.- if (source.agent && supportsNamedAgent(engine)) {- overrides = { ...overrides, extraArgs: [...overrides.extraArgs, ...namedAgentArgs(engine, source.agent)] }+ // handing the engine a flag it does not know. The same guard covers an opencode agent created on+ // v1 and relaunched on v2, whose TUI has no `--agent`: a resumed v2 session keeps the agent it+ // stored (`session_v2.agent`), so nothing is lost by not naming it.+ const opencodeMajor = deps.machine().opencodeMajor ?? null+ if (source.agent && supportsNamedAgent(engine, opencodeMajor)) {+ overrides = { ...overrides, extraArgs: [...overrides.extraArgs, ...namedAgentArgs(engine, source.agent, opencodeMajor)] }}return { ok: true, overrides: { ...overrides, clearEnv: [...overrides.clearEnv, ...harnessEnvToClear(overrides.env)] } }}@@ -196,7 +205,7 @@ async function buildBaseLaunchOverrides(// back on the DEFAULT profile, reading hooks from a folder that was not the one it writes to.let ownLogin: LaunchOverrides | null = nullif (!source.gridLaunch) {- const restored = subscriptionModelLaunch(engine, source.subscriptionModel)+ const restored = subscriptionModelLaunch(engine, source.subscriptionModel, deps.machine().opencodeMajor ?? null)// Ahead of the model on the command line: `-c` configures, `-m` selects, and Codex resolves the// model against the provider it has been given.const provider = ownLoginProviderArgs(engine, source.codexHome, { read: deps.readCodexConfig })@@ -205,6 +214,7 @@ async function buildBaseLaunchOverrides(env: { ...(restored?.env ?? {}) },extraArgs: [...provider, ...(restored?.args ?? [])],clearEnv: [],+ ...(restored?.sessionModel ? { sessionModel: restored.sessionModel } : {}),}}}@@ -232,6 +242,7 @@ async function buildBaseLaunchOverrides(extraArgs: [...built.launch.args],clearEnv: gridConflictingEnvToClear({ env }),gridLaunchRecord: { override: source.gridLaunch, webSearch: built.launch.webSearch },+ ...(built.launch.sessionModel ? { sessionModel: built.launch.sessionModel } : {}),},}}diff --git a/cli/src/lib/subscriptionModel.spec.ts b/cli/src/lib/subscriptionModel.spec.tsindex b16feb28c..06c14bcb3 100644--- a/cli/src/lib/subscriptionModel.spec.ts+++ b/cli/src/lib/subscriptionModel.spec.ts@@ -20,13 +20,22 @@ describe('subscriptionModelLaunch', () => {it('passes an OpenCode model only when it carries its provider', () => {expect(subscriptionModelLaunch('opencode', 'anthropic/claude-sonnet-4')).toEqual({- env: {}, args: ['-m', 'anthropic/claude-sonnet-4'],+ env: {}, args: ['-m', 'anthropic/claude-sonnet-4'], sessionModel: 'anthropic/claude-sonnet-4',})// A bare name has no provider this module could supply, and OpenCode would look for a model// that does not exist. Saying nothing leaves the engine to decide, which is the safe direction.expect(subscriptionModelLaunch('opencode', 'claude-sonnet-4')).toBeNull()})+ it('never passes -m to OpenCode v2, whose TUI has no such flag', () => {+ // The model is switched on the session instead (`applyOpencodeSessionModel`), so the launch+ // carries only the model to switch to.+ expect(subscriptionModelLaunch('opencode', 'anthropic/claude-sonnet-4', 2)).toEqual({+ env: {}, args: [], sessionModel: 'anthropic/claude-sonnet-4',+ })+ expect(subscriptionModelLaunch('opencode', 'claude-sonnet-4', 2)).toBeNull()+ })+it('says nothing for an engine with no cited mechanism', () => {// A guessed flag does not fail loudly: the engine starts and runs on a model nobody chose.expect(subscriptionModelLaunch('amp', 'some-model')).toBeNull()diff --git a/cli/src/lib/subscriptionModel.ts b/cli/src/lib/subscriptionModel.tsindex 14f569cf1..cbd40a561 100644--- a/cli/src/lib/subscriptionModel.ts+++ b/cli/src/lib/subscriptionModel.ts@@ -30,10 +30,13 @@* a regression, and it is recoverable by hand in the pane.*/import type { AgentEngine } from '../engines/types.js'+import { isOpencodeV2 } from '../engines/opencode/version.js'export interface SubscriptionModelLaunch {env: Record<string, string>args: string[]+ /** The `provider/model` a resumed session must be switched to first — see `GridEngineLaunch`. */+ sessionModel?: string}/**@@ -43,7 +46,7 @@ export interface SubscriptionModelLaunch {* that is about the model and not about the endpoint — so the two cannot drift into disagreeing* about how a model is named to an engine. See `GRID_ENGINE_CONTRACTS` in `gridLaunch.ts`.*/-const CONTRACTS: Partial<Record<AgentEngine, (model: string) => SubscriptionModelLaunch>> = {+const CONTRACTS: Partial<Record<AgentEngine, (model: string, opencodeMajor: number | null) => SubscriptionModelLaunch>> = {// Claude Code reads `ANTHROPIC_MODEL` and prefers it over the model stored on a resumed session,// which is precisely the stale value being displaced here. Same variable the grid contract sets.claude: (model) => ({ env: { ANTHROPIC_MODEL: model }, args: [] }),@@ -63,7 +66,12 @@ const CONTRACTS: Partial<Record<AgentEngine, (model: string) => SubscriptionMode// is one the engine itself reported, so it round-trips; a bare model name has no provider this// module could supply without inventing one, and OpenCode would look for a model that does not// exist. Absent provider ⇒ no argument, per the rule at the top of this file.- opencode: (model) => (model.includes('/') ? { env: {}, args: ['-m', model] } : { env: {}, args: [] }),+ // v2's TUI has no `-m` (it exits 1 on it); there the model is switched on the session before the+ // relaunch, through OpenCode's own API, and argv carries nothing.+ opencode: (model, opencodeMajor) => {+ if (!model.includes('/')) return { env: {}, args: [] }+ return { env: {}, args: isOpencodeV2(opencodeMajor) ? [] : ['-m', model], sessionModel: model }+ },}/** Engines that can be returned to a specific model. Everything else relaunches as it always did. */@@ -75,16 +83,18 @@ export function subscriptionModelEngines(): AgentEngine[] {* How to relaunch `engine` on its own login with `model` selected, or null when there is nothing* this module can say — an engine with no cited mechanism, or a model string it cannot use.*- * Null is a normal answer and never an error: the relaunch proceeds without it.+ * Null is a normal answer and never an error: the relaunch proceeds without it. `opencodeMajor` is+ * the installed OpenCode's major version (`engines/opencode/version.ts`); absent reads as v1.*/export function subscriptionModelLaunch(engine: AgentEngine,model: string | null | undefined,+ opencodeMajor: number | null = null,): SubscriptionModelLaunch | null {const chosen = model?.trim()if (!chosen) return nullconst build = CONTRACTS[engine]if (!build) return null- const launch = build(chosen)- return launch.args.length || Object.keys(launch.env).length ? launch : null+ const launch = build(chosen, opencodeMajor)+ return launch.args.length || Object.keys(launch.env).length || launch.sessionModel ? launch : null}