Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(agents): add model gateway switcher

Darren Kattancfca0843094e
diff --git a/CLAUDE.md b/CLAUDE.md
index 89c15ce55..b3539a390 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -656,7 +656,7 @@ persisted — only `unread`/`session`/`sessionId` go to localStorage under
`AGENT_HOOK_TARGETS`, `RESUMABLE_AGENTS`, `SUBAGENT_CAPABLE`, `RECURRING_CAPABLE`,
`BRANCH_CAPABLE`, `CONTEXT_LINK_CAPABLE`, `USAGE_CAPABLE`, `CHAT_CAPABLE`,
`TRANSFER_SOURCE_CAPABLE`, `RENAME_CAPABLE`, `TITLE_READ_CAPABLE`, `CANVAS_CONTROL_CAPABLE`,
- `PERMISSION_MODE_CAPABLE`, with helpers (`hasHooks`,
+ `PERMISSION_MODE_CAPABLE`, `MODEL_SWITCH_CAPABLE`, with helpers (`hasHooks`,
`canBranch`, `canContextLink`, `canChat`, `canRename`, `canReadTitle`, `hasPermissionMode`, …).
Branch and the ⌘M **ChatPanel** transcript view (`CHAT_CAPABLE` / `canChat` — since the SDK chat
node was removed, 2026-07, this is all `canChat` now gates) stay **Claude-only** purely by
@@ -673,6 +673,20 @@ persisted — only `unread`/`session`/`sessionId` go to localStorage under
**`docs/grok-agent.md`**, **`docs/gemini-agent.md`** (there is none for codex — its approval mapping
and every value's reasoning live in `src/shared/agents/approval-mode.ts`);
the distilled rules are **Adding a new agent** at the end of this section.
+- **Model gateway / switcher** — `settings.modelGateway` stores one Bifrost-compatible root +
+ virtual key; `shared/agents/model-gateway.ts` is the ONE mapping from a base harness to derived
+ routes, env vars, compatible models and safely quoted model flags. It derives `/v1/models`,
+ `/openai/v1` and `/anthropic`; discovery runs in core (`agent:discover-models`) so browser CORS
+ cannot block the Server Edition and the key never enters a terminal command. Support is a
+ capability (`MODEL_SWITCH_CAPABLE = claude/codex`) resolved through `capabilityAgentId`, so a
+ custom agent with a supported `baseAgent` inherits it automatically — the settings UI and canvas
+ menu carry no agent allowlist. A model switch cleanly exits the CLI and RECYCLES the tmux session
+ before cold-resume: an existing shell may predate the gateway setting, and tmux env changes do
+ not retroactively change that shell's environment. Recreating it guarantees the current URL/key
+ applies without typing a secret into the pane. Ordinary Restart stays in-place. Custom-agent env
+ is still merged last and may override the shared mapping. Desktop and Server Edition use the
+ same core handler; relay tabs deliberately do not apply this machine's gateway to another core.
+ Mobile needs a settings/model-picker surface before it can expose the feature.
- **Grok** (`@xai-official/grok` 1.0.0, builtin since 2026-08) — in `AGENT_HOOK_TARGETS`,
`RESUMABLE_AGENTS`, `RENAME_CAPABLE`, `PERMISSION_MODE_CAPABLE` and `CANVAS_CONTROL_CAPABLE`; NOT in
`USAGE_CAPABLE` / `CONTEXT_LINK_CAPABLE` / `SUBAGENT_CAPABLE` (each blocked on a fixture that needs a
@@ -1347,6 +1361,15 @@ principle. Per-agent write-ups: `docs/grok-agent.md`, `docs/gemini-agent.md`.
16. **Write the device checklist for what you could not run.** Every unverified claim becomes a
numbered item; group the ones that fall out of a single capture run. `docs/grok-agent.md` §9 and
`docs/gemini-agent.md` §9 are the format.
+17. **Extend the base harness mapping, never a frontend allowlist.** Model support is
+ `MODEL_SWITCH_CAPABLE` plus the protocol/env/flag leaf in `shared/agents/model-gateway.ts`.
+ Frontends call `canSwitchModel` / `modelsForAgent`; they never spell Claude, Codex or a custom
+ id themselves. This makes `baseAgent:'claude'` inherit discovery, filtering, environment and
+ command grammar as one unit instead of four copies that drift.
+18. **A model switch must refresh the shell environment without printing the key.** An already-live
+ shell does not inherit a later `tmux set-environment`, and prefixing the resume line with
+ `KEY=secret` leaks it into the pane/history. Exit the idle CLI, recycle the persistent session,
+ and let cold restore resume with the new model under the newly injected environment.
## Session memory (the RAM pill + the per-session panel)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index eff78f79a..5b68db0e0 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -111,6 +111,11 @@ here has: not while the kanban board covers it, not while the user is typing.
reasoning. A comment that restates the code is noise; one that says "do not simplify this back,
here is what broke" is the point.
+**Agent features attach to base harness capabilities, not frontend allowlists.** A custom agent can
+inherit a builtin harness, so add the capability and its one shared leaf (`src/shared/agents`) and
+let every UI ask the helper. Repeating Claude/Codex/etc. cases in menus breaks that inheritance and
+eventually drifts.
+
## Testing
`npm test` must pass, and `npm run typecheck` is the fastest gate.
diff --git a/src/core/agent-env-ipc.ts b/src/core/agent-env-ipc.ts
index fb9aec065..936a85b4e 100644
--- a/src/core/agent-env-ipc.ts
+++ b/src/core/agent-env-ipc.ts
@@ -5,6 +5,52 @@
import { IPC } from '../shared/ipc'
import { platform } from './platform'
import { assembleLaunchCommand, type LaunchInputs } from '../shared/agents/launch'
+import {
+ modelGatewayRoutes,
+ parseGatewayModels,
+ type ModelDiscoveryResult,
+ type ModelGatewaySettings
+} from '../shared/agents/model-gateway'
+
+const DISCOVERY_TIMEOUT_MS = 10_000
+
+/**
+ * Query model discovery from core rather than the renderer: gateways commonly omit browser CORS,
+ * and the API key should never be interpolated into a terminal command. Every failure is returned
+ * as data so opening Settings or a context menu cannot create an unhandled rejection.
+ */
+async function discoverModels(settings: ModelGatewaySettings): Promise<ModelDiscoveryResult> {
+ const routes = modelGatewayRoutes(settings?.baseUrl ?? '')
+ const apiKey = settings?.apiKey?.trim() ?? ''
+ if (!routes) return { models: [], error: 'Enter a valid HTTP(S) gateway URL.' }
+ if (!apiKey) return { models: [], error: 'Enter an API key.' }
+
+ const controller = new AbortController()
+ const timer = setTimeout(() => controller.abort(), DISCOVERY_TIMEOUT_MS)
+ try {
+ const response = await fetch(routes.discovery, {
+ headers: { Authorization: `Bearer ${apiKey}`, Accept: 'application/json' },
+ signal: controller.signal
+ })
+ if (!response.ok) {
+ return { models: [], error: `Model discovery failed (HTTP ${response.status}).` }
+ }
+ const models = parseGatewayModels(await response.json())
+ return models.length
+ ? { models }
+ : { models: [], error: 'The gateway returned no usable models.' }
+ } catch (err) {
+ const timedOut = err instanceof Error && err.name === 'AbortError'
+ return {
+ models: [],
+ error: timedOut
+ ? 'Model discovery timed out.'
+ : `Model discovery failed: ${err instanceof Error ? err.message : 'unknown error'}`
+ }
+ } finally {
+ clearTimeout(timer)
+ }
+}
/** A string-only snapshot of `process.env` (undefined entries omitted), for `${env:VAR}` expansion
* in the renderer's preview. */
@@ -23,4 +69,7 @@ export function registerAgentEnvIpc(): void {
platform().handle(IPC.agentPreviewCommand, (inputs: LaunchInputs) =>
assembleLaunchCommand(inputs, envSnapshot())
)
+ platform().handle(IPC.agentDiscoverModels, (settings: ModelGatewaySettings) =>
+ discoverModels(settings)
+ )
}
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index cb8649fa6..b97471277 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -75,6 +75,7 @@ import { clearNode as clearNodeAgentStatus } from './agent-status-mirror'
import { hasSharedIdentity, setCustomAgentBaseResolver, type AgentId } from '../shared/agents/config'
import { findCustomAgent } from '../shared/agents/custom-agent'
import { applyCustomAgentEnv, customAgentEnvArgs } from './custom-agent-env'
+import { modelGatewayEnv } from '../shared/agents/model-gateway'
// How often we snapshot a live tmux session's scrollback to disk, so a machine reboot (which
// kills the tmux server) can still replay recent output on cold restart. A final snapshot also
@@ -2002,6 +2003,20 @@ export class PtyManager {
for (const k of AUTH_ENV_STRIP) delete env[k]
}
+ // Shared model gateway: resolve through the node's BASE harness in one shared mapping, then
+ // apply it before custom-agent env. That precedence is intentional: an inheriting custom agent
+ // benefits from the one-click gateway by default, but env values it explicitly declares still
+ // win exactly as they did before this feature. Remote values travel through tmux `-e` below;
+ // do not leak them into the local ssh client process environment.
+ const gatewayEnv = modelGatewayEnv(
+ this.getSettings().modelGateway,
+ options.agentId ?? 'claude',
+ options.agentModel
+ )
+ if (!options.sshRemote) {
+ for (const [k, v] of Object.entries(gatewayEnv)) env[k] = v
+ }
+
// Custom-agent env: merged LAST so it wins over hook + account + PATH/LANG env (required for
// the proxy use case — the user's ANTHROPIC_AUTH_TOKEN / ANTHROPIC_BASE_URL must beat whatever
// the account path set). ${env:VAR} is expanded against the live process env. Only the LOCAL
@@ -2102,6 +2117,10 @@ export class PtyManager {
)
for (const w of remoteCustomEnv.warnings) console.warn(w)
const remoteCustomEnvArgs = remoteCustomEnv.args.flatMap((kv) => ['-e', kv])
+ const remoteGatewayEnvArgs = Object.entries(gatewayEnv).flatMap(([k, v]) => [
+ '-e',
+ `${k}=${v}`
+ ])
args = remoteTmuxPtyArgs(
options.sshRemote.conn,
options.sshRemote.controlPath,
@@ -2113,7 +2132,12 @@ export class PtyManager {
// place a foreign value is most at home.
reqShell,
options.shellArgs,
- [...hookExtraEnv, ...remoteAccountEnv, ...remoteCustomEnvArgs],
+ [
+ ...hookExtraEnv,
+ ...remoteAccountEnv,
+ ...remoteGatewayEnvArgs,
+ ...remoteCustomEnvArgs
+ ],
// Source nodeterm's remote tmux.conf via `-f` (written on connect, Task 2) so a cold-start
// session gets mouse/clipboard/scrollback. Fail-open: undefined → remote tmux host defaults.
options.sshRemote.tmuxConfPath
@@ -2142,6 +2166,12 @@ export class PtyManager {
// The account config dir must ride `-e` like the hook env: the tmux server is shared
// and long-lived, so session env comes from creation args, not client inheritance.
const accountEnvArgs = accountDir ? accountTmuxEnvArgs(accountDir) : []
+ // The shared tmux server outlives the app, so the gateway cannot rely on the tmux client's
+ // inherited process env. Emit only the centrally-mapped keys explicitly; read their FINAL
+ // values from `env` so a custom agent override retains last-write precedence.
+ const gatewayEnvArgs = Object.keys(gatewayEnv).flatMap((key) =>
+ typeof env[key] === 'string' ? ['-e', `${key}=${env[key]}`] : []
+ )
const attachFlags = tmuxAttachFlags(!!sinks)
args = [
'-L',
@@ -2154,6 +2184,7 @@ export class PtyManager {
...pathEnvArgs,
...langEnvArgs,
...accountEnvArgs,
+ ...gatewayEnvArgs,
'-c',
cwd,
'-s',
diff --git a/src/core/pty-single-user.test.ts b/src/core/pty-single-user.test.ts
index 98796771f..a16ace73f 100644
--- a/src/core/pty-single-user.test.ts
+++ b/src/core/pty-single-user.test.ts
@@ -228,6 +228,31 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () =
fs.rmSync(cwd, { recursive: true, force: true })
})
+ it('injects the shared gateway into both the PTY and its tmux session environment', async () => {
+ const { PtyManager } = await import('./pty-manager')
+ const m = new PtyManager()
+ m.init(() => ({
+ ...DEFAULT_SETTINGS,
+ modelGateway: { baseUrl: 'https://bifrost.example.test', apiKey: 'vk-secret' }
+ }))
+ m.registerIpc()
+
+ await create(80, 24, 'gateway-node', { agentId: 'claude' })
+
+ expect(spawnArgs[0].env.ANTHROPIC_BASE_URL).toBe(
+ 'https://bifrost.example.test/anthropic'
+ )
+ expect(spawnArgs[0].env.ANTHROPIC_AUTH_TOKEN).toBe('vk-secret')
+ expect(spawnArgs[0].args).toEqual(
+ expect.arrayContaining([
+ '-e',
+ 'ANTHROPIC_BASE_URL=https://bifrost.example.test/anthropic',
+ '-e',
+ 'ANTHROPIC_AUTH_TOKEN=vk-secret'
+ ])
+ )
+ })
+
// ── `fresh` drives scrollback replay + agent resume: it must still be computed from tmux ──
it('fresh:false on a WARM reattach (tmux session already exists) — no cold restore', async () => {
await tmuxManager()
diff --git a/src/core/settings-store.test.ts b/src/core/settings-store.test.ts
index 84f232886..05eb832d8 100644
--- a/src/core/settings-store.test.ts
+++ b/src/core/settings-store.test.ts
@@ -85,6 +85,20 @@ describe('SettingsStore nested-default merge', () => {
expect(store.get().speech).toEqual(DEFAULT_SETTINGS.speech)
})
+ it('fills missing model-gateway fields without losing a saved endpoint', () => {
+ writeFileSync(
+ path.join(dir, 'settings.json'),
+ JSON.stringify({ modelGateway: { baseUrl: 'https://bifrost.example.test' } }),
+ 'utf-8'
+ )
+ const store = new SettingsStore()
+ store.init()
+ expect(store.get().modelGateway).toEqual({
+ baseUrl: 'https://bifrost.example.test',
+ apiKey: ''
+ })
+ })
+
it("defaults everything when settings.json does not exist", () => {
const store = new SettingsStore()
store.init()
diff --git a/src/core/settings-store.ts b/src/core/settings-store.ts
index f2d497414..5ebf3e0aa 100644
--- a/src/core/settings-store.ts
+++ b/src/core/settings-store.ts
@@ -9,12 +9,13 @@ import { DEFAULT_SETTINGS, type Settings } from '../shared/types'
* `{ ...DEFAULT_SETTINGS, ...saved }` shallow merge is right for top-level keys (a missing key
* picks up the default), but WRONG for nested objects: an old `settings.json` that has a
* `speech` object without a newly-added key (e.g. `shortcut`) would have its whole `speech`
- * object override the default one-for-one, silently dropping the new key. `speech` is merged
- * one level deeper so old files still pick up new nested defaults.
+ * object override the default one-for-one, silently dropping the new key. Nested settings are
+ * merged one level deeper so old files still pick up new defaults.
*/
function mergeSettings(saved: Partial<Settings> | null | undefined): Settings {
const merged = { ...DEFAULT_SETTINGS, ...saved }
merged.speech = { ...DEFAULT_SETTINGS.speech, ...saved?.speech }
+ merged.modelGateway = { ...DEFAULT_SETTINGS.modelGateway, ...saved?.modelGateway }
// Legacy `terminalGpuRendering` was a boolean whose default (true) was merged into every saved
// file — so a stored `true` is indistinguishable from "never touched" and maps to the new
// 'auto' (platform-aware) default, while a stored `false` was always an explicit escape-hatch
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 0b28b46b9..b0c8dfde5 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -439,7 +439,8 @@ const api: NodeTerminalApi = {
},
agent: {
envSnapshot: () => ipcRenderer.invoke(IPC.envSnapshot),
- previewCommand: (inputs) => ipcRenderer.invoke(IPC.agentPreviewCommand, inputs)
+ previewCommand: (inputs) => ipcRenderer.invoke(IPC.agentPreviewCommand, inputs),
+ discoverModels: (settings) => ipcRenderer.invoke(IPC.agentDiscoverModels, settings)
},
chat: {
readTranscript: (sessionId, cwd, accountId, nodeId) =>
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index 416ff2ce9..1180dc18e 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -277,7 +277,8 @@ export function buildStubApi(): Omit<
// (Server Edition) ws-bridge overrides this with the real handler; the stub returns an empty
// env + unexpanded command so the preview degrades to "unavailable" rather than throwing.
envSnapshot: () => Promise.resolve({}),
- previewCommand: U('agent.previewCommand')
+ previewCommand: U('agent.previewCommand'),
+ discoverModels: () => Promise.resolve({ models: [], error: 'Model discovery is unavailable.' })
},
chat: {
readTranscript: U('chat.readTranscript')
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 50066c796..22bbb8c74 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -206,7 +206,7 @@ const AI_NAMING_UNAVAILABLE = {
* over an RpcClient, mirroring the preload's invoke(→request)/send(→cast) split exactly. */
export function buildRealApi(
client: RpcClient
-): Pick<NodeTerminalApi, 'pty' | 'workspace' | 'settings' | 'userDataDir'> {
+): Pick<NodeTerminalApi, 'pty' | 'workspace' | 'settings' | 'agent' | 'userDataDir'> {
const pty: PtyApi = {
create: (options: PtyCreateOptions) =>
client.request(IPC.ptyCreate, options) as ReturnType<PtyApi['create']>,
@@ -288,12 +288,24 @@ export function buildRealApi(
save: (s: Settings) => client.request(IPC.settingsSave, s) as Promise<void>
}
+ const agent: NodeTerminalApi['agent'] = {
+ envSnapshot: () => client.request(IPC.envSnapshot) as Promise<Record<string, string>>,
+ previewCommand: (inputs) =>
+ client.request(IPC.agentPreviewCommand, inputs) as ReturnType<
+ NodeTerminalApi['agent']['previewCommand']
+ >,
+ discoverModels: (gateway) =>
+ client.request(IPC.agentDiscoverModels, gateway) as ReturnType<
+ NodeTerminalApi['agent']['discoverModels']
+ >
+ }
+
// The server's data dir, over the SAME channel the desktop preload uses. It is the writable base
// the worktree dialog derives its default path from — a stub returning '' would suggest
// `/worktrees/…` at the filesystem root (the server usually runs as root, and git would create it).
const userDataDir = (): Promise<string> => client.request(IPC.appUserDataDir) as Promise<string>
- return { pty, workspace, settings, userDataDir }
+ return { pty, workspace, settings, agent, userDataDir }
}
export function buildGitHubApi(
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index b8d9ff0b6..ad26a10e6 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -144,6 +144,8 @@ import {
} from '../lib/addMenuSpec'
import { transferConversationItems } from '../lib/transferItems'
import { reopenVariants } from '../lib/reopenVariants'
+import { modelsForAgent } from '@shared/agents/model-gateway'
+import { useModelGateway } from '../state/modelGateway'
import { viewportAtZoom1 } from '../lib/zoomReset'
import { isSpaceRelease, spacePanKeydown } from '../lib/spacePan'
import { UpdateCard } from '../components/UpdateCard'
@@ -261,6 +263,7 @@ import {
canBranch,
canRename,
canContextLink,
+ canSwitchModel,
createdAgentId,
resumeCommand,
AGENT_CONFIG,
@@ -701,7 +704,8 @@ function StatusAwareMiniMap({ onNodeDoubleClick }: { onNodeDoubleClick: (node: N
export function Canvas() {
// This canvas's core api (a context read — stable for the session, no store subscription).
// For the local session it IS window.nodeTerminal, so every call resolves identically.
- const { api } = useSession()
+ const session = useSession()
+ const { api } = session
const [nodes, setNodes, onNodesChange] = useNodesState<CanvasNode>([])
// Persistent context links between Claude nodes (separate from ephemeral subagent/loop edges).
const [linkEdges, setLinkEdges, onLinkEdgesChange] = useEdgesState<Edge>([])
@@ -1023,6 +1027,30 @@ export function Canvas() {
const [mergeTarget, setMergeTargetState] = useState<MergeState | null>(null)
const [mergePush, setMergePush] = useState(false)
const settings = useSettings((s) => s.settings)
+ const gatewayModels = useModelGateway((s) => s.models)
+ const gatewayStatus = useModelGateway((s) => s.status)
+ const gatewayError = useModelGateway((s) => s.error)
+ const discoverModels = useModelGateway((s) => s.discover)
+ const clearModels = useModelGateway((s) => s.clear)
+
+ // Prime the context-menu catalogue after hydration and refresh it after a gateway edit. Debounce
+ // keystrokes so entering a URL/key does not issue one authenticated request per character. The
+ // global preload is deliberate: gateway settings belong to this app instance, never to a relay
+ // tab whose terminals and secrets live on another machine.
+ useEffect(() => {
+ const gateway = settings.modelGateway
+ if (!gateway.baseUrl.trim() || !gateway.apiKey.trim()) {
+ clearModels()
+ return
+ }
+ const timer = setTimeout(() => void discoverModels(gateway), 500)
+ return () => clearTimeout(timer)
+ }, [
+ settings.modelGateway.baseUrl,
+ settings.modelGateway.apiKey,
+ discoverModels,
+ clearModels
+ ])
const viewportRef = useRef<Viewport>({ x: 0, y: 0, zoom: 1 })
const nodesRef = useRef<CanvasNode[]>(nodes)
/**
@@ -4641,13 +4669,17 @@ export function Canvas() {
// time, so a stale menu cannot force a restart onto a session that just went busy); all that is
// left here is telling the user how it went. Up to ~6s of exit polling plus the echo-verified
// resume line, hence the await before the notice.
- const restartAgentNode = useCallback(async (nodeId: string, targetAgentId?: AgentId) => {
+ const restartAgentNode = useCallback(async (
+ nodeId: string,
+ targetAgentId?: AgentId,
+ targetModel?: string
+ ) => {
const fn = agentRestartFn(nodeId)
if (!fn) return // node unmounted between opening the menu and clicking
- const action = targetAgentId ? 'Reopen' : 'Restart'
+ const action = targetModel ? 'Model switch' : targetAgentId ? 'Reopen' : 'Restart'
let outcome: RestartOutcome
try {
- outcome = await fn(targetAgentId)
+ outcome = await fn(targetAgentId, targetModel)
} catch {
// The transport under the restart threw (a relay socket still CONNECTING rejects the very
// first write). Unhandled, this rejection made the action a silent no-op — the user clicked
@@ -4659,14 +4691,21 @@ export function Canvas() {
})
return
}
- if (outcome === 'restarted' && targetAgentId) {
+ if (outcome === 'restarted' && (targetAgentId || targetModel)) {
// The pane now runs the target variant. Persist that identity so its icon/capabilities and
// every later plain Restart describe what is actually in the pane. The provider session id
// stays unchanged, so choosing the original variant later reverses this cleanly.
setNodes((ns) =>
ns.map((n) =>
n.id === nodeId && n.type === 'terminal'
- ? { ...n, data: { ...n.data, agentId: targetAgentId } }
+ ? {
+ ...n,
+ data: {
+ ...n.data,
+ ...(targetAgentId ? { agentId: targetAgentId } : {}),
+ ...(targetModel ? { agentModel: targetModel } : {})
+ }
+ }
: n
)
)
@@ -4684,9 +4723,11 @@ export function Canvas() {
outcome === 'restarted'
? {
kind: 'info',
- text: targetLabel
- ? `Session reopened as ${targetLabel} — conversation resumed.`
- : 'Agent restarted — conversation resumed.'
+ text: targetModel
+ ? `Switched to ${targetModel} — conversation resumed.`
+ : targetLabel
+ ? `Session reopened as ${targetLabel} — conversation resumed.`
+ : 'Agent restarted — conversation resumed.'
}
: outcome === 'exit-timeout'
? {
@@ -5329,6 +5370,12 @@ export function Canvas() {
const variants = sourceAgentId
? reopenVariants(sourceAgentId, settings.customAgents, settings.disabledAgents)
: []
+ const switchCapable = !!sourceAgentId && canSwitchModel(sourceAgentId)
+ const compatibleModels = sourceAgentId && session.source !== 'relay'
+ ? modelsForAgent(gatewayModels, sourceAgentId)
+ : []
+ const currentModel =
+ typeof n?.data.agentModel === 'string' ? n.data.agentModel : undefined
// 'not-resumable' is permanent (a plain shell, opencode, a custom CLI with no exit
// command) — no row at all. The other two are temporary, so the row stays and says
// what to wait for instead of disappearing and teaching nothing.
@@ -5375,6 +5422,43 @@ export function Canvas() {
)
}
] as MenuItem[])
+ : []),
+ ...(switchCapable
+ ? compatibleModels.length
+ ? ([
+ {
+ type: 'submenu',
+ label: currentModel ? `Switch model (${currentModel})` : 'Switch model',
+ icon: <IconSwitch />,
+ children: compatibleModels.map(
+ (model): MenuItem => ({
+ label: `${model.id === currentModel ? '✓ ' : ''}${model.id}`,
+ disabled: !!why || model.id === currentModel,
+ hint:
+ model.id === currentModel
+ ? 'This node is already using this model.'
+ : why ??
+ `Restarts the terminal session and resumes this conversation with ${model.id}.`,
+ onClick: () =>
+ void restartAgentNode(ids[0], undefined, model.id)
+ })
+ )
+ }
+ ] as MenuItem[])
+ : ([
+ {
+ label: 'Switch model',
+ icon: <IconSwitch />,
+ disabled: true,
+ hint:
+ session.source === 'relay'
+ ? 'Configure the model gateway on the machine hosting this relay session.'
+ : gatewayStatus === 'loading'
+ ? 'Discovering models…'
+ : gatewayError ||
+ 'Configure a URL and API key in Settings → Model gateway.'
+ }
+ ] as MenuItem[])
: [])
] as MenuItem[]
})()
@@ -5396,7 +5480,11 @@ export function Canvas() {
toggleMarkdown,
reloadTerminals,
restartAgentNode,
- deleteNodes
+ deleteNodes,
+ gatewayModels,
+ gatewayStatus,
+ gatewayError,
+ session.source
])
/** "New <agent>" creation entries shared by the pane and group context menus.
diff --git a/src/renderer/components/settings/SettingsIcons.tsx b/src/renderer/components/settings/SettingsIcons.tsx
index 4281c0632..b5ce81c4f 100644
--- a/src/renderer/components/settings/SettingsIcons.tsx
+++ b/src/renderer/components/settings/SettingsIcons.tsx
@@ -63,6 +63,14 @@ const PATHS: Record<SettingsSectionId, React.JSX.Element> = {
<path d="M8 5.5v5M5.5 8h5" />
</>
),
+ 'model-gateway': (
+ <>
+ <circle cx="4" cy="8" r="1.6" />
+ <circle cx="12" cy="4" r="1.6" />
+ <circle cx="12" cy="12" r="1.6" />
+ <path d="M5.6 7.4 10.4 4.6M5.6 8.6l4.8 2.8" />
+ </>
+ ),
notifications: (
<>
<path d="M4.8 7a3.2 3.2 0 0 1 6.4 0c0 3 1.1 3.9 1.1 3.9H3.7S4.8 10 4.8 7Z" />
diff --git a/src/renderer/components/settings/SettingsPage.tsx b/src/renderer/components/settings/SettingsPage.tsx
index 1167dcbe7..dd684ef81 100644
--- a/src/renderer/components/settings/SettingsPage.tsx
+++ b/src/renderer/components/settings/SettingsPage.tsx
@@ -26,6 +26,7 @@ import { SshSection } from './sections/SshSection'
import { UpdatesSection } from './sections/UpdatesSection'
import { PrivacySection } from './sections/PrivacySection'
import { GitHubIssuesSection } from './sections/GitHubIssuesSection'
+import { ModelGatewaySection } from './sections/ModelGatewaySection'
const isMac = /Mac/i.test(navigator.platform || navigator.userAgent)
@@ -81,6 +82,7 @@ export function SettingsPage({
<UsageSection isActive={active === 'usage'} />
<AccountsSection isActive={active === 'accounts'} />
<CustomAgentsSection isActive={active === 'custom-agents'} />
+ <ModelGatewaySection isActive={active === 'model-gateway'} />
<NotificationsSection isActive={active === 'notifications'} />
<CommitSection isActive={active === 'commit'} />
<TmuxSection isActive={active === 'tmux'} />
diff --git a/src/renderer/components/settings/nav.test.ts b/src/renderer/components/settings/nav.test.ts
index ee2544a35..0b6e6add7 100644
--- a/src/renderer/components/settings/nav.test.ts
+++ b/src/renderer/components/settings/nav.test.ts
@@ -2,10 +2,10 @@ import { describe, it, expect } from 'vitest'
import { SETTINGS_GROUPS, allSectionIds, FIRST_SECTION_ID, visibleSettingsGroups } from './nav'
describe('SETTINGS_GROUPS', () => {
- it('lists exactly 22 sections with no duplicates', () => {
+ it('lists exactly 23 sections with no duplicates', () => {
const ids = allSectionIds()
- expect(ids).toHaveLength(22)
- expect(new Set(ids).size).toBe(22)
+ expect(ids).toHaveLength(23)
+ expect(new Set(ids).size).toBe(23)
})
it('starts at a section that exists in the groups', () => {
expect(allSectionIds()).toContain(FIRST_SECTION_ID)
@@ -13,7 +13,7 @@ describe('SETTINGS_GROUPS', () => {
it('hides mac-only sections off macOS, keeps them on', () => {
const off = visibleSettingsGroups(false).flatMap((g) => g.sections.map((s) => s.id))
expect(off).not.toContain('notch')
- expect(off).toHaveLength(21)
+ expect(off).toHaveLength(22)
expect(visibleSettingsGroups(true)).toEqual(SETTINGS_GROUPS)
// No group is left empty by the filter.
expect(visibleSettingsGroups(false).every((g) => g.sections.length > 0)).toBe(true)
diff --git a/src/renderer/components/settings/nav.ts b/src/renderer/components/settings/nav.ts
index 8591a6a1c..f242f3e5f 100644
--- a/src/renderer/components/settings/nav.ts
+++ b/src/renderer/components/settings/nav.ts
@@ -10,6 +10,7 @@ export type SettingsSectionId =
| 'usage'
| 'accounts'
| 'custom-agents'
+ | 'model-gateway'
| 'notifications'
| 'commit'
| 'tmux'
@@ -45,6 +46,7 @@ export const SETTINGS_GROUPS: SettingsGroup[] = [
{ id: 'agents', title: 'Agents' },
{ id: 'accounts', title: 'Accounts' },
{ id: 'custom-agents', title: 'Custom agents' },
+ { id: 'model-gateway', title: 'Model gateway' },
{ id: 'usage', title: 'Usage' },
{ id: 'commit', title: 'Commit messages' }
]
diff --git a/src/renderer/components/settings/sections/ModelGatewaySection.tsx b/src/renderer/components/settings/sections/ModelGatewaySection.tsx
new file mode 100644
index 000000000..f30fba514
--- /dev/null
+++ b/src/renderer/components/settings/sections/ModelGatewaySection.tsx
@@ -0,0 +1,134 @@
+import { useState } from 'react'
+import { modelGatewayRoutes } from '@shared/agents/model-gateway'
+import { useModelGateway } from '../../../state/modelGateway'
+import { useSettings } from '../../../state/settings'
+import { Button } from '@renderer/ui/Button'
+import { Input } from '@renderer/ui/Input'
+import { FieldRow } from '../FieldRow'
+import { SearchableRow } from '../SearchableRow'
+import { SettingsSection } from '../SettingsSection'
+
+const ROWS = {
+ endpoint: {
+ title: 'Gateway URL',
+ description: 'One Bifrost-compatible root URL for model discovery and agent routes.',
+ keywords: ['bifrost', 'model', 'provider', 'base url', 'endpoint']
+ },
+ key: {
+ title: 'API key',
+ description: 'A Bifrost virtual key or compatible bearer key.',
+ keywords: ['token', 'secret', 'virtual key', 'authentication']
+ },
+ discovery: {
+ title: 'Available models',
+ description: 'Refresh the model catalogue used by agent-node context menus.',
+ keywords: ['discover', 'refresh', 'switch model', 'catalogue']
+ }
+}
+const ENTRIES = Object.values(ROWS)
+
+export function ModelGatewaySection({ isActive }: { isActive: boolean }): React.JSX.Element {
+ const gateway = useSettings((s) => s.settings.modelGateway)
+ const update = useSettings((s) => s.update)
+ const models = useModelGateway((s) => s.models)
+ const status = useModelGateway((s) => s.status)
+ const error = useModelGateway((s) => s.error)
+ const discover = useModelGateway((s) => s.discover)
+ const [showKey, setShowKey] = useState(false)
+ const routes = modelGatewayRoutes(gateway.baseUrl)
+
+ const patchGateway = (patch: Partial<typeof gateway>): void =>
+ update({ modelGateway: { ...gateway, ...patch } })
+
+ return (
+ <SettingsSection
+ id="model-gateway"
+ title="Model gateway"
+ description="Configure one Bifrost-compatible endpoint, discover its models, and switch a supported agent node without creating a custom agent for every model."
+ isActive={isActive}
+ searchEntries={ENTRIES}
+ >
+ <SearchableRow {...ROWS.endpoint}>
+ <FieldRow
+ label="Gateway URL"
+ description="Enter the server root; nodeterm derives /v1/models, /openai/v1, and /anthropic."
+ htmlFor="model-gateway-url"
+ control={
+ <Input
+ id="model-gateway-url"
+ className="w-80"
+ type="url"
+ placeholder="https://bifrost.example.com"
+ value={gateway.baseUrl}
+ onChange={(e) => patchGateway({ baseUrl: e.target.value })}
+ />
+ }
+ />
+ {gateway.baseUrl && !routes ? (
+ <p className="mt-2 text-right text-xs text-[color:var(--warn)]">
+ Enter a valid HTTP(S) URL without embedded credentials.
+ </p>
+ ) : routes ? (
+ <div className="mt-3 space-y-1 text-right font-mono text-[11px] text-muted">
+ <div>Discovery: {routes.discovery}</div>
+ <div>OpenAI: {routes.openai}</div>
+ <div>Anthropic: {routes.anthropic}</div>
+ </div>
+ ) : null}
+ </SearchableRow>
+
+ <SearchableRow {...ROWS.key}>
+ <FieldRow
+ label="API key"
+ description="Saved locally in the owner-only settings file and never placed in restart commands."
+ htmlFor="model-gateway-key"
+ control={
+ <div className="flex items-center gap-2">
+ <Input
+ id="model-gateway-key"
+ className="w-64"
+ type={showKey ? 'text' : 'password'}
+ autoComplete="off"
+ placeholder="virtual key"
+ value={gateway.apiKey}
+ onChange={(e) => patchGateway({ apiKey: e.target.value })}
+ />
+ <Button onClick={() => setShowKey((value) => !value)}>
+ {showKey ? 'Hide' : 'Show'}
+ </Button>
+ </div>
+ }
+ />
+ </SearchableRow>
+
+ <SearchableRow {...ROWS.discovery}>
+ <div className="flex items-center justify-between gap-6">
+ <div>
+ <div className="text-sm font-medium text-text">Available models</div>
+ <p className="mt-1 text-[13px] text-muted">
+ {status === 'loading'
+ ? 'Discovering models…'
+ : status === 'ready'
+ ? `${models.length} model${models.length === 1 ? '' : 's'} available.`
+ : 'Models are also refreshed automatically when these settings change.'}
+ </p>
+ {error ? <p className="mt-1 text-xs text-[color:var(--warn)]">{error}</p> : null}
+ </div>
+ <Button
+ disabled={!routes || !gateway.apiKey.trim() || status === 'loading'}
+ onClick={() => void discover(gateway)}
+ >
+ {status === 'loading' ? 'Discovering…' : models.length ? 'Refresh' : 'Discover models'}
+ </Button>
+ </div>
+ {models.length ? (
+ <div className="mt-3 max-h-40 overflow-y-auto rounded-lg bg-black/15 px-3 py-2 font-mono text-[11px] text-muted">
+ {models.map((model) => (
+ <div key={model.id}>{model.id}</div>
+ ))}
+ </div>
+ ) : null}
+ </SearchableRow>
+ </SettingsSection>
+ )
+}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 67c6a4c27..99e7c50e4 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -158,6 +158,7 @@ import {
} from '@shared/agents/config'
import { withPermissionMode } from '@shared/agents/approval-mode'
import { assembleResumeCommand } from '@shared/agents/launch'
+import { normalizedAgentModel } from '@shared/agents/model-gateway'
import { ensureActivePermissionMode } from '../state/permissionMode'
import { buildSshArgs, sshConnectionIdForProject, sshHostKey, type SshConnection } from '@shared/ssh'
import { hintLabel } from '@shared/platform-utils'
@@ -2429,6 +2430,7 @@ export function TerminalNode({
cwd: data.cwd,
persistKey: id,
agentId: data.agentId,
+ agentModel: data.agentModel,
accountId: data.accountId,
sshRemote,
// Belt AND braces: the guard above cannot see a `ssh` executable that has gone missing,
@@ -2792,7 +2794,14 @@ export function TerminalNode({
? undefined
: useSettings.getState().settings.customAgents.find((c) => c.id === agentId)
const { command: cmd } = assembleResumeCommand(
- { agentId, customAgent, sessionId: priorId || undefined, permissionMode: mode, sharedIdentity: shared },
+ {
+ agentId,
+ customAgent,
+ sessionId: priorId || undefined,
+ permissionMode: mode,
+ model: data.agentModel,
+ sharedIdentity: shared
+ },
{}
)
if (cmd) writeWhenShellReady(cmd) // same shell-startup race as initialCommand
@@ -2846,7 +2855,7 @@ export function TerminalNode({
}
const unregisterRestart = registerAgentRestart(
id,
- guardConcurrentRestart(id, async (targetAgentId?: AgentId) => {
+ guardConcurrentRestart(id, async (targetAgentId?: AgentId, targetModel?: string) => {
const st = useAgentStatus.getState().byId[id]
const agentSessionId = st?.sessionId
// `data.agentId` can change after a successful same-base swap while this deliberately
@@ -2870,6 +2879,35 @@ export function TerminalNode({
capabilityAgentId(target) !== capabilityAgentId(sourceAgentId)
)
return 'not-eligible'
+ const selectedModel = targetModel
+ ? normalizedAgentModel(target, targetModel)
+ : normalizedAgentModel(
+ target,
+ getNode(id)?.data.agentModel as string | undefined
+ )
+ // A model switch must rebuild the terminal session, not merely type a new command into its
+ // existing shell: URL/key env was fixed when that shell was spawned and may have been
+ // configured AFTER this node was created. Recycling after a clean CLI exit gives the new
+ // shell the current gateway env without ever exposing the key in the pane. Relay sessions
+ // belong to another core/settings store, so a local gateway must never be pushed into one.
+ if (targetModel) {
+ if (!selectedModel || session.source === 'relay') return 'not-eligible'
+ const exited = await performExitPhase({
+ agentId: target,
+ sessionId: agentSessionId,
+ io: restartIo,
+ paneCommand: () => api.pty.paneCommand(id),
+ isLive: restartTarget
+ })
+ if (exited !== 'exited') return exited
+ transport.recycle(id)
+ updateNodeData(id, (node) => ({
+ agentId: target,
+ agentModel: selectedModel,
+ respawnNonce: ((node.data.respawnNonce as number | undefined) ?? 0) + 1
+ }))
+ return 'restarted'
+ }
// Built HERE, not inside the choreography: the shared assembly builder is the single funnel
// for every CLI launch path (shared/agents/launch.ts) and the mode is a renderer-side, async
// read — exactly as the cold-restore relaunch above does it. Without it a canvas running
@@ -2887,7 +2925,8 @@ export function TerminalNode({
agentId: target,
customAgent: customTarget,
sessionId: agentSessionId,
- permissionMode: await ensureActivePermissionMode(target)
+ permissionMode: await ensureActivePermissionMode(target),
+ model: selectedModel ?? undefined
},
launchEnv
)
diff --git a/src/renderer/state/modelGateway.ts b/src/renderer/state/modelGateway.ts
new file mode 100644
index 000000000..9ed770573
--- /dev/null
+++ b/src/renderer/state/modelGateway.ts
@@ -0,0 +1,44 @@
+import { create } from 'zustand'
+import type { GatewayModel, ModelGatewaySettings } from '@shared/agents/model-gateway'
+
+export type ModelDiscoveryStatus = 'idle' | 'loading' | 'ready' | 'error'
+
+interface ModelGatewayState {
+ models: GatewayModel[]
+ status: ModelDiscoveryStatus
+ error: string
+ discover(settings: ModelGatewaySettings): Promise<void>
+ clear(): void
+}
+
+// A later request supersedes an earlier one. Editing the gateway URL/key can otherwise let a slow
+// response from the OLD endpoint land after the new catalogue and silently replace it.
+let requestSeq = 0
+
+export const useModelGateway = create<ModelGatewayState>((set) => ({
+ models: [],
+ status: 'idle',
+ error: '',
+
+ async discover(settings) {
+ const seq = ++requestSeq
+ set({ status: 'loading', error: '' })
+ const result = await window.nodeTerminal.agent
+ .discoverModels(settings)
+ .catch((err: unknown) => ({
+ models: [],
+ error: err instanceof Error ? err.message : 'Model discovery failed.'
+ }))
+ if (seq !== requestSeq) return
+ set({
+ models: result.models,
+ status: result.error ? 'error' : 'ready',
+ error: result.error ?? ''
+ })
+ },
+
+ clear() {
+ requestSeq++
+ set({ models: [], status: 'idle', error: '' })
+ }
+}))
diff --git a/src/renderer/state/workspace.test.ts b/src/renderer/state/workspace.test.ts
index aacc02f09..131253404 100644
--- a/src/renderer/state/workspace.test.ts
+++ b/src/renderer/state/workspace.test.ts
@@ -574,12 +574,21 @@ describe('accountId serialization', () => {
position: { x: 0, y: 0 },
width: 600,
height: 400,
- data: { title: 'T', color: '#888', group: null, agentId: 'claude', accountId: 'a1' }
+ data: {
+ title: 'T',
+ color: '#888',
+ group: null,
+ agentId: 'claude',
+ agentModel: 'openai/gpt-5',
+ accountId: 'a1'
+ }
} as unknown as CanvasNode
const states = flowToNodeStates([node])
expect(states[0].accountId).toBe('a1')
+ expect(states[0].agentModel).toBe('openai/gpt-5')
const back = nodeStatesToFlow(states)
expect(back[0].data.accountId).toBe('a1')
+ expect(back[0].data.agentModel).toBe('openai/gpt-5')
})
it('leaves accountId undefined when unset', () => {
const node = {
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index c242263c3..989e01835 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -93,6 +93,8 @@ export interface NodeData {
highScore?: number
/** Which agent runs in this terminal node (claude/codex/gemini/custom). */
agentId?: AgentId
+ /** Model selected for this node through the shared model gateway. */
+ agentModel?: string
/**
* Claude nodes only: the managed Claude account (config-dir isolated) this node runs under.
* Persisted so cold-restore resume reads the transcript from the right account dir.
@@ -1274,6 +1276,7 @@ export function nodeStatesToFlow(states: CanvasNodeState[]): CanvasNode[] {
commitOid: n.commitOid,
highScore: n.highScore,
agentId,
+ agentModel: n.agentModel,
accountId: n.accountId,
agentSessionId: n.agentSessionId,
pendingLaunch: n.pendingLaunch,
@@ -1339,6 +1342,7 @@ export function flowToNodeStates(nodes: CanvasNode[]): CanvasNodeState[] {
commitOid: n.data.commitOid,
highScore: n.data.highScore,
agentId: n.data.agentId,
+ agentModel: n.data.agentModel,
accountId: n.data.accountId,
agentSessionId: n.data.agentSessionId,
pendingLaunch: n.data.pendingLaunch,
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index d580a3649..1babb1981 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -2826,6 +2826,8 @@ body,
the row's remaining width — size it to its content so long account labels don't wrap. */
width: max-content;
max-width: 320px;
+ max-height: min(70vh, 520px);
+ overflow-y: auto;
}
.ctx-submenu .ctx-item {
/* Keep the label and its default ✓ on one line (labels ellipsize past max-width). */
diff --git a/src/renderer/terminal/agent-restart.test.ts b/src/renderer/terminal/agent-restart.test.ts
index 9d9cd01a1..b643350be 100644
--- a/src/renderer/terminal/agent-restart.test.ts
+++ b/src/renderer/terminal/agent-restart.test.ts
@@ -991,15 +991,15 @@ describe('agent restart registry', () => {
expect(agentRestartFn('n2')).toBeUndefined()
})
- it('forwards an optional target agent to the registered restart', async () => {
- let seen: string | undefined
- registerAgentRestart('n3', async (targetAgentId) => {
- seen = targetAgentId
+ it('forwards optional target agent and model to the registered restart', async () => {
+ let seen: [string | undefined, string | undefined] | undefined
+ registerAgentRestart('n3', async (targetAgentId, targetModel) => {
+ seen = [targetAgentId, targetModel]
return 'restarted'
})
- expect(await agentRestartFn('n3')?.('custom:claude')).toBe('restarted')
- expect(seen).toBe('custom:claude')
+ expect(await agentRestartFn('n3')?.('custom:claude', 'openai/gpt-5')).toBe('restarted')
+ expect(seen).toEqual(['custom:claude', 'openai/gpt-5'])
})
})
diff --git a/src/renderer/terminal/agent-restart.ts b/src/renderer/terminal/agent-restart.ts
index a8a1b7745..4aa66aaad 100644
--- a/src/renderer/terminal/agent-restart.ts
+++ b/src/renderer/terminal/agent-restart.ts
@@ -409,7 +409,10 @@ export function guardConcurrentRestart<T extends string, Args extends unknown[]>
}
// ── Node registry (same park-surviving pattern as TerminalNode's restartSubs) ────────────
-export type AgentRestartFn = (targetAgentId?: AgentId) => Promise<RestartOutcome>
+export type AgentRestartFn = (
+ targetAgentId?: AgentId,
+ targetModel?: string
+) => Promise<RestartOutcome>
const restartFns = new Map<string, AgentRestartFn>()
diff --git a/src/shared/agents/config.capabilities.test.ts b/src/shared/agents/config.capabilities.test.ts
index 16408a7d6..61c021a5b 100644
--- a/src/shared/agents/config.capabilities.test.ts
+++ b/src/shared/agents/config.capabilities.test.ts
@@ -12,6 +12,7 @@ import {
canResume,
canSubagent,
canTransferFrom,
+ canSwitchModel,
createdAgentId,
hasHooks,
hasPermissionMode,
@@ -34,6 +35,16 @@ describe('CONTEXT_LINK_CAPABLE', () => {
})
})
+describe('MODEL_SWITCH_CAPABLE', () => {
+ it('is centralized on the base harness capability', () => {
+ expect(canSwitchModel('claude')).toBe(true)
+ expect(canSwitchModel('codex')).toBe(true)
+ for (const id of ['gemini', 'opencode', 'grok', 'custom:plain'] as const) {
+ expect(canSwitchModel(id), id).toBe(false)
+ }
+ })
+})
+
describe('opencode capabilities', () => {
it('is a builtin with the parity capability set', () => {
expect(BUILTIN_AGENT_IDS).toContain('opencode')
diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.ts
index 0a0ae844c..b9d79a101 100644
--- a/src/shared/agents/config.ts
+++ b/src/shared/agents/config.ts
@@ -194,6 +194,10 @@ export const CANVAS_CONTROL_CAPABLE = ['claude', 'codex', 'gemini', 'opencode',
// release, and gemini/codex accept theirs on the versions we measured, so none of them may inherit
// a gate fed by a `claude --version` probe.
export const PERMISSION_MODE_CAPABLE = ['claude', 'grok', 'gemini', 'codex'] as const
+// Agents whose harness accepts a per-launch model override and whose gateway protocol we know how
+// to configure. Custom agents inherit this through `capabilityAgentId`, like every other harness
+// capability — the renderer never maintains its own Claude/Codex allowlist.
+export const MODEL_SWITCH_CAPABLE = ['claude', 'codex'] as const
// Agents whose own CLI already tells the user when it copies, so nodeterm must not say it again.
// Claude Code captures the mouse itself and prints its own line — "copied N chars to tmux buffer ·
// paste with prefix + ]" — which makes our copy pill a second message for one gesture. Membership
@@ -267,6 +271,7 @@ export const canRename = (id: AgentId): boolean => includes(RENAME_CAPABLE, id)
export const canReadTitle = (id: AgentId): boolean => includes(TITLE_READ_CAPABLE, id)
export const canControlCanvas = (id: AgentId): boolean => includes(CANVAS_CONTROL_CAPABLE, id)
export const hasPermissionMode = (id: AgentId): boolean => includes(PERMISSION_MODE_CAPABLE, id)
+export const canSwitchModel = (id: AgentId): boolean => includes(MODEL_SWITCH_CAPABLE, id)
export const hasSharedIdentity = (id: AgentId): boolean => includes(SHARED_IDENTITY_CAPABLE, id)
/**
diff --git a/src/shared/agents/launch.test.ts b/src/shared/agents/launch.test.ts
index 0edff53e2..068e39977 100644
--- a/src/shared/agents/launch.test.ts
+++ b/src/shared/agents/launch.test.ts
@@ -56,6 +56,19 @@ describe('assembleLaunchCommand — builtins (byte-identical to the historical p
assembleLaunchCommand({ agentId: 'opencode', initialPrompt: 'fix it' }, ENV).command
).toBe("opencode --prompt 'fix it'")
})
+ it('adds a safely quoted model override after the ordinary Claude launch flags', () => {
+ expect(
+ assembleLaunchCommand(
+ {
+ agentId: 'claude',
+ initialPrompt: 'fix',
+ permissionMode: 'plan',
+ model: 'anthropic/claude-sonnet-4'
+ },
+ ENV
+ ).command
+ ).toBe("claude 'fix' --permission-mode plan --model 'anthropic/claude-sonnet-4'")
+ })
})
describe('assembleLaunchCommand — custom agents', () => {
@@ -92,6 +105,19 @@ describe('assembleLaunchCommand — custom agents', () => {
expect(r.command).toContain("'read the handoff file'")
expect(r.command).not.toContain('--prompt')
})
+ it('a base-agent proxy inherits model-switch command grammar', () => {
+ setCustomAgentBaseResolver((id) => (id === 'custom:proxy' ? 'claude' : undefined))
+ expect(
+ assembleLaunchCommand(
+ {
+ agentId: 'custom:proxy',
+ customAgent: { ...claudeProxy, args: '' },
+ model: 'anthropic/claude-opus'
+ },
+ ENV
+ ).command
+ ).toBe("claude-wopr --model 'anthropic/claude-opus'")
+ })
it('expands ${env:…} in args and reports missing vars', () => {
setCustomAgentBaseResolver((id) => (id === 'custom:proxy' ? 'claude' : undefined))
const r = assembleLaunchCommand(
@@ -118,6 +144,14 @@ describe('assembleResumeCommand', () => {
'codex resume abc-123'
)
})
+ it('puts the model flag in the measured Codex resume grammar', () => {
+ expect(
+ assembleResumeCommand(
+ { agentId: 'codex', sessionId: 'abc-123', model: 'openai/gpt-5' },
+ ENV
+ ).command
+ ).toBe("codex resume abc-123 --model 'openai/gpt-5'")
+ })
it('falls back to the bare launch command when there is no session id', () => {
expect(assembleResumeCommand({ agentId: 'claude' }, ENV).command).toBe('claude')
})
diff --git a/src/shared/agents/launch.ts b/src/shared/agents/launch.ts
index 8a7f4f111..05826582d 100644
--- a/src/shared/agents/launch.ts
+++ b/src/shared/agents/launch.ts
@@ -25,6 +25,7 @@ import {
} from './config'
import { withPermissionMode } from './approval-mode'
import { resolveAgentConfig } from './custom-agent'
+import { withAgentModel } from './model-gateway'
export interface LaunchInputs {
agentId: AgentId
@@ -34,6 +35,8 @@ export interface LaunchInputs {
initialPrompt?: string
/** Permission mode to start in. `undefined` = no flag (the agent's own default). */
permissionMode?: AgentPermissionMode
+ /** Per-node model override, applied through the effective base harness. */
+ model?: string
/** A minted session id for FIRST launch (claude-base only, when the CLI supports `--session-id`).
* Ignored on resume. */
sessionId?: string
@@ -53,6 +56,8 @@ export interface ResumeInputs {
/** The provider session id to resume (live hook id, or the minted id persisted on the node). */
sessionId?: string
permissionMode?: AgentPermissionMode
+ /** Per-node model override, applied through the effective base harness. */
+ model?: string
/** Should a SHARED_IDENTITY_CAPABLE agent (codex) name its managed launcher on resume? Same
* semantics as `LaunchInputs.sharedIdentity`. */
sharedIdentity?: boolean
@@ -118,9 +123,9 @@ export function assembleLaunchCommand(
// Session-id minting: claude-base + CLI supports the flag. On resume this branch is never
// taken (assembleResumeCommand does not pass sessionId).
if (inputs.sessionId && mintsSessionId(capId) && inputs.sessionIdFlagSupported) {
- return withSessionId(withMode, capId, inputs.sessionId)
+ return withAgentModel(withSessionId(withMode, capId, inputs.sessionId), capId, inputs.model)
}
- return withMode
+ return withAgentModel(withMode, capId, inputs.model)
}
const command = usesSep ? `${flagged(baseCmd)} ${sep} ${promptArg}` : flagged(withPrompt)
@@ -150,8 +155,9 @@ export function assembleResumeCommand(
const resumeBase = inputs.sessionId ? resumeCommandWith(baseCmd, capId, inputs.sessionId) : null
const base = resumeBase ?? baseCmd
- const command = inputs.permissionMode
+ const withMode = inputs.permissionMode
? withPermissionMode(base, capId, inputs.permissionMode)
: base
+ const command = withAgentModel(withMode, capId, inputs.model)
return { command, missingEnv: [...m1, ...m2] }
}
diff --git a/src/shared/agents/model-gateway.test.ts b/src/shared/agents/model-gateway.test.ts
new file mode 100644
index 000000000..600be2dda
--- /dev/null
+++ b/src/shared/agents/model-gateway.test.ts
@@ -0,0 +1,116 @@
+import { describe, expect, it } from 'vitest'
+import {
+ modelGatewayEnv,
+ modelGatewayRoutes,
+ modelsForAgent,
+ parseGatewayModels,
+ withAgentModel
+} from './model-gateway'
+import {
+ setCustomAgentBaseResolver,
+ type AgentId,
+ type BuiltinAgentId
+} from './config'
+
+describe('modelGatewayRoutes', () => {
+ it('derives Bifrost discovery and protocol routes from one root', () => {
+ expect(modelGatewayRoutes('https://bifrost.example.test/root///')).toEqual({
+ discovery: 'https://bifrost.example.test/root/v1/models',
+ openai: 'https://bifrost.example.test/root/openai/v1',
+ anthropic: 'https://bifrost.example.test/root/anthropic'
+ })
+ })
+
+ it('refuses non-http, credential-bearing, and ambiguous URLs', () => {
+ expect(modelGatewayRoutes('file:///tmp/gateway')).toBeNull()
+ expect(modelGatewayRoutes('https://[email protected]')).toBeNull()
+ expect(modelGatewayRoutes('https://example.test?route=other')).toBeNull()
+ expect(modelGatewayRoutes('https://example.test/#fragment')).toBeNull()
+ expect(modelGatewayRoutes('not a URL')).toBeNull()
+ })
+})
+
+describe('parseGatewayModels', () => {
+ it('normalizes, sorts, and deduplicates an OpenAI-compatible model list', () => {
+ expect(
+ parseGatewayModels({
+ data: [
+ { id: 'openai/gpt-5', owned_by: 'openai' },
+ { id: 'anthropic/claude-sonnet-4', name: 'Sonnet' },
+ { id: 'openai/gpt-5', name: 'Latest wins' },
+ { id: '' },
+ null
+ ]
+ })
+ ).toEqual([
+ { id: 'anthropic/claude-sonnet-4', name: 'Sonnet', provider: 'anthropic' },
+ { id: 'openai/gpt-5', name: 'Latest wins', provider: 'openai' }
+ ])
+ })
+
+ it('fails closed on an unexpected response shape', () => {
+ expect(parseGatewayModels({ models: [{ id: 'gpt-5' }] })).toEqual([])
+ expect(parseGatewayModels(null)).toEqual([])
+ })
+})
+
+describe('agent mappings', () => {
+ const gateway = { baseUrl: 'https://bifrost.example.test', apiKey: 'vk-secret' }
+
+ it('maps the shared gateway to Claude and Codex environment variables', () => {
+ expect(modelGatewayEnv(gateway, 'claude')).toEqual({
+ ANTHROPIC_BASE_URL: 'https://bifrost.example.test/anthropic',
+ ANTHROPIC_AUTH_TOKEN: 'vk-secret'
+ })
+ expect(modelGatewayEnv(gateway, 'codex')).toEqual({
+ OPENAI_BASE_URL: 'https://bifrost.example.test/openai/v1',
+ OPENAI_API_KEY: 'vk-secret'
+ })
+ expect(modelGatewayEnv(gateway, 'gemini')).toEqual({})
+ })
+
+ it('quotes model ids and refuses unsupported/control-bearing values', () => {
+ expect(withAgentModel('codex resume abc', 'codex', "openai/o'model")).toBe(
+ "codex resume abc --model 'openai/o'\\''model'"
+ )
+ expect(withAgentModel('gemini --resume abc', 'gemini', 'gemini/pro')).toBe(
+ 'gemini --resume abc'
+ )
+ expect(withAgentModel('claude', 'claude', 'bad\nmodel')).toBe('claude')
+ })
+
+ it('offers every Bifrost model to each capable harness', () => {
+ const models = parseGatewayModels({
+ data: [
+ { id: 'openai/gpt-5' },
+ { id: 'anthropic/claude-sonnet-4' },
+ { id: 'claude-alias' }
+ ]
+ })
+ const all = [
+ 'anthropic/claude-sonnet-4',
+ 'claude-alias',
+ 'openai/gpt-5'
+ ]
+ expect(modelsForAgent(models, 'claude').map((m) => m.id)).toEqual(all)
+ expect(modelsForAgent(models, 'codex').map((m) => m.id)).toEqual(all)
+ expect(modelsForAgent(models, 'gemini')).toEqual([])
+ })
+
+ it('inherits mappings and filtering through a custom base agent', () => {
+ setCustomAgentBaseResolver((id: AgentId): BuiltinAgentId | undefined =>
+ id === 'custom:proxy' ? 'claude' : undefined
+ )
+ try {
+ expect(modelGatewayEnv(gateway, 'custom:proxy')).toEqual({
+ ANTHROPIC_BASE_URL: 'https://bifrost.example.test/anthropic',
+ ANTHROPIC_AUTH_TOKEN: 'vk-secret'
+ })
+ expect(withAgentModel('proxy', 'custom:proxy', 'anthropic/claude-opus')).toBe(
+ "proxy --model 'anthropic/claude-opus'"
+ )
+ } finally {
+ setCustomAgentBaseResolver(null)
+ }
+ })
+})
diff --git a/src/shared/agents/model-gateway.ts b/src/shared/agents/model-gateway.ts
new file mode 100644
index 000000000..00b9b860a
--- /dev/null
+++ b/src/shared/agents/model-gateway.ts
@@ -0,0 +1,140 @@
+import { canSwitchModel, capabilityAgentId, type AgentId } from './config'
+import { shellSingleQuote } from '../shell-quote'
+
+/** One Bifrost-compatible gateway configured once for every supported agent harness. */
+export interface ModelGatewaySettings {
+ /** Gateway root, before Bifrost's `/openai`, `/anthropic`, and `/v1/models` routes. */
+ baseUrl: string
+ /** Bifrost virtual key (or an upstream-compatible bearer key). */
+ apiKey: string
+}
+
+/** The intentionally small model shape shared across IPC and renderer state. */
+export interface GatewayModel {
+ id: string
+ name?: string
+ provider?: string
+}
+
+export interface ModelDiscoveryResult {
+ models: GatewayModel[]
+ error?: string
+}
+
+export interface ModelGatewayRoutes {
+ discovery: string
+ openai: string
+ anthropic: string
+}
+
+/**
+ * Derive every route from one user-entered root. Only http(s) URLs are accepted: this value is
+ * later handed to `fetch` and agent CLIs, and settings.json is hand-editable. Invalid input
+ * degrades to null (no discovery and no injected environment), never to a guessed endpoint.
+ */
+export function modelGatewayRoutes(baseUrl: string): ModelGatewayRoutes | null {
+ const raw = baseUrl.trim().replace(/\/+$/, '')
+ if (!raw) return null
+ try {
+ const parsed = new URL(raw)
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null
+ // Credentials in the URL would be copied into every derived endpoint and surfaced in the UI.
+ // The separate API-key field exists precisely so a secret never has to live there.
+ if (parsed.username || parsed.password || parsed.search || parsed.hash) return null
+ const root = parsed.toString().replace(/\/+$/, '')
+ return {
+ discovery: `${root}/v1/models`,
+ openai: `${root}/openai/v1`,
+ anthropic: `${root}/anthropic`
+ }
+ } catch {
+ return null
+ }
+}
+
+/** Parse OpenAI/Bifrost model-list responses, dropping unsafe/empty/duplicate ids. */
+export function parseGatewayModels(payload: unknown): GatewayModel[] {
+ if (!payload || typeof payload !== 'object') return []
+ const data = (payload as { data?: unknown }).data
+ if (!Array.isArray(data)) return []
+ const byId = new Map<string, GatewayModel>()
+ for (const raw of data) {
+ if (!raw || typeof raw !== 'object') continue
+ const row = raw as { id?: unknown; name?: unknown; provider?: unknown; owned_by?: unknown }
+ const id = typeof row.id === 'string' ? row.id.trim() : ''
+ if (!id || id.length > 500 || /[\u0000-\u001f\u007f]/.test(id)) continue
+ const prefix = id.includes('/') ? id.slice(0, id.indexOf('/')) : ''
+ const explicitProvider =
+ typeof row.provider === 'string'
+ ? row.provider.trim()
+ : typeof row.owned_by === 'string'
+ ? row.owned_by.trim()
+ : ''
+ byId.set(id, {
+ id,
+ ...(typeof row.name === 'string' && row.name.trim() ? { name: row.name.trim() } : {}),
+ ...(explicitProvider || prefix ? { provider: explicitProvider || prefix } : {})
+ })
+ }
+ return [...byId.values()].sort((a, b) => a.id.localeCompare(b.id))
+}
+
+/**
+ * Models an agent can be offered. Bifrost intentionally routes provider-prefixed models through
+ * each harness protocol (including non-Anthropic models through Claude Code's Anthropic route), so
+ * filtering by provider here would hide supported modes. The capability is the only UI gate;
+ * custom agents inherit it from their declared base harness.
+ */
+export function modelsForAgent(models: GatewayModel[], agentId: AgentId): GatewayModel[] {
+ if (!canSwitchModel(agentId)) return []
+ return models
+}
+
+/**
+ * Environment applied to a terminal session before custom-agent env (custom values still win).
+ * Model selection itself stays a quoted CLI flag for Claude/Codex; the environment contains only
+ * the gateway route and credential, so a restart command never exposes the API key in the pane.
+ */
+export function modelGatewayEnv(
+ settings: ModelGatewaySettings,
+ agentId: AgentId,
+ _model?: string
+): Record<string, string> {
+ const routes = modelGatewayRoutes(settings.baseUrl)
+ const key = settings.apiKey.trim()
+ if (!routes || !key || !canSwitchModel(agentId)) return {}
+ switch (capabilityAgentId(agentId)) {
+ case 'claude':
+ return {
+ ANTHROPIC_BASE_URL: routes.anthropic,
+ ANTHROPIC_AUTH_TOKEN: key
+ }
+ case 'codex':
+ return {
+ OPENAI_BASE_URL: routes.openai,
+ OPENAI_API_KEY: key
+ }
+ default:
+ return {}
+ }
+}
+
+/** Re-validate a hand-editable/discovered model id at the point it reaches a launch command. */
+export function normalizedAgentModel(agentId: AgentId, model: string | undefined): string | null {
+ const value = model?.trim()
+ if (
+ !value ||
+ value.length > 500 ||
+ /[\u0000-\u001f\u007f]/.test(value) ||
+ !canSwitchModel(agentId)
+ )
+ return null
+ return value
+}
+
+/** Append a safely quoted model flag only for harnesses whose CLI grammar supports it. */
+export function withAgentModel(cmd: string, agentId: AgentId, model: string | undefined): string {
+ const value = normalizedAgentModel(agentId, model)
+ if (!value) return cmd
+ return `${cmd} --model ${shellSingleQuote(value)}`
+}
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index d82a39d8d..98af2974f 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -53,6 +53,8 @@ export const IPC = {
* live preview in Settings → Custom agents. Payload: `LaunchInputs`; resolves
* `{ command, missingEnv }`. */
agentPreviewCommand: 'agent:preview-command',
+ /** Renderer → core: fetch a Bifrost/OpenAI-compatible model catalogue without browser CORS. */
+ agentDiscoverModels: 'agent:discover-models',
transcriptSearch: 'transcript:search',
appToggleMarkdown: 'app:toggle-markdown',
appCloseNode: 'app:close-node',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index f80bcccde..dd7eaeb83 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -8,6 +8,10 @@ import type { GroupWorktree } from './worktree'
import type { ClientId, DinoSnapshot, PeerDiff, PeerIdentity, PeerState } from './presence'
import type { WhisperModelInfo } from './speech'
import type { ProjectKanbanGitHub } from './github-issues'
+import type {
+ ModelDiscoveryResult,
+ ModelGatewaySettings
+} from './agents/model-gateway'
export interface PtyCreateOptions {
shell?: string
@@ -27,6 +31,8 @@ export interface PtyCreateOptions {
* real value in a later phase.
*/
agentId?: AgentId
+ /** Per-node model override. Applied through the node's base harness on launch/cold restore. */
+ agentModel?: string
/** Managed Claude account: inject CLAUDE_CONFIG_DIR for this account into the session env. */
accountId?: string
/**
@@ -224,6 +230,8 @@ export interface CanvasNodeState {
cwd?: string
/** Which agent runs in this terminal node (claude/codex/gemini/custom). */
agentId?: AgentId
+ /** Model selected for this agent node through the shared model gateway. */
+ agentModel?: string
/** Set while this node is armed but not yet launched — see PendingLaunch. */
pendingLaunch?: PendingLaunch
/**
@@ -1007,6 +1015,8 @@ export interface Settings {
soundVolume: number
/** User-defined agents (BYO CLI) appended to the Add menus. */
customAgents: CustomAgent[]
+ /** One Bifrost-compatible endpoint/key used by every model-switch-capable base harness. */
+ modelGateway: ModelGatewaySettings
/** Managed Claude accounts (config-dir isolated). See ClaudeAccount. */
claudeAccounts: ClaudeAccount[]
/** Custom display label for the SYSTEM Claude account (~/.claude) in pickers/settings.
@@ -1152,6 +1162,7 @@ export const DEFAULT_SETTINGS: Settings = {
soundEffects: true,
soundVolume: 0.5,
customAgents: [],
+ modelGateway: { baseUrl: '', apiKey: '' },
claudeAccounts: [],
systemAccountLabel: '',
// All three builtin agents (Claude/Codex/Gemini) show in the Add menus out of the box.
@@ -2043,10 +2054,13 @@ export interface AgentApi {
agentId: AgentId
customAgent?: CustomAgent
initialPrompt?: string
+ model?: string
permissionMode?: AgentPermissionMode
sessionId?: string
sessionIdFlagSupported?: boolean
}): Promise<{ command: string; missingEnv: string[] }>
+ /** Query the configured gateway's OpenAI-compatible `/v1/models` endpoint. Never rejects. */
+ discoverModels(settings: ModelGatewaySettings): Promise<ModelDiscoveryResult>
}
export interface HandoffApi {