Skip to content

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.

cli: make an opencode model switch actually take effect

bitcoinbuilder6bf35695e323
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index c4b700042..9b45df0e0 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -60,7 +60,7 @@ import { ENGINE_CLI_COMMANDS, ENGINES, engineBin, enginePathOverride } from './l
import type { AgentEngine } from './engines/types.js'
import { engineInstallRecipe } from './lib/engineInstall.js'
import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell } from './lib/engineLaunch.js'
-import { buildGridEngineLaunch, describeGridLaunch, gridConflictingEnvToClear, gridEnvVarNames, type GridLaunchMachine, type GridWebSearchStatus } from './lib/gridLaunch.js'
+import { buildGridEngineLaunch, describeGridLaunch, gridConflictingEnvToClear, gridEnvVarNames, gridProviderId, type GridLaunchMachine, type GridWebSearchStatus } from './lib/gridLaunch.js'
import { HERMES_SYSTEM_MANAGED_DIR } from './lib/gridWebMcp.js'
import { writeGridConfigDir } from './lib/gridConfigDir.js'
import { tmuxSupportsSessionEnv, TMUX_SESSION_ENV_MIN } from './lib/tmuxVersion.js'
@@ -175,7 +175,7 @@ import { agentFrame, type AgentFrame } from './lib/agentFrame.js'
import { SessionInputController } from './lib/sessionInput.js'
import { adaptSlashCommand } from './lib/goalCommand.js'
import { RuntimeProfileManager, parseRuntimeProfile } from './lib/runtimeProfile.js'
-import { RuntimeProfileController, inspectRuntimePane } from './lib/runtimeProfileController.js'
+import { RuntimeProfileControlError, RuntimeProfileController, inspectRuntimePane } from './lib/runtimeProfileController.js'
import { deviceErrorText } from './lib/deviceErrors.js'
import { correlateAgentEvent, turnHeartbeatFrame } from './lib/agentEvent.js'
@@ -3974,6 +3974,41 @@ async function runForeground(session: AuthSession): Promise<void> {
? describeGridLaunch(session.engine, record.override, record.webSearch)
: `${session.engine} on its own login`
console.log(`${where} · retargeted ${sid(session.agentId)} · ${how}`)
+ // OpenCode's TUI drops `-m` when it RESUMES a session — it restores the model stored on that
+ // session instead — so the respawn above lands the right provider, key and argv on a pane that
+ // then answers on the OLD model. Nothing else here can tell: the process is correct, and only
+ // the engine's own footer says otherwise. Selecting through its `/models` picker is what makes
+ // the move real; see [RuntimeProfileController.selectOpencodeModel] for the measurements.
+ //
+ // Only on a RESUME, and only when a model was actually named: a fresh session takes `-m`, and
+ // with nothing named there is nothing to select — the engine's own default is the right answer.
+ //
+ // ⚠️ The picker needs a `provider/model` id, and a grid override carries the model BARE
+ // (`Qwen3.6-35B-A3B`) — the provider is derived from the network name, exactly as the `-m` this
+ // same launch passes derives it. Handing the bare id over refused instantly as MODEL_UNAVAILABLE,
+ // which read as "the grid is not serving it" for a grid that was serving it fine.
+ const selecting = session.engine === 'opencode' && outcome.resumed
+ ? (grid
+ ? (grid.model ? `${gridProviderId(grid.networkName)}/${grid.model}` : null)
+ : remembered)
+ : null
+ if (selecting) {
+ try {
+ await runtimeController.selectOpencodeModel(session, selecting)
+ } catch (err) {
+ // The move HAPPENED — the registry above records the process that is really running — so
+ // this reports what is true rather than pretending either way: the agent is where it was
+ // asked to go, on a model it was not asked to be on. Saying `ok` here is the failure this
+ // handler exists to refuse; it would read as a working switch and bill the wrong account.
+ const detail = err instanceof RuntimeProfileControlError ? err.code : String(err)
+ console.warn(`[grid] ${sid(session.agentId)} moved but could not select ${selecting} · ${detail}`)
+ return {
+ ok: false,
+ error: 'MODEL_SELECT_FAILED',
+ detail: `moved, but opencode stayed on its previous model (${detail}) — pick ${selecting} from /models in the pane`,
+ }
+ }
+ }
return { ok: true }
} finally {
release()
diff --git a/cli/src/engines/opencode/runtimeProfile.ts b/cli/src/engines/opencode/runtimeProfile.ts
index afb83fb11..bd23b888a 100644
--- a/cli/src/engines/opencode/runtimeProfile.ts
+++ b/cli/src/engines/opencode/runtimeProfile.ts
@@ -23,6 +23,18 @@ export interface OpencodeModelTarget {
model: string
/** What the picker filter is fed: model words, then provider words to disambiguate. */
filter: string
+ /**
+ * The model's words ALONE, for the render where the provider is not in the row to match against.
+ *
+ * OpenCode draws the provider into the row only when it needs to: with several providers connected
+ * a row reads `Big Pickle OpenCode Zen · Free`, but with one it is just `Big Pickle · Free` and
+ * the provider name appears only as the section heading above. Feeding [filter] to the second one
+ * matches NOTHING — measured on a live picker: `big pickle opencode` returned an empty list where
+ * `big pickle` returned the row. So the drive falls back to this, and the "exactly one row left"
+ * rule does the disambiguating instead: if only one model answers to the name, there is no second
+ * provider to confuse it with.
+ */
+ modelFilter: string
}
export interface OpencodePickerRow {
@@ -40,21 +52,42 @@ function squash(value: string): string {
return value.replace(/[^a-z0-9]+/gi, '').toLowerCase()
}
+/**
+ * One `provider/model` id as a picker target, or null when it is not that shape.
+ *
+ * Split out from [parseOpencodeModelsOutput] because a target is also needed for a model that
+ * `opencode models` never printed: a grid's provider is declared in a config file this daemon writes
+ * for ONE agent, so the grid's models exist in that pane's picker and nowhere else. The construction
+ * is identical either way — which is the point of sharing it, since a filter built by a second rule
+ * would drift from the one the picker was measured against.
+ */
+export function opencodeModelTarget(id: string): OpencodeModelTarget | null {
+ const trimmed = id.trim()
+ if (!/^[a-z0-9][\w.-]*\/[\w./-]+$/i.test(trimmed)) return null
+ const slash = trimmed.indexOf('/')
+ const provider = trimmed.slice(0, slash)
+ const model = trimmed.slice(slash + 1)
+ // The picker shows the model's LAST segment (`minimax/minimax-m3` renders as "MiniMax M3"), so the
+ // filter is built from that plus the provider.
+ const leaf = model.slice(model.lastIndexOf('/') + 1)
+ return {
+ id: trimmed,
+ provider,
+ model,
+ filter: `${words(leaf)} ${words(provider)}`.trim(),
+ modelFilter: words(leaf),
+ }
+}
+
/** Parse `opencode models`; anything that is not a `provider/model` line is ignored. */
export function parseOpencodeModelsOutput(output: string): OpencodeModelTarget[] {
const targets: OpencodeModelTarget[] = []
const seen = new Set<string>()
for (const rawLine of output.split('\n')) {
- const id = rawLine.trim()
- if (!/^[a-z0-9][\w.-]*\/[\w./-]+$/i.test(id) || seen.has(id)) continue
- seen.add(id)
- const slash = id.indexOf('/')
- const provider = id.slice(0, slash)
- const model = id.slice(slash + 1)
- // The picker shows the model's LAST segment (`minimax/minimax-m3` renders as "MiniMax M3"), so the
- // filter is built from that plus the provider.
- const leaf = model.slice(model.lastIndexOf('/') + 1)
- targets.push({ id, provider, model, filter: `${words(leaf)} ${words(provider)}`.trim() })
+ const target = opencodeModelTarget(rawLine)
+ if (!target || seen.has(target.id)) continue
+ seen.add(target.id)
+ targets.push(target)
}
return targets
}
@@ -94,10 +127,15 @@ export function countOpencodePickers(capture: string): number {
return capture.split('\n').filter((line) => /\bSelect model\b/.test(line)).length
}
-/** True when a picker row is the catalog entry we are trying to select. */
-export function opencodeRowMatches(target: OpencodeModelTarget, row: OpencodePickerRow): boolean {
+/** True when a picker row NAMES the target's model, whatever provider it is listed under. */
+export function opencodeRowNamesModel(target: OpencodeModelTarget, row: OpencodePickerRow): boolean {
const leaf = target.model.slice(target.model.lastIndexOf('/') + 1)
return squash(row.display).startsWith(squash(leaf))
+}
+
+/** True when a picker row is the catalog entry we are trying to select. */
+export function opencodeRowMatches(target: OpencodeModelTarget, row: OpencodePickerRow): boolean {
+ return opencodeRowNamesModel(target, row)
&& squash(`${row.display} ${row.provider}`).includes(squash(target.provider))
}
diff --git a/cli/src/lib/runtimeProfileController.spec.ts b/cli/src/lib/runtimeProfileController.spec.ts
index 6c675431c..f75090d46 100644
--- a/cli/src/lib/runtimeProfileController.spec.ts
+++ b/cli/src/lib/runtimeProfileController.spec.ts
@@ -14,14 +14,14 @@ import {
// The id inside a `runtime-v1:` string is the AGENT id ('h1' here) — a client only ever echoes back an id
// the catalog minted, and the catalog is agent-scoped. `setProfile` is still addressed with either id.
-function session(engine: 'claude' | 'codex' | 'cursor'): RegisteredSession {
+function session(engine: 'claude' | 'codex' | 'cursor' | 'opencode'): RegisteredSession {
return {
schemaVersion: 2,
active: true,
sessionId: 's1', engine, launcherId: 'h1', agentId: 'h1', boundAt: 0, transcriptPath: '/tmp/s1.jsonl', projectDir: 'tmp', cwd: '/tmp',
tmuxPane: '%1', source: null, title: null, model: null,
runtimes: [{ backend: 'tmux', paneId: '%1' }], primaryRuntimeKey: 'tmux\u0000%1',
- cliVersion: engine === 'codex' ? '0.144.5' : engine === 'cursor' ? '2026.07.20-8cc9c0b' : '2.1.212', processIdentity: null,
+ cliVersion: engine === 'codex' ? '0.144.5' : engine === 'cursor' ? '2026.07.20-8cc9c0b' : engine === 'opencode' ? '1.18.31' : '2.1.212', processIdentity: null,
registeredAt: 1, updatedAt: 1, lastHookAt: 1, lastTranscriptAt: 1,
}
}
@@ -78,6 +78,62 @@ describe('runtime pane parsing', () => {
)).toMatchObject({ idle: true, draft: false })
})
+ it('reads opencode past a card floating over its composer', () => {
+ // Copied off a live pane (2026-09-15). OpenCode's `Getting started` card is drawn on the RIGHT,
+ // which puts its text on the composer's own rows — a TUI paints one terminal row at a time, so
+ // anything floating over the box lands inside the box's lines. Reading to end-of-line took
+ // `Connect provider /connect` as something the user had typed, so an EMPTY composer read as a
+ // draft, the pane was never idle, and every model switch came back AGENT_BUSY.
+ const PANE = '\u001b[48;2;10;10;10m'
+ const BOX = '\u001b[48;2;30;30;30m'
+ const SIDEBAR = '\u001b[48;2;20;20;20m'
+ const BLUE = '\u001b[38;2;92;156;245m'
+ const WHITE = '\u001b[38;2;255;255;255m'
+ const row = (composer: string, card: string) =>
+ `${PANE} ${BLUE}┃${WHITE}${BOX}${composer.padEnd(40)}`
+ + `${PANE} ${SIDEBAR} ${BOX} \u001b[38;2;238;238;238m${card}`
+ const pane = (composer: readonly string[]) => [
+ ...composer.map((line) => row(line, 'Connect provider /connect')),
+ row(' Build · Big Pickle OpenCode Zen', ''),
+ ` ${BLUE}╹\u001b[38;2;30;30;30m▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀`,
+ ].join('\n')
+
+ expect(inspectRuntimePane('opencode', pane(['', '', '']))).toMatchObject({ idle: true, draft: false })
+ // The card must not be able to hide a draft either: text INSIDE the box still counts, on the
+ // very row the card writes into. Reading a real draft as an empty prompt respawns the engine
+ // under text the user typed — the one direction this must never be wrong in.
+ expect(inspectRuntimePane('opencode', pane(['', ' what changed in this repo', ''])))
+ .toMatchObject({ idle: false, draft: true })
+ })
+
+ it('reads OpenCode\'s grey placeholder as a placeholder, not a draft', () => {
+ // Copied off a live pane (1.18.31). The third placeholder styling this module has had to learn:
+ // claude/codex/devin draw dim, hermes draws italic, and OpenCode draws a plain TRUECOLOR GREY
+ // with neither attribute — so nothing recognised it and a BRAND-NEW pane read as one holding a
+ // draft. It was never idle, and every model switch on an agent with no messages yet refused as
+ // AGENT_BUSY over an empty composer.
+ const BOX = '\u001b[48;2;30;30;30m'
+ const PANE = '\u001b[48;2;10;10;10m'
+ const WHITE = '\u001b[38;2;255;255;255m'
+ const GREY = '\u001b[38;2;128;128;128m'
+ const pane = (composer: string) => [
+ ` \u001b[38;2;92;156;245m┃${WHITE}${BOX} ${composer}${WHITE} ${PANE}`,
+ ` \u001b[38;2;92;156;245m┃${WHITE}${BOX} \u001b[38;2;92;156;245mBuild${WHITE} ${GREY}·${WHITE} Big Pickle${PANE}`,
+ ' \u001b[38;2;92;156;245m╹\u001b[38;2;30;30;30m▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀',
+ ].join('\n')
+
+ expect(inspectRuntimePane('opencode', pane(`${GREY}Ask anything… "What is the tech stack of this project?"`)))
+ .toMatchObject({ idle: true, draft: false })
+ // ⚠️ The direction that must never be wrong: text the user typed is drawn in the composer's own
+ // near-white, and reading it as a placeholder would respawn the engine under a real draft.
+ expect(inspectRuntimePane('opencode', pane(`${WHITE}switch me please`)))
+ .toMatchObject({ idle: false, draft: true })
+ // A grey hint sitting BESIDE typed text does not make the line a placeholder — every visible
+ // character has to be muted, not merely some of them.
+ expect(inspectRuntimePane('opencode', pane(`${WHITE}fix the parser${GREY} ⏎ send`)))
+ .toMatchObject({ idle: false, draft: true })
+ })
+
it('reads copilot, whose composer carries no marker while its sent messages do', () => {
// Copied off a live pane. Copilot echoes every message the user has ALREADY SENT into the
// transcript as `❯ <text>` in full brightness, and draws its composer as a `┃` box that carries
@@ -284,6 +340,152 @@ describe('runtime pane parsing', () => {
})
describe('RuntimeProfileController', () => {
+ it('selects a grid model through OpenCode\'s own picker, which a resumed pane needs', async () => {
+ // OpenCode's TUI honours `-m` only when it STARTS a session; resuming one restores the model
+ // stored on that session and drops the flag. Measured on 1.18.31 outside the harness:
+ // opencode -m <grid>/Qwen3.6-35B-A3B → Build · Qwen3.6-35B-A3B <grid>
+ // opencode --session <id> -m <grid>/Qwen3.6-35B-A3B → Build · Big Pickle OpenCode Zen
+ // So a retarget landed the right provider, key and argv and the engine answered on the OLD
+ // model. The grid's models are in that pane's picker — the provider block is in the config the
+ // respawn points OPENCODE_CONFIG at — so the picker is what makes the move real.
+ const value = session('opencode')
+ const footer = (model: string) => ` ┃ Build · ${model}\n`
+ let model = 'Big Pickle OpenCode Zen'
+ let picker = ''
+ let filter = ''
+ const controller = new RuntimeProfileController({
+ manager: new RuntimeProfileManager(),
+ getSession: () => value,
+ validateRuntime: async () => true,
+ capture: async () => footer(model) + picker,
+ sendText: async (_pane, command) => {
+ // The picker lists BOTH the subscription model and the grid one, as the live pane does.
+ if (command === '/models') {
+ picker = [
+ 'Select model esc',
+ '● Big Pickle OpenCode Zen Free',
+ `Qwen3.6-35B-A3B ${'minhduccm90-cecb9724'}`,
+ 'Connect provider ctrl+a Favorite ctrl+f',
+ ].join('\n')
+ }
+ return true
+ },
+ sendLiteral: async (_pane, text) => {
+ filter = text
+ // Typing narrows it to the one row, which is the only state this drive ever acts on.
+ picker = [
+ 'Select model esc',
+ text,
+ `Qwen3.6-35B-A3B ${'minhduccm90-cecb9724'}`,
+ 'Connect provider ctrl+a Favorite ctrl+f',
+ ].join('\n')
+ return true
+ },
+ sendKey: async (_pane, key) => {
+ if (key === 'Enter') { model = 'Qwen3.6-35B-A3B minhduccm90-cecb9724'; picker = '' }
+ return true
+ },
+ acquireInput: () => () => {},
+ })
+
+ await expect(controller.selectOpencodeModel(value, 'minhduccm90-cecb9724/Qwen3.6-35B-A3B'))
+ .resolves.toBeUndefined()
+ // The filter is built from the model's last segment plus the provider, the same rule the
+ // subscription drive uses — a second rule here would drift from the one the picker was measured
+ // against.
+ expect(filter).toBe('qwen3.6 35b a3b minhduccm90 cecb9724')
+ expect(model).toBe('Qwen3.6-35B-A3B minhduccm90-cecb9724')
+ })
+
+ it('falls back to the model-only filter when a row carries no provider', async () => {
+ // Measured on a live picker with ONE provider connected: the row is bare (`Big Pickle · Free`),
+ // the provider name is only the heading above it, and `big pickle opencode` matches NOTHING while
+ // `big pickle` returns the row. This is the way HOME from a grid — the subscription model named
+ // here — and it refused with MODEL_UNAVAILABLE until the filter dropped its provider half.
+ const value = session('opencode')
+ let pane = ' ┃ Build · Qwen3.6-35B-A3B minhduccm90-cecb9724\n'
+ const filters: string[] = []
+ let chosen: string | null = null
+ const rowsFor = (filter: string) => (
+ // OpenCode's own matcher: the provider is not in the row, so a filter naming it finds nothing.
+ 'bigpickle'.startsWith(filter.replace(/[^a-z0-9]/g, '')) || filter.replace(/[^a-z0-9]/g, '') === 'bigpickle'
+ ? ['● Big Pickle Free']
+ : []
+ )
+ const controller = new RuntimeProfileController({
+ manager: new RuntimeProfileManager(),
+ getSession: () => value,
+ validateRuntime: async () => true,
+ capture: async () => pane,
+ sendText: async () => {
+ pane += '\nSelect model esc\nConnect provider ctrl+a'
+ return true
+ },
+ sendLiteral: async (_pane, text) => {
+ filters.push(text)
+ pane = pane.slice(0, pane.lastIndexOf('Select model'))
+ + ['Select model esc', text, ...rowsFor(text), 'Connect provider ctrl+a'].join('\n')
+ return true
+ },
+ sendKey: async (_pane, key) => {
+ if (key !== 'Enter') return true
+ chosen = 'opencode/big-pickle'
+ // Selecting repaints the footer, which is what the drive confirms from.
+ pane = ' ┃ Build · Big Pickle OpenCode Zen\n'
+ return true
+ },
+ acquireInput: () => () => {},
+ })
+
+ await controller.selectOpencodeModel(value, 'opencode/big-pickle')
+ // The qualified filter is tried FIRST — dropping it would lose the only thing that tells two
+ // same-named models apart when the provider IS rendered.
+ expect(filters).toEqual(['big pickle opencode', 'big pickle'])
+ expect(chosen).toBe('opencode/big-pickle')
+ }, 15_000)
+
+ it('refuses when OpenCode\'s picker never offers the grid model', async () => {
+ // The confirmation is read from the FOOTER, not from the manager's observed profile: that
+ // resolves what it sees against `opencode models`, which cannot list a provider written for one
+ // agent — so it would answer null for a switch that had actually worked.
+ const value = session('opencode')
+ // Scrollback ACCUMULATES, the way a real capture does: a closed picker stays on screen above, which
+ // is why the drive counts openings rather than asking whether one is open.
+ let pane = ' ┃ Build · Big Pickle OpenCode Zen\n'
+ let opens = 0
+ const picker = (filter: string) => [
+ 'Select model esc',
+ filter,
+ '● Big Pickle OpenCode Zen Free',
+ 'Connect provider ctrl+a Favorite ctrl+f',
+ ].join('\n')
+ const controller = new RuntimeProfileController({
+ manager: new RuntimeProfileManager(),
+ getSession: () => value,
+ validateRuntime: async () => true,
+ capture: async () => pane,
+ sendText: async () => {
+ // The picker opens, and the grid's provider is not in it — the config the respawn points at
+ // did not take, or the provider names no models.
+ opens += 1
+ pane += '\n' + picker('')
+ return true
+ },
+ sendLiteral: async (_pane, text) => {
+ pane = pane.slice(0, pane.lastIndexOf('Select model')) + picker(text)
+ return true
+ },
+ sendKey: async () => true,
+ acquireInput: () => () => {},
+ })
+
+ await expect(controller.selectOpencodeModel(value, 'minhduccm90-cecb9724/Qwen3.6-35B-A3B'))
+ .rejects.toMatchObject({ code: 'MODEL_UNAVAILABLE' })
+ // Both filters were tried — the provider-qualified one and the model-only fallback — before it gave
+ // up, and neither pressed Enter on a row that was not the target.
+ expect(opens).toBe(2)
+ })
+
it('sets Claude model and effort only after transcript confirmations', async () => {
const value = session('claude')
const manager = new RuntimeProfileManager()
diff --git a/cli/src/lib/runtimeProfileController.ts b/cli/src/lib/runtimeProfileController.ts
index 1002c3e39..6e17d9e56 100644
--- a/cli/src/lib/runtimeProfileController.ts
+++ b/cli/src/lib/runtimeProfileController.ts
@@ -5,8 +5,13 @@ import { parseHermesPickerPage } from '../engines/hermes/runtimeProfile.js'
import { parsePiFooterProfile, parsePiThinkingSelection, piThinkingSteps } from '../engines/pi/runtimeProfile.js'
import {
countOpencodePickers,
+ opencodeModelTarget,
opencodeRowMatches,
+ opencodeRowNamesModel,
+ parseOpencodeFooter,
parseOpencodePickerRows,
+ type OpencodeModelTarget,
+ type OpencodePickerRow,
} from '../engines/opencode/runtimeProfile.js'
import {
codexEffortAllowed,
@@ -24,6 +29,16 @@ const PICKER_STEP_MS = 2_000
const PI_LADDER_MAX_STEPS = 14
/** Hermes' longest picker page is a provider's model list; twice its size still terminates. */
const HERMES_PAGE_MAX_STEPS = 60
+/**
+ * How long a freshly respawned OpenCode TUI gets to draw its composer before the model is selected.
+ * Generous next to the picker steps because this one spans a process start, not a keystroke.
+ */
+const OPENCODE_BOOT_MS = 20_000
+
+/** Compare model names the way OpenCode's own picker matcher does — punctuation and case are noise. */
+function squashModel(value: string): string {
+ return value.replace(/[^a-z0-9]+/gi, '').toLowerCase()
+}
/** "Anthropic (13 models)" names provider key `anthropic`; "GitHub Copilot (17 models)" names `copilot`. */
function hermesProviderMatches(row: string, provider: string): boolean {
@@ -94,6 +109,79 @@ function sgrAttributes(params: readonly string[]): string[] {
return attributes
}
+/**
+ * The background an SGR sequence sets, as a comparable string — or null if it sets none.
+ *
+ * Needed because a composer box is identified by the colour it PAINTS, and the parameters that
+ * choose one are positional: `48;5;<n>` and `48;2;<r>;<g>;<b>` carry their arguments inline, so the
+ * arguments have to be consumed rather than read as further attributes. `38`/`58` are skipped the
+ * same way for the same reason — a truecolor FOREGROUND ends in numbers that would otherwise parse
+ * as a background code of their own.
+ *
+ * SGR 0 counts: a reset puts the default background back, which is a change like any other.
+ */
+function sgrBackground(params: readonly string[]): string | null {
+ for (let index = 0; index < params.length; index += 1) {
+ const code = params[index]
+ if (code === '48') {
+ const kind = params[index + 1]
+ return params.slice(index, index + (kind === '5' ? 3 : kind === '2' ? 5 : 2)).join(';')
+ }
+ if (code === '49' || /^(?:4[0-7]|10[0-7])$/.test(code)) return code
+ if (code === '0' || code === '') return '49'
+ if (code === '38' || code === '58') {
+ const kind = params[index + 1]
+ index += kind === '5' ? 2 : kind === '2' ? 4 : 1
+ }
+ }
+ return null
+}
+
+/**
+ * The span of a gutter line the BOX ITSELF paints — everything after the marker was wrong.
+ *
+ * A TUI draws one row of the terminal at a time, so anything floating OVER the composer lands on the
+ * composer's own lines. OpenCode's `Getting started` card is exactly that: a panel on the right-hand
+ * side, and its rows are written after the composer's on the same lines. Reading to end-of-line took
+ * the card's text as something the user had typed —
+ *
+ * ┃ <121 spaces of composer> <sidebar> Connect provider /connect
+ *
+ * so `draft` was true over an EMPTY composer, the pane never read idle, and every model switch came
+ * back AGENT_BUSY. Measured on a live pane (`harness-opencode-*`, 2026-09-15) with nothing typed in.
+ * Fourth variant of the family above: the marker is found, the strip is dropped, and then the wrong
+ * COLUMNS are read.
+ *
+ * The boundary is the box's own background. Everything a box paints is painted in it, so the
+ * interior runs from the background set right after the marker to the next background change — in
+ * the capture above, back to the pane's `48;2;10;10;10` where the box ends and the sidebar begins.
+ *
+ * Two deliberate conservatisms, both pointing the same way — a real draft must never be read as an
+ * empty prompt, because that respawns the engine under text the user typed:
+ * * A background that appears only AFTER visible text is not the interior's. It is a highlight
+ * drawn mid-draft, and treating it as the boundary would cut the draft off at its own styling.
+ * * A line that sets no background at all is not clipped. Plain-text panes (and every engine that
+ * paints no box) keep the whole line, exactly as before.
+ */
+function gutterBoxInterior(line: string, markerIndex: number): string {
+ const after = line.slice(markerIndex + 1)
+ const sgr = /\u001b\[([0-9;:]*)m/g
+ let interior: string | null = null
+ let end = after.length
+ let match: RegExpExecArray | null
+ while ((match = sgr.exec(after)) !== null) {
+ const background = sgrBackground(match[1].split(/[;:]/))
+ if (background === null) continue
+ if (interior === null) {
+ if (stripAnsi(after.slice(0, match.index)).trim().length > 0) break
+ interior = background
+ continue
+ }
+ if (background !== interior) { end = match.index; break }
+ }
+ return after.slice(0, end)
+}
+
/**
* Is the text after the composer marker the PLACEHOLDER, rather than something the user typed?
*
@@ -117,6 +205,81 @@ function hasPlaceholderSgr(value: string): boolean {
})
}
+/**
+ * Is this SGR foreground a MUTED one — the grey a TUI writes hints and placeholders in?
+ *
+ * Returns null when the sequence sets no foreground, so a caller can keep the colour already in
+ * effect rather than treating "no change" as a change.
+ *
+ * Grey is judged by the colour itself: equal channels, and dark enough to read as secondary next to
+ * the near-white a composer draws real text in. OpenCode's placeholder is `38;2;128;128;128` and its
+ * own text `38;2;255;255;255`; the 256-colour ramp (232–255) and SGR 90 are the same intent spelled
+ * differently.
+ */
+function sgrMutedForeground(params: readonly string[]): boolean | null {
+ for (let index = 0; index < params.length; index += 1) {
+ const code = params[index]
+ if (code === '38') {
+ const kind = params[index + 1]
+ if (kind === '2') {
+ const [r, g, b] = [params[index + 2], params[index + 3], params[index + 4]].map(Number)
+ if (![r, g, b].every(Number.isFinite)) return null
+ return r === g && g === b && r >= 0x40 && r <= 0xb0
+ }
+ if (kind === '5') {
+ const n = Number(params[index + 2])
+ if (!Number.isFinite(n)) return null
+ // 8 is bright black; 232–255 is the grey ramp, whose middle is the secondary tone.
+ return n === 8 || (n >= 236 && n <= 250)
+ }
+ return null
+ }
+ if (code === '90') return true
+ if (code === '39' || code === '0' || code === '') return false
+ if (/^(?:3[0-7]|9[1-7])$/.test(code)) return false
+ if (code === '48' || code === '58') {
+ const kind = params[index + 1]
+ index += kind === '5' ? 2 : kind === '2' ? 4 : 1
+ }
+ }
+ return null
+}
+
+/**
+ * Is EVERY visible character here written in a muted colour — i.e. is this a hint rather than a draft?
+ *
+ * The third placeholder styling this module has had to learn, after dim (claude, codex, devin) and
+ * italic (hermes). OpenCode draws `Ask anything… "What is the tech stack of this project?"` as a plain
+ * TRUECOLOR GREY with no dim and no italic attribute at all, so [hasPlaceholderSgr] saw nothing and a
+ * brand-new pane read as a pane with a draft in it: never idle, and every model switch on an agent
+ * with no messages yet refused as AGENT_BUSY over an empty composer. Measured on 1.18.31.
+ *
+ * ⚠️ EVERY character, not any — which is what keeps this from swallowing a real draft. A composer
+ * writes what the user typed in its normal near-white; one such character anywhere means this is
+ * text, whatever grey hint may be sitting beside it. Spaces are not evidence of either and carry no
+ * colour worth reading, so they are skipped.
+ */
+function allVisibleTextIsMuted(value: string): boolean {
+ const sgr = /\u001b\[([0-9;:]*)m/g
+ let muted: boolean | null = null
+ let cursor = 0
+ let sawText = false
+ let match: RegExpExecArray | null
+ const segment = (text: string): boolean => {
+ if (!text.trim()) return true
+ sawText = true
+ return muted === true
+ }
+ while ((match = sgr.exec(value)) !== null) {
+ if (!segment(value.slice(cursor, match.index))) return false
+ const next = sgrMutedForeground(match[1].split(/[;:]/))
+ if (next !== null) muted = next
+ cursor = match.index + match[0].length
+ }
+ if (!segment(value.slice(cursor))) return false
+ return sawText
+}
+
function interactionText(capture: string): string {
const lines = capture.split('\n')
const promptIndex = lines.findLastIndex((line) => {
@@ -230,8 +393,14 @@ function inspectGutterBoxPane(capture: string, hasStatusStrip: boolean): PaneIns
const visibleMarker = stripAnsi(line).search(marks)
if (visibleMarker < 0) return false
const rawMarker = line.search(marks)
- if (rawMarker >= 0 && hasPlaceholderSgr(line.slice(rawMarker + 1))) return false
- return stripAnsi(line).slice(visibleMarker + 1).replace(/\u00a0/g, ' ').trim().length > 0
+ // The box's interior, not the rest of the row: a panel floating over the composer writes into
+ // these same lines, and its text is not a draft. See [gutterBoxInterior]. With no marker in the
+ // RAW line there is no interior to bound — read the whole row, the direction that keeps a draft.
+ const interior = rawMarker < 0
+ ? stripAnsi(line).slice(visibleMarker + 1)
+ : gutterBoxInterior(line, rawMarker)
+ if (hasPlaceholderSgr(interior) || allVisibleTextIsMuted(interior)) return false
+ return stripAnsi(interior).replace(/\u00a0/g, ' ').trim().length > 0
})
return { idle: !dialog && !draft, plan: /\bplan mode on\b/i.test(currentUi), dialog, draft }
}
@@ -749,9 +918,97 @@ export class RuntimeProfileController {
* same model name) the switch is refused rather than guessed — picking the wrong model silently is worse
* than not switching, and blind arrow-driving is what sank the Command Code attempt.
*/
+ /**
+ * Put a RESUMED OpenCode pane on an exact `provider/model`, through OpenCode's own picker.
+ *
+ * ## Why a pane that was just launched with `-m` needs this at all
+ *
+ * OpenCode's TUI honours `-m` only when it STARTS a session. Resuming one (`--session <id>`, which
+ * is how a retarget keeps the conversation) restores the model stored on that session and the flag
+ * is dropped. Measured on 1.18.31, outside the harness, against the same config file this daemon
+ * writes:
+ *
+ * opencode -m <grid>/Qwen3.6-35B-A3B → `Build · Qwen3.6-35B-A3B <grid>` ✅
+ * opencode --session <id> -m <grid>/Qwen3.6-35B-A3B → `Build · Big Pickle OpenCode Zen` ❌
+ * opencode run --session <id> -m <model> → honoured ✅ (a different command)
+ *
+ * A top-level `"model"` in the config file loses to the stored model the same way. So the move
+ * landed — right provider, right key, right argv — and the engine answered on the OLD model, which
+ * is the failure this whole module exists to prevent: it looks like it worked, and it bills the
+ * wrong account.
+ *
+ * The grid's models ARE in that pane's picker, because the provider block naming them is in the
+ * config the respawn points `OPENCODE_CONFIG` at. So the same `/models` drive [setOpencode] uses
+ * for a subscription model selects a grid one, and this is that drive with the catalogue check
+ * removed — the catalogue is `opencode models`, which cannot know about a provider written for one
+ * agent.
+ *
+ * ⚠️ The caller must ALREADY hold this pane's input. This types into the pane and does not take the
+ * lock itself, because the only caller is mid-retarget and is holding it for the respawn.
+ */
+ async selectOpencodeModel(session: RegisteredSession, id: string): Promise<void> {
+ const entry = opencodeModelTarget(id)
+ if (!entry) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
+ // A pane that has just been respawned is still drawing. Typing `/models` into a TUI that has not
+ // put its composer up yet loses the keystrokes — or worse, lands them somewhere else — so wait
+ // for the footer, which is the first thing that proves the composer is live.
+ if (!await this.waitPane(session.agentId, (v) => parseOpencodeFooter(stripAnsi(v)) !== null, OPENCODE_BOOT_MS)) {
+ throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
+ }
+ await this.driveOpencodePicker(session, entry)
+ // Confirmed from the footer rather than from the manager's observed profile: the manager resolves
+ // what it sees against `opencode models`, and a grid model is not in it — so its answer would be
+ // null here for a switch that actually worked.
+ const leaf = entry.model.slice(entry.model.lastIndexOf('/') + 1)
+ const landed = await this.waitPane(session.agentId, (v) => {
+ const footer = parseOpencodeFooter(stripAnsi(v))
+ return !!footer && squashModel(footer.target).startsWith(squashModel(leaf))
+ }, COMMAND_CONFIRM_MS)
+ if (!landed) throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
+ }
+
private async setOpencode(session: RegisteredSession, target: RuntimeProfile): Promise<void> {
const entry = (await this.deps.manager.opencodeCatalog()).find((item) => item.id === target.model)
if (!entry) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
+ await this.driveOpencodePicker(session, entry)
+ if (!await this.waitObservedProfile(session, target)) {
+ throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
+ }
+ }
+
+ /**
+ * `/models`, filter, act only once exactly one row is left. Shared by both OpenCode callers.
+ *
+ * Two attempts, because one filter does not fit both renders. With several providers connected a
+ * row carries its provider (`Big Pickle OpenCode Zen`) and the provider-qualified filter is what
+ * tells two same-named models apart; with one provider the row is bare (`Big Pickle`) and that same
+ * filter matches NOTHING. Measured on a live picker: `big pickle opencode` → empty, `big pickle` →
+ * the row.
+ *
+ * The fallback drops only the PROVIDER half, never the "exactly one row" rule — which is what makes
+ * it safe: if one model answers to the name, there is no second provider to confuse it with, and if
+ * two do, the list does not narrow and this refuses rather than guessing.
+ */
+ private async driveOpencodePicker(session: RegisteredSession, entry: OpencodeModelTarget): Promise<void> {
+ if (await this.pickOpencodeRow(session, entry, entry.filter, opencodeRowMatches)) return
+ if (entry.modelFilter === entry.filter) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
+ if (!await this.pickOpencodeRow(session, entry, entry.modelFilter, opencodeRowNamesModel)) {
+ throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
+ }
+ }
+
+ /**
+ * One attempt at the picker: open it, type `filter`, and press Enter only if exactly one row is left
+ * AND `matches` accepts it. Returns false — with the picker CLOSED — when the list did not narrow to
+ * a row this may act on, so the caller can try a different filter on a pane in its resting state.
+ * Throws only for the states no retry can help: tmux refusing input, or the picker never opening.
+ */
+ private async pickOpencodeRow(
+ session: RegisteredSession,
+ entry: OpencodeModelTarget,
+ filter: string,
+ matches: (target: OpencodeModelTarget, row: OpencodePickerRow) => boolean,
+ ): Promise<boolean> {
// "Is a picker open?" cannot be asked of a capture that carries scrollback — an EARLIER picker is
// still up there, so the check passes before this one opens and the filter would be typed into the
// composer and submitted as a message. Count the openings instead and wait for one more.
@@ -766,7 +1023,7 @@ export class RuntimeProfileController {
)) {
throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
}
- if (!await this.deps.sendLiteral(session.agentId, entry.filter)) {
+ if (!await this.deps.sendLiteral(session.agentId, filter)) {
throw new RuntimeProfileControlError('TMUX_FAILED')
}
const narrowed = await this.waitPane(
@@ -775,15 +1032,16 @@ export class RuntimeProfileController {
PICKER_STEP_MS,
)
const rows = narrowed ? parseOpencodePickerRows(stripAnsi(narrowed)) ?? [] : []
- if (rows.length !== 1 || !opencodeRowMatches(entry, rows[0])) {
- throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
+ if (rows.length !== 1 || !matches(entry, rows[0])) {
+ // Leave the pane as it was found. A picker left open with a dead filter in it swallows whatever
+ // the user types next, and the retry below would type its filter on top of this one.
+ await this.deps.sendKey(session.agentId, 'Escape')
+ return false
}
if (!await this.deps.sendKey(session.agentId, 'Enter')) {
throw new RuntimeProfileControlError('TMUX_FAILED')
}
- if (!await this.waitObservedProfile(session, target)) {
- throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
- }
+ return true
}
/**