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
feat(cli): coming back off a grid returns the agent to its own model
bitcoinbuildere39557b4f5d6
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 17cb264a5..0a7bd48e8 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -3804,8 +3804,22 @@ async function runForeground(session: AuthSession): Promise<void> {// validate, and respawning over a pane whose occupant we cannot identify is how you replace// something that was not ours.if (!session.processIdentity) return { ok: false, error: 'NO_ACTIVE_PROCESS' }+ // Leaving for a grid is the LAST moment this agent's own model is observable: once the pane is on+ // the grid, the engine reports the grid's model and the previous choice exists nowhere. So it is+ // read now and kept, and a later move back returns the person to it rather than to whatever+ // default the engine would otherwise fall to. Read from the live engine, not from the row.+ //+ // Coming back reads what was kept. Not cleared on the way home: an agent bounced between a grid+ // and its own login should land on the same model every time, not only the first.+ const remembered = grid+ ? (runtimeProfiles.selectedModel(session) ?? null)+ : (session.subscriptionModel ?? null)// What this machine cannot do at all is said first, before the pane is even looked at.- const target: LaunchSource = { gridLaunch: grid, codexHome: session.codexHome }+ const target: LaunchSource = {+ gridLaunch: grid,+ codexHome: session.codexHome,+ ...(grid ? {} : { subscriptionModel: remembered }),+ }const valid = await validateLaunchOverrides(launchOverridesDeps, session.engine, target)if (!valid.ok) return { ok: false, error: valid.error, detail: valid.detail }// Mid-turn is the one state where restarting costs real work: the conversation comes back but@@ -3875,6 +3889,10 @@ async function runForeground(session: AuthSession): Promise<void> {registry.updateProcessIdentity(session.agentId, outcome.processIdentity, gateway.kind, assignment)// The launch that just worked is the one a restart or a post-reboot restore must repeat.registry.setGridLaunch(session.agentId, grid)+ // Persisted only on the way OUT, and only once the move actually succeeded — a refused move+ // must not overwrite the model the agent is still sitting on. Survives a daemon restart, so an+ // agent left on a grid for a week still knows where it came from.+ if (grid && remembered) registry.setSubscriptionModel(session.agentId, remembered)registry.setActive(session.agentId, true)await clearPaneRemainOnExit(pane.paneId)const refreshed = registry.byAgent(session.agentId)diff --git a/cli/src/lib/launchOverrides.spec.ts b/cli/src/lib/launchOverrides.spec.tsindex 87e3ed5a2..057973fd5 100644--- a/cli/src/lib/launchOverrides.spec.ts+++ b/cli/src/lib/launchOverrides.spec.ts@@ -87,3 +87,33 @@ describe('buildLaunchOverrides — a relaunch comes back where the agent was', (}})})++describe('buildLaunchOverrides — coming back off a grid', () => {+ it('re-selects the model the agent was on before it left', async () => {+ // Without this the engine restores the model its OWN session file remembers — the grid's — fails+ // to resolve it, and falls back to a house default. Measured on Claude Code: "Session model+ // Qwen3.6-35B-A3B-UD-Q5_K_XL could not be restored … using opus instead."+ const result = await buildLaunchOverrides(deps().d, 'claude', { subscriptionModel: 'opus' }, 'a')+ expect(result).toMatchObject({ ok: true, overrides: { env: { ANTHROPIC_MODEL: 'opus' } } })+ })++ it('uses argv for an engine whose interactive CLI resolves the model there', async () => {+ const result = await buildLaunchOverrides(deps().d, 'codex', { subscriptionModel: 'gpt-5-codex' }, 'a')+ expect(result).toMatchObject({ ok: true, overrides: { extraArgs: ['-m', 'gpt-5-codex'] } })+ })++ it('adds nothing when there is no model to come back to', async () => {+ const result = await buildLaunchOverrides(deps().d, 'claude', {}, 'a')+ expect(result).toMatchObject({ ok: true, overrides: { env: {}, extraArgs: [] } })+ })++ it('never lets a remembered model reach a GRID launch — that launch names its own', async () => {+ const result = await buildLaunchOverrides(+ deps().d, 'claude', { gridLaunch: GRID, subscriptionModel: 'opus' }, 'a',+ )+ expect(result.ok).toBe(true)+ if (!result.ok) return+ // The grid's model, not the remembered one.+ expect(result.overrides.env.ANTHROPIC_MODEL).toBe('gpt-5')+ })+})diff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.tsindex e9544e6a6..ff622b234 100644--- a/cli/src/lib/launchOverrides.ts+++ b/cli/src/lib/launchOverrides.ts@@ -14,6 +14,7 @@import { join } from 'node:path'import type { AgentEngine } from '../engines/types.js'+import { subscriptionModelLaunch } from './subscriptionModel.js'import {buildGridEngineLaunch,gridConflictingEnvToClear,@@ -53,6 +54,13 @@ export interface LaunchOverridesDeps {export interface LaunchSource {gridLaunch?: GridLaunchOverride | nullcodexHome?: string | null+ /**+ * The engine's OWN model to come back to, when this relaunch is a move off a grid.+ *+ * Ignored while `gridLaunch` is set — that launch names its own model. Absent means "let the+ * engine decide", which is what happens for an engine with no cited mechanism.+ */+ subscriptionModel?: string | null}/** Fresh each time: callers hand `env` to tmux and may extend it, and a shared object would carry@@ -101,6 +109,23 @@ export async function buildLaunchOverrides(): Promise<LaunchOverridesResult> {const valid = await validateLaunchOverrides(deps, engine, source)if (!valid.ok) return valid+ if (!source.gridLaunch) {+ // Coming back to the engine's own login: re-select the model this agent was on before it left,+ // so the engine does not fall back to a house default. See `subscriptionModel.ts` for why an+ // engine with no cited mechanism is given nothing rather than a guess.+ const restored = subscriptionModelLaunch(engine, source.subscriptionModel)+ if (restored) {+ const base = noOverrides()+ return {+ ok: true,+ overrides: {+ ...base,+ env: { ...base.env, ...restored.env },+ extraArgs: [...base.extraArgs, ...restored.args],+ },+ }+ }+ }if (source.gridLaunch) {const built = buildGridEngineLaunch(engine, source.gridLaunch)if (!built.ok) return { ok: false, error: built.error, detail: built.detail }diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex aba34e4d8..db008a0d6 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -111,6 +111,16 @@ export interface RegisteredSession {* treats as "grid agent without a credential".*/gridLaunch?: GridLaunchOverride | null+ /**+ * The engine's OWN model this agent was on immediately before it moved to a grid.+ *+ * Captured at the moment of leaving, because that is the only moment it is still observable: once+ * the pane is on a grid, the engine reports the GRID's model and the previous one exists nowhere.+ * Re-selected when the agent moves back, so coming home does not mean landing on whatever default+ * the vendor would otherwise pick. Null when the agent has never left, or was on no particular+ * model when it did.+ */+ subscriptionModel?: string | null/*** The CODEX_HOME folder this agent was launched against, if one was chosen instead of `~/.codex`.* Codex only. Unlike `grid`, this is chosen once at creation and never re-derived from the live@@ -1344,6 +1354,17 @@ class Registry {return true}+ /** Remember the engine's own model an agent is leaving behind, so a later move back can restore it.+ * Kept even while the agent is on a grid — it is the only record that the previous choice existed. */+ setSubscriptionModel(agentId: string, model: string | null): boolean {+ const session = this.agents.get(agentId)+ if (!session) return false+ session.subscriptionModel = model+ session.updatedAt = Date.now()+ this.save()+ return true+ }+touchTranscript(sessionId: string, at = Date.now()): boolean {const session = this.bySession(sessionId)if (!session) return falsediff --git a/cli/src/lib/subscriptionModel.spec.ts b/cli/src/lib/subscriptionModel.spec.tsnew file mode 100644index 000000000..5be3526ef--- /dev/null+++ b/cli/src/lib/subscriptionModel.spec.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest'+import { subscriptionModelLaunch, subscriptionModelEngines } from './subscriptionModel.js'++/**+ * The point of this module is that coming back from a grid returns a person to the model they were+ * on — so what is pinned here is the MECHANISM per engine, and the refusal to invent one.+ */+describe('subscriptionModelLaunch', () => {+ it('gives Claude Code the variable it prefers over a resumed session’s model', () => {+ // The stale session model is exactly what produced "could not be restored — using opus instead".+ expect(subscriptionModelLaunch('claude', 'opus')).toEqual({ env: { ANTHROPIC_MODEL: 'opus' }, args: [] })+ })++ it('gives Codex and Hermes argv, because their interactive CLIs resolve the model there', () => {+ expect(subscriptionModelLaunch('codex', 'gpt-5-codex')).toEqual({ env: {}, args: ['-m', 'gpt-5-codex'] })+ // Hermes reads `-m` then config.yaml with NO environment tier for this surface, so setting+ // HERMES_INFERENCE_MODEL here would be ignored by the pane it is meant to steer.+ expect(subscriptionModelLaunch('hermes', 'GLM-4.7-Flash')).toEqual({ env: {}, args: ['-m', 'GLM-4.7-Flash'] })+ })++ 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'],+ })+ // 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('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()+ expect(subscriptionModelLaunch('devin', 'some-model')).toBeNull()+ })++ it('treats an absent or blank model as nothing to restore', () => {+ expect(subscriptionModelLaunch('claude', null)).toBeNull()+ expect(subscriptionModelLaunch('claude', ' ')).toBeNull()+ expect(subscriptionModelLaunch('claude', undefined)).toBeNull()+ })++ it('only claims engines it can actually steer', () => {+ expect(subscriptionModelEngines().sort()).toEqual(['claude', 'codex', 'hermes', 'opencode'])+ })+})diff --git a/cli/src/lib/subscriptionModel.ts b/cli/src/lib/subscriptionModel.tsnew file mode 100644index 000000000..14f569cf1--- /dev/null+++ b/cli/src/lib/subscriptionModel.ts@@ -0,0 +1,90 @@+/**+ * Putting an agent back on its own login, ON THE MODEL IT WAS USING BEFORE.+ *+ * Moving an agent to a grid and back is not symmetric, and the asymmetry is invisible until you do+ * it. Going TO a grid sets the endpoint AND the model. Coming back clears both — and the engine then+ * restores whatever its OWN session file remembers, which is the grid's model. Measured on Claude+ * Code: after a switch back it said+ *+ * Session model Qwen3.6-35B-A3B-UD-Q5_K_XL could not be restored (not a model this version of+ * Claude Code recognizes) — using opus instead.+ *+ * The engine picked a house default, which is the one thing the harness must not let it do on the+ * user's behalf: the person had a model before, and coming back should return them to it rather+ * than to whatever the vendor considers reasonable. So the model in use is remembered when an agent+ * leaves for a grid, and re-selected when it comes back.+ *+ * ## Why this is its own table rather than a flag on the grid contract+ *+ * A grid launch answers "where do requests go, with which credential, for which model". This answers+ * only the last third, against the vendor's own endpoint. They share no fields, and the mechanisms+ * genuinely differ per engine — Claude Code reads an environment variable while Codex and Hermes+ * resolve the interactive CLI's model from argv.+ *+ * ## An engine with no entry gets nothing, deliberately+ *+ * The alternative to a cited mechanism is a guessed one, and a guessed model flag does not fail+ * loudly: the engine starts, ignores what it did not understand, and runs on a model the person did+ * not choose — which is the exact failure this module exists to remove. So an engine absent from+ * this table relaunches the way it always did, and the engine picks. That is today's behaviour, not+ * a regression, and it is recoverable by hand in the pane.+ */+import type { AgentEngine } from '../engines/types.js'++export interface SubscriptionModelLaunch {+ env: Record<string, string>+ args: string[]+}++/**+ * How each engine is told which of its OWN models to use, on its own login.+ *+ * Every entry is the same mechanism the grid contract uses for that engine's model — the part of it+ * 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>> = {+ // 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: [] }),++ // Codex resolves its model from argv; `-m` is what the grid contract passes, and it means the same+ // thing without a provider block beside it.+ codex: (model) => ({ env: {}, args: ['-m', model] }),++ // Hermes' INTERACTIVE cli resolves `-m` then config.yaml, with no environment tier at all+ // (`cli.py:_init_model_and_provider`, "Priority: CLI args > config"), and `--resume` otherwise+ // restores the model stored on the session row unless argv carried one. So argv — NOT+ // `HERMES_INFERENCE_MODEL`, which the grid contract sets for a different surface and which this+ // pane would ignore. The distinction is documented at length in `gridLaunch.ts`'s hermes entry.+ hermes: (model) => ({ env: {}, args: ['-m', model] }),++ // OpenCode's `-m` wants a `provider/model` pair. A remembered value that already carries a slash+ // 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: [] }),+}++/** Engines that can be returned to a specific model. Everything else relaunches as it always did. */+export function subscriptionModelEngines(): AgentEngine[] {+ return Object.keys(CONTRACTS) as 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.+ */+export function subscriptionModelLaunch(+ engine: AgentEngine,+ model: string | null | undefined,+): SubscriptionModelLaunch | null {+ const chosen = model?.trim()+ if (!chosen) return null+ const build = CONTRACTS[engine]+ if (!build) return null+ const launch = build(chosen)+ return launch.args.length || Object.keys(launch.env).length ? launch : null+}