An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.
TypeScript agentic-browseragentic-browsingagy-cliaiai-agentai-browser-extensionai-toolsbrave-extensionbrowser-agentbrowser-automationbrowser-extensionbrowser-usebrowserskillchrome-extensionclaude-codecodexfirefox-addonmcp-servernanobrowserweb-automation
feat(agents): offer each agent CLI's own model list in the picker, read in the background, kept when a read fails, and never passed on when a CLI could take it for a flag
Shahriarb1c8c447f630
diff --git a/src/daemon/agent/config.test.ts b/src/daemon/agent/config.test.tsindex 35da77a..3d6ab89 100644--- a/src/daemon/agent/config.test.ts+++ b/src/daemon/agent/config.test.ts@@ -27,7 +27,7 @@ beforeEach(() => {const DEFAULTS: AgentConfig = {agent: 'claude',agents: {- claude: { bin: 'claude', model: 'claude-sonnet-5' },+ claude: { bin: 'claude', model: 'sonnet' },codex: { bin: 'codex' },antigravity: { bin: 'agy' },vibe: { bin: 'vibe' },@@ -74,6 +74,12 @@ describe('reading config.json', () => {expect(readAgentConfig().agents.claude.model).toBe('claude-haiku-4-5');});+ test('a model a CLI could read as a flag is left out, so the run falls back to the default instead', () => {+ store({ agents: { claude: { model: '--dangerously-skip-permissions' }, codex: { model: 'gpt 5' }, cursor: { model: 'claude-opus-4-8[effort=high]' } } });+ const { agents } = readAgentConfig();+ expect([agents.claude.model, agents.codex.model, agents.cursor.model]).toEqual(['sonnet', undefined, 'claude-opus-4-8[effort=high]']);+ });+test('keys the daemon does not model are carried through', () => {store({ screenshotDir: '~/Pictures', downloadTtlDays: 3, requireApproval: [] });expect(readAgentConfig()).toMatchObject({ screenshotDir: '~/Pictures', downloadTtlDays: 3, requireApproval: [] });@@ -129,7 +135,16 @@ describe('writing config.json', () => {test("clearing Claude Code's model also removes the pre-0.2 spelling, so it cannot come back", () => {store({ model: 'claude-opus-5', agents: { claude: { model: 'claude-opus-5' } } });writeAgentModel('claude', '');- expect([stored(), readAgentConfig().agents.claude.model]).toEqual([{}, 'claude-sonnet-5']);+ expect([stored(), readAgentConfig().agents.claude.model]).toEqual([{}, 'sonnet']);+ });++ test('a model a CLI could read as a flag is refused, and nothing is written', () => {+ store({ agents: { codex: { model: 'gpt-5.5' } } });+ expect([writeAgentModel('codex', '-c sandbox_mode=off'), writeAgentModel('codex', 'gpt\n5'), stored()]).toEqual([+ false,+ false,+ { agents: { codex: { model: 'gpt-5.5' } } },+ ]);});describe('guardrail overrides', () => {diff --git a/src/daemon/agent/config.ts b/src/daemon/agent/config.tsindex 939e528..242990c 100644--- a/src/daemon/agent/config.ts+++ b/src/daemon/agent/config.ts@@ -1,9 +1,10 @@import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { join } from 'node:path';-import { AGENTS, AGENT_KINDS, DEFAULT_AGENT, isAgentKind, type AgentKind } from '@/lib/agents/catalog';+import { AGENTS, AGENT_KINDS, DEFAULT_AGENT, isAgentKind, isModelId, type AgentKind } from '@/lib/agents/catalog';import { FENCE_SETTING, UNATTENDED_SETTING, type GuardrailValue, type RuleEffect } from '@/lib/settings/guardrails';import type { GuardrailConfig } from '../guardrails';import { stateDir } from '../lockfile';+import { log } from '../log';export interface AgentSettings {/** Binary name or absolute path. Defaults to the agent's own command name. */@@ -80,7 +81,7 @@ function clamp(value: unknown, { fallback, max }: { fallback: number; max: numbeexport const configPath = join(stateDir, 'config.json');const DEFAULT_MODEL: Partial<Record<AgentKind, string>> = {- claude: 'claude-sonnet-5',+ claude: 'sonnet',};const DEFAULT_APPROVALS = ['page.submitForm'];@@ -125,7 +126,7 @@ function settingsFor(stored: StoredConfig, kind: AgentKind): AgentSettings {const legacy = kind === 'claude' ? { bin: stored.claudeBin, model: stored.model, effort: stored.effort } : {};return {bin: text(scoped.bin) ?? text(legacy.bin) ?? AGENTS[kind].bin,- model: text(scoped.model) ?? text(legacy.model) ?? DEFAULT_MODEL[kind],+ model: modelOf(kind, scoped.model) ?? modelOf(kind, legacy.model) ?? DEFAULT_MODEL[kind],effort: text(scoped.effort) ?? text(legacy.effort),};}@@ -133,6 +134,14 @@ function settingsFor(stored: StoredConfig, kind: AgentKind): AgentSettings {const text = (value: unknown): string | undefined =>typeof value === 'string' && value.trim() ? value.trim() : undefined;+/** A hand-edited model a CLI could read as a flag is left out, so the run falls back rather than failing. */+function modelOf(kind: AgentKind, value: unknown): string | undefined {+ const model = text(value);+ if (model === undefined || isModelId(model)) return model;+ log(`ignoring ${kind} model ${JSON.stringify(model)} — a model id starts with a letter or digit and has no spaces`);+ return undefined;+}+export interface ActiveAgent extends AgentSettings {kind: AgentKind;}@@ -150,12 +159,14 @@ export function writeActiveAgent(kind: AgentKind): void {/*** Sets or clears one agent's model, leaving every other key in config.json untouched. Claude's* pre-0.2 top-level `model` spelling is removed alongside, so a cleared pick cannot resurface it.+ * False, and nothing written, when the model is not one `isModelId` accepts.*/-export function writeAgentModel(kind: AgentKind, model: string | null): void {+export function writeAgentModel(kind: AgentKind, model: string | null): boolean {+ const value = text(model);+ if (value !== undefined && !isModelId(value)) return false;const stored = readStored();const agents = { ...(stored.agents ?? {}) };const scoped = { ...(agents[kind] ?? {}) };- const value = text(model);if (value) scoped.model = value;else delete scoped.model;if (Object.keys(scoped).length) agents[kind] = scoped;@@ -166,6 +177,7 @@ export function writeAgentModel(kind: AgentKind, model: string | null): void {else delete next.agents;if (kind === 'claude') delete next.model;write(next);+ return true;}/**diff --git a/src/daemon/agent/runners/antigravity.ts b/src/daemon/agent/runners/antigravity.tsindex 1bee934..cb6b504 100644--- a/src/daemon/agent/runners/antigravity.ts+++ b/src/daemon/agent/runners/antigravity.ts@@ -7,7 +7,7 @@ import { stateDir } from '../../lockfile';import { log } from '../../log';import { MCP_SERVER_NAME } from './claude';import { effortOf, parseJsonLine, sweepRunDirs } from './util';-import type { JsonContext, McpServer, Plan, Runner, RunMode, StreamContext, StreamReader } from './types';+import type { JsonContext, Listing, McpServer, Plan, Runner, RunMode, StreamContext, StreamReader } from './types';/** Antigravity reads MCP servers and instructions from the directory it runs in, not from flags. */const MCP_CONFIG = '.agents/mcp_config.json';@@ -68,6 +68,8 @@ export const antigravityRunner: Runner = {workspace: (mode: RunMode) => join(stateDir, 'agents', 'antigravity', mode),+ models: { args: ['models'], parse: listedModels },+skillDirs: () => {try {return readFileSync(skillsIndexPath, 'utf8')@@ -274,3 +276,12 @@ function lastFrame(stdout: string): Frame | null {}const ownTool = (name: string) => /browsentic|^mcp/i.test(name);++/** `agy models` prints one `id<TAB>label` line per model, and exits 1 when signed out. */+function listedModels({ stdout, code }: Listing): string[] | null {+ if (code !== 0) return null;+ return stdout.split('\n').flatMap((line) => {+ const [id, label] = line.split('\t');+ return label !== undefined && id.trim() ? [id.trim()] : [];+ });+}diff --git a/src/daemon/agent/runners/codex.ts b/src/daemon/agent/runners/codex.tsindex 66b622e..e61dd34 100644--- a/src/daemon/agent/runners/codex.ts+++ b/src/daemon/agent/runners/codex.ts@@ -107,6 +107,12 @@ export const codexRunner: Runner = {skillDirs: () => [join(homedir(), '.codex', 'skills'), join(homedir(), '.codex', 'prompts')],+ // Codex keeps the account's models in a cache it refreshes itself, so reading them spawns nothing.+ models: {+ file: () => join(process.env.CODEX_HOME || join(homedir(), '.codex'), 'models_cache.json'),+ parse: listedModels,+ },+stream(context: StreamContext): Plan {const { settings, mcp, research } = context;const server = `mcp_servers.${MCP_SERVER_NAME}`;@@ -312,3 +318,21 @@ const tomlTable = (values: Record<string, string>): string =>`{${Object.entries(values).map(([key, value]) => `${key}=${tomlString(value)}`).join(',')}}`;++interface CachedModel {+ slug?: unknown;+ visibility?: unknown;+ priority?: unknown;+}++/** The models Codex's own picker offers, in its order. Hidden ones are Codex's internal helpers. */+function listedModels(content: string): string[] | null {+ const models = parseJsonLine<{ models?: CachedModel[] }>(content)?.models;+ if (!Array.isArray(models)) return null;+ return models+ .filter((model) => model.visibility === 'list' && typeof model.slug === 'string')+ .sort((a, b) => rank(a) - rank(b))+ .map((model) => model.slug as string);+}++const rank = (model: CachedModel) => (typeof model.priority === 'number' ? model.priority : Number.MAX_SAFE_INTEGER);diff --git a/src/daemon/agent/runners/cursor.ts b/src/daemon/agent/runners/cursor.tsindex c266510..7d3650c 100644--- a/src/daemon/agent/runners/cursor.ts+++ b/src/daemon/agent/runners/cursor.ts@@ -7,7 +7,7 @@ import { stateDir } from '../../lockfile';import type { AgentSettings } from '../config';import { MCP_SERVER_NAME } from './claude';import { conversationDir, parseJsonLine, sweepRunDirs } from './util';-import type { JsonContext, Plan, Runner, RunMode, StreamContext, StreamReader, StreamSink } from './types';+import type { JsonContext, Listing, Plan, Runner, RunMode, StreamContext, StreamReader, StreamSink } from './types';/*** Cursor takes its MCP server, its permissions and its sandbox from files in the folder it starts@@ -58,6 +58,8 @@ export const cursorRunner: Runner = {skillDirs: () => [join(cursorHome(), 'skills'), join(homedir(), '.agents', 'skills')],+ models: { args: ['models'], parse: listedModels },+stream(context: StreamContext): Plan {const { settings, research } = context;const base = this.workspace('run');@@ -306,3 +308,12 @@ function lastResult(stdout: string): Event | null {}return null;}++/** `cursor-agent models` prints `id - label` lines under a heading, and exits 1 when signed out. */+function listedModels({ stdout, code }: Listing): string[] | null {+ if (code !== 0) return null;+ const lines = plain(stdout).split('\n');+ const heading = lines.findIndex((line) => /^available models$/i.test(line.trim()));+ if (heading === -1) return null;+ return lines.slice(heading + 1).flatMap((line) => /^(\S+) - \S/.exec(line.trim())?.slice(1, 2) ?? []);+}diff --git a/src/daemon/agent/runners/drive.ts b/src/daemon/agent/runners/drive.tsindex 43ad54a..663f804 100644--- a/src/daemon/agent/runners/drive.ts+++ b/src/daemon/agent/runners/drive.ts@@ -59,9 +59,7 @@ export function launch(const dropped = sealedAway(kind, process.env);if (dropped.length) log(`sealed ${dropped.length} credential-shaped variables out of the ${kind} environment`);- const env: NodeJS.ProcessEnv = sealEnv(kind, process.env);- for (const key of STRIPPED) delete env[key];- Object.assign(env, plan.env);+ const env = { ...childEnv(kind), ...plan.env };const child = spawn(settings.bin, plan.args, {cwd: plan.cwd,@@ -79,6 +77,13 @@ export function launch(return { child, release: () => signal.removeEventListener('abort', kill), stop: kill };}+/** The environment any process of this agent's CLI starts with, before a plan adds its own. */+export function childEnv(kind: AgentKind): NodeJS.ProcessEnv {+ const env = sealEnv(kind, process.env);+ for (const key of STRIPPED) delete env[key];+ return env;+}+function notInstalled(runner: Runner, settings: AgentSettings): RunError {const agent = AGENTS[runner.kind];return new RunError(diff --git a/src/daemon/agent/runners/fixtures/README.md b/src/daemon/agent/runners/fixtures/README.mdindex 4172433..6a2d71e 100644--- a/src/daemon/agent/runners/fixtures/README.md+++ b/src/daemon/agent/runners/fixtures/README.md@@ -15,3 +15,8 @@ What each agent CLI printed on stdout, one event per line, for the reader testsproduce or a CLI that was not installed. Its first line says so.Lines starting with `#` are comments, and the tests skip them.++- `<cli version>-models.txt` and `-models-signed-out.txt` are what the CLI's model-listing command+ printed, for `../models.test.ts`: stdout, then stderr after a `# stderr` line, with the exit code+ in a `# exit` line. `codex/<version>-models_cache.json` is Codex's own cache, cut to the fields the+ lister reads, with the account identity and etag replaced.diff --git a/src/daemon/agent/runners/fixtures/antigravity/1.2.11-models-signed-out.txt b/src/daemon/agent/runners/fixtures/antigravity/1.2.11-models-signed-out.txtnew file mode 100644index 0000000..2f311aa--- /dev/null+++ b/src/daemon/agent/runners/fixtures/antigravity/1.2.11-models-signed-out.txt@@ -0,0 +1,5 @@+# `agy models` 1.2.11 with an empty HOME, recorded 2026-09-25.+# exit 1+# stderr+Fetching available models...+Error: Please sign in to view available models. Launch the CLI without arguments to sign in.diff --git a/src/daemon/agent/runners/fixtures/antigravity/1.2.11-models.txt b/src/daemon/agent/runners/fixtures/antigravity/1.2.11-models.txtnew file mode 100644index 0000000..04c4da8--- /dev/null+++ b/src/daemon/agent/runners/fixtures/antigravity/1.2.11-models.txt@@ -0,0 +1,18 @@+# `agy models` 1.2.11, signed in, recorded 2026-09-25.+# exit 0+gemini-3.8-flash-high Gemini 3.8 Flash (High)+gemini-3.8-flash-medium Gemini 3.8 Flash (Medium)+gemini-3.8-flash-low Gemini 3.8 Flash (Low)+gemini-3.7-flash-high Gemini 3.7 Flash (High)+gemini-3.7-flash-medium Gemini 3.7 Flash (Medium)+gemini-3.7-flash-low Gemini 3.7 Flash (Low)+gemini-3.6-flash-high Gemini 3.6 Flash (High)+gemini-3.6-flash-medium Gemini 3.6 Flash (Medium)+gemini-3.6-flash-low Gemini 3.6 Flash (Low)+gemini-3.1-pro-high Gemini 3.1 Pro (High)+gemini-3.1-pro-low Gemini 3.1 Pro (Low)+claude-sonnet-4-6 Claude Sonnet 4.6 (Thinking)+claude-opus-4-6-thinking Claude Opus 4.6 (Thinking)+gpt-oss-120b-medium GPT-OSS 120B (Medium)+# stderr+Fetching available models...diff --git a/src/daemon/agent/runners/fixtures/codex/0.155.1-models_cache.json b/src/daemon/agent/runners/fixtures/codex/0.155.1-models_cache.jsonnew file mode 100644index 0000000..1e472e0--- /dev/null+++ b/src/daemon/agent/runners/fixtures/codex/0.155.1-models_cache.json@@ -0,0 +1,43 @@+{+ "fetched_at": "2026-09-22T18:00:29.244034Z",+ "etag": "\"etag\"",+ "client_version": "0.155.1",+ "identity": "<identity>",+ "models": [+ {+ "slug": "gpt-reserve",+ "display_name": "GPT-Reserve",+ "visibility": "hide",+ "priority": 3,+ "supported_in_api": true+ },+ {+ "slug": "gpt-5.6-terra",+ "display_name": "GPT-5.6-Terra",+ "visibility": "list",+ "priority": 7,+ "supported_in_api": true+ },+ {+ "slug": "gpt-5.6-luna",+ "display_name": "GPT-5.6-Luna",+ "visibility": "list",+ "priority": 8,+ "supported_in_api": true+ },+ {+ "slug": "gpt-5.5",+ "display_name": "GPT-5.5",+ "visibility": "list",+ "priority": 12,+ "supported_in_api": true+ },+ {+ "slug": "codex-auto-review",+ "display_name": "Codex Auto Review",+ "visibility": "hide",+ "priority": 43,+ "supported_in_api": true+ }+ ]+}diff --git a/src/daemon/agent/runners/fixtures/cursor/2026.09.18-models-signed-out.txt b/src/daemon/agent/runners/fixtures/cursor/2026.09.18-models-signed-out.txtnew file mode 100644index 0000000..78987af--- /dev/null+++ b/src/daemon/agent/runners/fixtures/cursor/2026.09.18-models-signed-out.txt@@ -0,0 +1,4 @@+# `cursor-agent models` 2026.09.18-9a7762b with an empty HOME, recorded 2026-09-25.+# exit 1+# stderr+Error: Authentication required. Run 'agent login', pass --api-key/--auth-token, or set CURSOR_API_KEY/CURSOR_AUTH_TOKEN.diff --git a/src/daemon/agent/runners/fixtures/cursor/2026.09.18-models.txt b/src/daemon/agent/runners/fixtures/cursor/2026.09.18-models.txtnew file mode 100644index 0000000..883d24a--- /dev/null+++ b/src/daemon/agent/runners/fixtures/cursor/2026.09.18-models.txt@@ -0,0 +1,247 @@+# `cursor-agent models` 2026.09.18-9a7762b, signed in, recorded 2026-09-25.+# exit 0+Available models++auto - Auto (current, default)+gpt-5.3-codex-low - Codex 5.3 Low+gpt-5.3-codex-low-fast - Codex 5.3 Low Fast+gpt-5.3-codex - Codex 5.3+gpt-5.3-codex-fast - Codex 5.3 Fast+gpt-5.3-codex-high - Codex 5.3 High+gpt-5.3-codex-high-fast - Codex 5.3 High Fast+gpt-5.3-codex-xhigh - Codex 5.3 Extra High+gpt-5.3-codex-xhigh-fast - Codex 5.3 Extra High Fast+gpt-5.2 - GPT-5.2+composer-2.5 - Composer 2.5+claude-opus-5-thinking-high - Claude Opus 5 1M Thinking+claude-opus-5-thinking-high-fast - Claude Opus 5 1M Thinking Fast+gpt-5.6-sol-high - GPT-5.6 Sol 1M High+gpt-5.6-sol-high-fast - GPT-5.6 Sol 1M High Fast+gpt-5.6-sol-xhigh - GPT-5.6 Sol 1M Extra High+gpt-5.6-sol-xhigh-fast - GPT-5.6 Sol 1M Extra High Fast+claude-fable-5-thinking-high - Claude Fable 5 1M Thinking (NO ZDR)+claude-fable-5-thinking-xhigh - Claude Fable 5 1M Extra High Thinking (NO ZDR)+cursor-grok-4.5-high - Grok 4.5+cursor-grok-4.5-high-fast - Grok 4.5 Fast+gemini-3.7-flash-high - Gemini 3.7 Flash+claude-sonnet-5-thinking-high - Claude Sonnet 5 1M Thinking+claude-sonnet-5-thinking-xhigh - Claude Sonnet 5 1M Extra High Thinking+gpt-5.6-luna-high - GPT-5.6 Luna 1M High+grok-4.7-low - Grok 4.7 Low+grok-4.7-low-fast - Grok 4.7 Low Fast+grok-4.7-medium - Grok 4.7 Medium+grok-4.7-medium-fast - Grok 4.7 Medium Fast+grok-4.7-high - Grok 4.7 High+grok-4.7-high-fast - Grok 4.7 High Fast+grok-4.7-xhigh - Grok 4.7 Extra High+grok-4.7-xhigh-fast - Grok 4.7 Extra High Fast+cursor-grok-4.6-low - Grok 4.6 Low+cursor-grok-4.6-low-fast - Grok 4.6 Low Fast+cursor-grok-4.6-medium - Grok 4.6 Medium+cursor-grok-4.6-medium-fast - Grok 4.6 Medium Fast+cursor-grok-4.6-high - Grok 4.6+cursor-grok-4.6-high-fast - Grok 4.6 Fast+cursor-grok-4.6-xhigh - Grok 4.6 Extra High+cursor-grok-4.6-xhigh-fast - Grok 4.6 Extra High Fast+composer-2.5-fast - Composer 2.5 Fast+claude-opus-5-5-low - Claude Opus 5.5 1M Low+claude-opus-5-5-low-fast - Claude Opus 5.5 1M Low Fast+claude-opus-5-5-medium - Claude Opus 5.5 1M+claude-opus-5-5-medium-fast - Claude Opus 5.5 1M Fast+claude-opus-5-5-high - Claude Opus 5.5 1M High+claude-opus-5-5-high-fast - Claude Opus 5.5 1M High Fast+claude-opus-5-5-xhigh - Claude Opus 5.5 1M Extra High+claude-opus-5-5-xhigh-fast - Claude Opus 5.5 1M Extra High Fast+claude-opus-5-5-max - Claude Opus 5.5 1M Max+claude-opus-5-5-max-fast - Claude Opus 5.5 1M Max Fast+claude-opus-5-low - Claude Opus 5 1M Low+claude-opus-5-low-fast - Claude Opus 5 1M Low Fast+claude-opus-5-medium - Claude Opus 5 1M Medium+claude-opus-5-medium-fast - Claude Opus 5 1M Medium Fast+claude-opus-5-high - Claude Opus 5 1M+claude-opus-5-high-fast - Claude Opus 5 1M Fast+claude-opus-5-thinking-low - Claude Opus 5 1M Low Thinking+claude-opus-5-thinking-low-fast - Claude Opus 5 1M Low Thinking Fast+claude-opus-5-thinking-medium - Claude Opus 5 1M Medium Thinking+claude-opus-5-thinking-medium-fast - Claude Opus 5 1M Medium Thinking Fast+claude-opus-5-thinking-xhigh - Claude Opus 5 1M Extra High Thinking+claude-opus-5-thinking-xhigh-fast - Claude Opus 5 1M Extra High Thinking Fast+claude-opus-5-thinking-max - Claude Opus 5 1M Max Thinking+claude-opus-5-thinking-max-fast - Claude Opus 5 1M Max Thinking Fast+claude-opus-4-8-low - Claude Opus 4.8 1M Low+claude-opus-4-8-low-fast - Claude Opus 4.8 1M Low Fast+claude-opus-4-8-medium - Claude Opus 4.8 1M Medium+claude-opus-4-8-medium-fast - Claude Opus 4.8 1M Medium Fast+claude-opus-4-8-high - Claude Opus 4.8 1M+claude-opus-4-8-high-fast - Claude Opus 4.8 1M Fast+claude-opus-4-8-xhigh - Claude Opus 4.8 1M Extra High+claude-opus-4-8-xhigh-fast - Claude Opus 4.8 1M Extra High Fast+claude-opus-4-8-max - Claude Opus 4.8 1M Max+claude-opus-4-8-max-fast - Claude Opus 4.8 1M Max Fast+claude-opus-4-8-thinking-low - Claude Opus 4.8 1M Low Thinking+claude-opus-4-8-thinking-low-fast - Claude Opus 4.8 1M Low Thinking Fast+claude-opus-4-8-thinking-medium - Claude Opus 4.8 1M Medium Thinking+claude-opus-4-8-thinking-medium-fast - Claude Opus 4.8 1M Medium Thinking Fast+claude-opus-4-8-thinking-high - Claude Opus 4.8 1M Thinking+claude-opus-4-8-thinking-high-fast - Claude Opus 4.8 1M Thinking Fast+claude-opus-4-8-thinking-xhigh - Claude Opus 4.8 1M Extra High Thinking+claude-opus-4-8-thinking-xhigh-fast - Claude Opus 4.8 1M Extra High Thinking Fast+claude-opus-4-8-thinking-max - Claude Opus 4.8 1M Max Thinking+claude-opus-4-8-thinking-max-fast - Claude Opus 4.8 1M Max Thinking Fast+gpt-5.6-sol-none - GPT-5.6 Sol 1M None+gpt-5.6-sol-none-fast - GPT-5.6 Sol 1M None Fast+gpt-5.6-sol-low - GPT-5.6 Sol 1M Low+gpt-5.6-sol-low-fast - GPT-5.6 Sol 1M Low Fast+gpt-5.6-sol-medium - GPT-5.6 Sol 1M+gpt-5.6-sol-medium-fast - GPT-5.6 Sol 1M Fast+gpt-5.6-sol-max - GPT-5.6 Sol 1M Max+gpt-5.6-sol-max-fast - GPT-5.6 Sol 1M Max Fast+gpt-5.5-none - GPT-5.5 1M None+gpt-5.5-none-fast - GPT-5.5 None Fast+gpt-5.5-low - GPT-5.5 1M Low+gpt-5.5-low-fast - GPT-5.5 Low Fast+gpt-5.5-medium - GPT-5.5 1M+gpt-5.5-medium-fast - GPT-5.5 Fast+gpt-5.5-high - GPT-5.5 1M High+gpt-5.5-high-fast - GPT-5.5 High Fast+gpt-5.5-extra-high - GPT-5.5 1M Extra High+gpt-5.5-extra-high-fast - GPT-5.5 Extra High Fast+claude-fable-5-1-low - Claude Fable 5.1 1M Low (NO ZDR)+claude-fable-5-1-medium - Claude Fable 5.1 1M Medium (NO ZDR)+claude-fable-5-1-high - Claude Fable 5.1 1M (NO ZDR)+claude-fable-5-1-xhigh - Claude Fable 5.1 1M Extra High (NO ZDR)+claude-fable-5-1-max - Claude Fable 5.1 1M Max (NO ZDR)+claude-fable-5-1-thinking-low - Claude Fable 5.1 1M Low Thinking (NO ZDR)+claude-fable-5-1-thinking-medium - Claude Fable 5.1 1M Medium Thinking (NO ZDR)+claude-fable-5-1-thinking-high - Claude Fable 5.1 1M Thinking (NO ZDR)+claude-fable-5-1-thinking-xhigh - Claude Fable 5.1 1M Extra High Thinking (NO ZDR)+claude-fable-5-1-thinking-max - Claude Fable 5.1 1M Max Thinking (NO ZDR)+claude-fable-5-low - Claude Fable 5 1M Low (NO ZDR)+claude-fable-5-medium - Claude Fable 5 1M Medium (NO ZDR)+claude-fable-5-high - Claude Fable 5 1M (NO ZDR)+claude-fable-5-xhigh - Claude Fable 5 1M Extra High (NO ZDR)+claude-fable-5-max - Claude Fable 5 1M Max (NO ZDR)+claude-fable-5-thinking-low - Claude Fable 5 1M Low Thinking (NO ZDR)+claude-fable-5-thinking-medium - Claude Fable 5 1M Medium Thinking (NO ZDR)+claude-fable-5-thinking-max - Claude Fable 5 1M Max Thinking (NO ZDR)+cursor-grok-4.5-low - Grok 4.5 Low+cursor-grok-4.5-low-fast - Grok 4.5 Low Fast+cursor-grok-4.5-medium - Grok 4.5 Medium+cursor-grok-4.5-medium-fast - Grok 4.5 Medium Fast+gemini-3.8-flash-low - Gemini 3.8 Flash Low+gemini-3.8-flash-medium - Gemini 3.8 Flash Medium+gemini-3.8-flash-high - Gemini 3.8 Flash High+gemini-3.7-flash-low - Gemini 3.7 Flash Low+gemini-3.7-flash-medium - Gemini 3.7 Flash Medium+muse-spark-1.3-minimal - Muse Spark 1.3 1M Minimal+muse-spark-1.3-low - Muse Spark 1.3 1M Low+muse-spark-1.3-medium - Muse Spark 1.3 1M Medium+muse-spark-1.3-high - Muse Spark 1.3 1M+muse-spark-1.3-xhigh - Muse Spark 1.3 1M Extra High+muse-spark-1.3-max - Muse Spark 1.3 1M Max+gpt-5.6-terra-none - GPT-5.6 Terra 1M None+gpt-5.6-terra-none-fast - GPT-5.6 Terra 1M None Fast+gpt-5.6-terra-low - GPT-5.6 Terra 1M Low+gpt-5.6-terra-low-fast - GPT-5.6 Terra 1M Low Fast+gpt-5.6-terra-medium - GPT-5.6 Terra 1M+gpt-5.6-terra-medium-fast - GPT-5.6 Terra 1M Fast+gpt-5.6-terra-high - GPT-5.6 Terra 1M High+gpt-5.6-terra-high-fast - GPT-5.6 Terra 1M High Fast+gpt-5.6-terra-xhigh - GPT-5.6 Terra 1M Extra High+gpt-5.6-terra-xhigh-fast - GPT-5.6 Terra 1M Extra High Fast+gpt-5.6-terra-max - GPT-5.6 Terra 1M Max+gpt-5.6-terra-max-fast - GPT-5.6 Terra 1M Max Fast+claude-sonnet-5-low - Claude Sonnet 5 1M Low+claude-sonnet-5-medium - Claude Sonnet 5 1M Medium+claude-sonnet-5-high - Claude Sonnet 5 1M+claude-sonnet-5-xhigh - Claude Sonnet 5 1M Extra High+claude-sonnet-5-max - Claude Sonnet 5 1M Max+claude-sonnet-5-thinking-low - Claude Sonnet 5 1M Low Thinking+claude-sonnet-5-thinking-medium - Claude Sonnet 5 1M Medium Thinking+claude-sonnet-5-thinking-max - Claude Sonnet 5 1M Max Thinking+claude-4.6-sonnet-medium - Claude Sonnet 4.6 1M+claude-4.6-sonnet-medium-thinking - Claude Sonnet 4.6 1M Thinking+claude-opus-4-7-low - Claude Opus 4.7 1M Low+claude-opus-4-7-low-fast - Claude Opus 4.7 1M Low Fast+claude-opus-4-7-medium - Claude Opus 4.7 1M Medium+claude-opus-4-7-medium-fast - Claude Opus 4.7 1M Medium Fast+claude-opus-4-7-high - Claude Opus 4.7 1M High+claude-opus-4-7-high-fast - Claude Opus 4.7 1M High Fast+claude-opus-4-7-xhigh - Claude Opus 4.7 1M+claude-opus-4-7-xhigh-fast - Claude Opus 4.7 1M Fast+claude-opus-4-7-max - Claude Opus 4.7 1M Max+claude-opus-4-7-max-fast - Claude Opus 4.7 1M Max Fast+claude-opus-4-7-thinking-low - Claude Opus 4.7 1M Low Thinking+claude-opus-4-7-thinking-low-fast - Claude Opus 4.7 1M Low Thinking Fast+claude-opus-4-7-thinking-medium - Claude Opus 4.7 1M Medium Thinking+claude-opus-4-7-thinking-medium-fast - Claude Opus 4.7 1M Medium Thinking Fast+claude-opus-4-7-thinking-high - Claude Opus 4.7 1M High Thinking+claude-opus-4-7-thinking-high-fast - Claude Opus 4.7 1M High Thinking Fast+claude-opus-4-7-thinking-xhigh - Claude Opus 4.7 1M Thinking+claude-opus-4-7-thinking-xhigh-fast - Claude Opus 4.7 1M Thinking Fast+claude-opus-4-7-thinking-max - Claude Opus 4.7 1M Max Thinking+claude-opus-4-7-thinking-max-fast - Claude Opus 4.7 1M Max Thinking Fast+gpt-5.4-low - GPT-5.4 1M Low+gpt-5.4-medium - GPT-5.4 1M+gpt-5.4-medium-fast - GPT-5.4 Fast+gpt-5.4-high - GPT-5.4 1M High+gpt-5.4-high-fast - GPT-5.4 High Fast+gpt-5.4-xhigh - GPT-5.4 1M Extra High+gpt-5.4-xhigh-fast - GPT-5.4 Extra High Fast+claude-4.6-opus-high - Claude Opus 4.6 1M+claude-4.6-opus-max - Claude Opus 4.6 1M Max+claude-4.6-opus-high-thinking - Claude Opus 4.6 1M Thinking+claude-4.6-opus-max-thinking - Claude Opus 4.6 1M Max Thinking+claude-4.5-opus-high - Claude Opus 4.5+claude-4.5-opus-high-thinking - Claude Opus 4.5 Thinking+gpt-5.2-low - GPT-5.2 Low+gpt-5.2-low-fast - GPT-5.2 Low Fast+gpt-5.2-fast - GPT-5.2 Fast+gpt-5.2-high - GPT-5.2 High+gpt-5.2-high-fast - GPT-5.2 High Fast+gpt-5.2-xhigh - GPT-5.2 Extra High+gpt-5.2-xhigh-fast - GPT-5.2 Extra High Fast+gpt-5.6-luna-none - GPT-5.6 Luna 1M None+gpt-5.6-luna-none-fast - GPT-5.6 Luna 1M None Fast+gpt-5.6-luna-low - GPT-5.6 Luna 1M Low+gpt-5.6-luna-low-fast - GPT-5.6 Luna 1M Low Fast+gpt-5.6-luna-medium - GPT-5.6 Luna 1M+gpt-5.6-luna-medium-fast - GPT-5.6 Luna 1M Fast+gpt-5.6-luna-high-fast - GPT-5.6 Luna 1M High Fast+gpt-5.6-luna-xhigh - GPT-5.6 Luna 1M Extra High+gpt-5.6-luna-xhigh-fast - GPT-5.6 Luna 1M Extra High Fast+gpt-5.6-luna-max - GPT-5.6 Luna 1M Max+gpt-5.6-luna-max-fast - GPT-5.6 Luna 1M Max Fast+gemini-3.6-flash-minimal - Gemini 3.6 Flash Minimal+gemini-3.6-flash-low - Gemini 3.6 Flash Low+gemini-3.6-flash-medium - Gemini 3.6 Flash Medium+gemini-3.6-flash-high - Gemini 3.6 Flash+gemini-3.1-pro - Gemini 3.1 Pro+gpt-5.4-mini-none - GPT-5.4 Mini None+gpt-5.4-mini-low - GPT-5.4 Mini Low+gpt-5.4-mini-medium - GPT-5.4 Mini+gpt-5.4-mini-high - GPT-5.4 Mini High+gpt-5.4-mini-xhigh - GPT-5.4 Mini Extra High+gpt-5.4-nano-none - GPT-5.4 Nano None+gpt-5.4-nano-low - GPT-5.4 Nano Low+gpt-5.4-nano-medium - GPT-5.4 Nano+gpt-5.4-nano-high - GPT-5.4 Nano High+gpt-5.4-nano-xhigh - GPT-5.4 Nano Extra High+claude-4.5-sonnet - Claude Sonnet 4.5+claude-4.5-sonnet-thinking - Claude Sonnet 4.5 Thinking+gpt-5.1-low - GPT-5.1 Low+gpt-5.1 - GPT-5.1+gpt-5.1-high - GPT-5.1 High+gemini-3-flash - Gemini 3 Flash+gemini-3.5-flash - Gemini 3.5 Flash+claude-4-sonnet - Claude Sonnet 4+claude-4-sonnet-thinking - Claude Sonnet 4 Thinking+gpt-5-mini - GPT-5 Mini+kimi-k3-low - Kimi K3 Low+kimi-k3-high - Kimi K3 High+kimi-k3-max - Kimi K3+kimi-k2.7-code - Kimi K2.7 Code+glm-5.2-high - GLM 5.2+glm-5.2-max - GLM 5.2 Max++Tip: use --model <id> (or /model <id> in interactive mode) to switch. Parameterized models also accept quoted overrides, e.g. --model 'claude-opus-4-8[context=1m,effort=high,fast=false]'.diff --git a/src/daemon/agent/runners/fixtures/grok/1.0.40-models-signed-out.txt b/src/daemon/agent/runners/fixtures/grok/1.0.40-models-signed-out.txtnew file mode 100644index 0000000..734dbfa--- /dev/null+++ b/src/daemon/agent/runners/fixtures/grok/1.0.40-models-signed-out.txt@@ -0,0 +1,9 @@+# `grok models` 1.0.40 with an empty HOME: exit 0, and a built-in list the account may not have, recorded 2026-09-25.+# exit 0+You are not authenticated.++Default model: grok-4.6++Available models:+ * grok-4.6 (default)+ - grok-4.5diff --git a/src/daemon/agent/runners/fixtures/grok/1.0.40-models.txt b/src/daemon/agent/runners/fixtures/grok/1.0.40-models.txtnew file mode 100644index 0000000..061359b--- /dev/null+++ b/src/daemon/agent/runners/fixtures/grok/1.0.40-models.txt@@ -0,0 +1,8 @@+# `grok models` 1.0.40, signed in with grok.com, recorded 2026-09-25.+# exit 0+You are logged in with grok.com.++Default model: grok-4.7++Available models:+ * grok-4.7 (default)diff --git a/src/daemon/agent/runners/fixtures/support.ts b/src/daemon/agent/runners/fixtures/support.tsindex 4381b30..297255d 100644--- a/src/daemon/agent/runners/fixtures/support.ts+++ b/src/daemon/agent/runners/fixtures/support.ts@@ -3,7 +3,7 @@ import { homedir } from 'node:os';import type { AgentKind } from '@/lib/agents/catalog';import { stateDir } from '../../../lockfile';import type { AgentSettings } from '../../config';-import type { JsonContext, McpServer, Plan, Runner, StreamContext, StreamSink } from '../types';+import type { JsonContext, Listing, McpServer, Plan, Runner, StreamContext, StreamSink } from '../types';export type Signal = keyof StreamSink;export type Call = [Signal, ...unknown[]];@@ -14,6 +14,20 @@ export function transcript(agent: AgentKind, name: string): string[] {.filter((line) => line.trim() && !line.startsWith('#'));}+/** A recorded `models` listing: stdout, then stderr after a `# stderr` line, and the code from `# exit`. */+export function listing(agent: AgentKind, name: string): Listing {+ const streams = { stdout: [] as string[], stderr: [] as string[] };+ let into: keyof typeof streams = 'stdout';+ let code = 0;+ for (const line of readFileSync(new URL(`./${agent}/${name}`, import.meta.url), 'utf8').split('\n')) {+ const exit = /^# exit (\d+)$/.exec(line);+ if (exit) code = Number(exit[1]);+ else if (line === '# stderr') into = 'stderr';+ else if (!line.startsWith('#')) streams[into].push(line);+ }+ return { stdout: streams.stdout.join('\n'), stderr: streams.stderr.join('\n'), code };+}+/** Every sink call a fresh reader makes for these lines, in order. */export function readThrough(runner: Runner, lines: string[], only?: Signal): Call[] {const calls: Call[] = [];diff --git a/src/daemon/agent/runners/grok.ts b/src/daemon/agent/runners/grok.tsindex 0d426d5..fe92815 100644--- a/src/daemon/agent/runners/grok.ts+++ b/src/daemon/agent/runners/grok.ts@@ -6,7 +6,7 @@ import type { AgentProblem } from '@/lib/agents/catalog';import { stateDir } from '../../lockfile';import { MCP_SERVER_NAME } from './claude';import { conversationDir, effortOf, parseJsonLine, sweepRunDirs } from './util';-import type { JsonContext, McpServer, Plan, Runner, RunMode, StreamContext, StreamReader, StreamSink } from './types';+import type { JsonContext, Listing, McpServer, Plan, Runner, RunMode, StreamContext, StreamReader, StreamSink } from './types';/** Grok takes every setting a run needs as a flag except its MCP server, which only a project config can add. */const CONFIG = '.grok/config.toml';@@ -71,6 +71,8 @@ export const grokRunner: Runner = {workspace: (mode: RunMode) => join(stateDir, 'agents', 'grok', mode),+ models: { args: ['models'], parse: listedModels },+skillDirs: () => [join(grokHome(), 'skills'), join(homedir(), '.agents', 'skills'), join(homedir(), '.claude', 'skills')],stream(context: StreamContext): Plan {@@ -287,3 +289,15 @@ function lastLine<T>(stdout: string): T | null {}return null;}++/**+ * `grok models` prints ` * id (default)` and ` - id` lines under a heading. Signed out it still+ * exits 0, with a built-in list the account may not have, so that output is no list at all.+ */+function listedModels({ stdout, stderr, code }: Listing): string[] | null {+ if (code !== 0 || /not authenticated/i.test(`${stdout}\n${stderr}`)) return null;+ const lines = stdout.split('\n');+ const heading = lines.findIndex((line) => /^available models:?$/i.test(line.trim()));+ if (heading === -1) return null;+ return lines.slice(heading + 1).flatMap((line) => /^\s+[*-]\s+(\S+)/.exec(line)?.slice(1, 2) ?? []);+}diff --git a/src/daemon/agent/runners/index.test.ts b/src/daemon/agent/runners/index.test.tsindex 0c552c9..c7fd231 100644--- a/src/daemon/agent/runners/index.test.ts+++ b/src/daemon/agent/runners/index.test.ts@@ -6,7 +6,7 @@ import { AGENT_KINDS, AGENTS, type AgentKind } from '@/lib/agents/catalog';import { stateDir } from '../../lockfile';import type { AgentConfig, AgentSettings } from '../config';import { MCP_RULE, settingsPath } from './antigravity';-import { agentState, grantRunner, mcpServerFor, RUNNERS, runnerFor } from './index';+import { agentState, grantRunner, mcpServerFor, refreshModelLists, RUNNERS, runnerFor } from './index';const bin = join(stateDir, 'stub-bin');const probes = join(stateDir, 'probes.log');@@ -170,6 +170,46 @@ describe('readiness probes', () => {]);});+ test('an installed agent offers the curated models until its own list has been read', async () => {+ rmSync(join(stateDir, 'models.json'), { force: true });+ expect((await runner('codex', configWith({})))?.models).toEqual({ ids: AGENTS.codex.models, from: 'catalog', error: undefined });+ });++ test("once read, an agent offers its CLI's list, and the probe is taken again so the picker sees it", async () => {+ rmSync(join(stateDir, 'models.json'), { force: true });+ const codexHome = join(stateDir, 'codex-home');+ mkdirSync(codexHome, { recursive: true });+ writeFileSync(+ join(codexHome, 'models_cache.json'),+ JSON.stringify({ models: [{ slug: 'gpt-next', visibility: 'list', priority: 1 }, { slug: 'gpt-5.5', visibility: 'list', priority: 2 }] }),+ );+ vi.stubEnv('CODEX_HOME', codexHome);+ const config = configWith({});+ await agentState(config, { refresh: true });+ const changed = await refreshModelLists(config);+ expect([changed, (await agentState(config)).runners.find((status) => status.kind === 'codex')?.models]).toMatchObject([+ true,+ { ids: ['gpt-5.5', 'gpt-next'], from: 'cli' },+ ]);+ });++ test('a forced read that finds the same list still shows when it was read', async () => {+ rmSync(join(stateDir, 'models.json'), { force: true });+ const codexHome = join(stateDir, 'codex-home');+ mkdirSync(codexHome, { recursive: true });+ writeFileSync(join(codexHome, 'models_cache.json'), JSON.stringify({ models: [{ slug: 'gpt-5.5', visibility: 'list' }] }));+ vi.stubEnv('CODEX_HOME', codexHome);+ const config = configWith({});+ const now = vi.spyOn(Date, 'now').mockReturnValue(1_000);+ await refreshModelLists(config, { force: true });+ await agentState(config);+ now.mockReturnValue(2_000);+ const changed = await refreshModelLists(config, { force: true });+ const codex = (await agentState(config)).runners.find((status) => status.kind === 'codex');+ now.mockRestore();+ expect([changed, codex?.models?.at]).toEqual([false, 2_000]);+ });+test('an agent with nothing to set up reports no problem', async () => {expect(await grantRunner('claude')).toBeNull();});diff --git a/src/daemon/agent/runners/index.ts b/src/daemon/agent/runners/index.tsindex 1a52462..3c9d831 100644--- a/src/daemon/agent/runners/index.ts+++ b/src/daemon/agent/runners/index.ts@@ -16,6 +16,7 @@ import { claudeRunner } from './claude';import { codexRunner } from './codex';import { cursorRunner } from './cursor';import { grokRunner } from './grok';+import { modelsFor, refreshModels } from './models';import { opencodeRunner } from './opencode';import { qwenRunner } from './qwen';import type { McpServer, Runner } from './types';@@ -76,6 +77,25 @@ function forgetProbes(): void {cached = null;}+/**+ * Re-reads the model lists that are due, for every installed agent, or only the one named. One still+ * to be set up is read too, so its list is there the moment it is. Resolves to whether any list the+ * picker shows changed — the caller's cue to push the state again.+ */+export async function refreshModelLists(+ config: AgentConfig,+ { force = false, only }: { force?: boolean; only?: AgentKind } = {},+): Promise<boolean> {+ const state = await agentState(config);+ const reads = state.runners+ .filter((status) => (status.ready || status.problem?.code === 'AGENT_NEEDS_PERMISSION') && (!only || status.kind === only))+ .map((status) => refreshModels(RUNNERS[status.kind], config.agents[status.kind], status.version, { force }));+ const changed = (await Promise.all(reads)).some(Boolean);+ // A forced read restamps the list even when it came back the same, and the next state should say so.+ if (changed || force) forgetProbes();+ return changed;+}+export async function grantRunner(kind: AgentKind): Promise<AgentProblem | null> {const problem = (await RUNNERS[kind].grant?.()) ?? null;forgetProbes();@@ -122,6 +142,7 @@ async function probe(runner: Runner, settings: AgentSettings): Promise<RunnerStamodel: settings.model,ready: !problem,version: found.detail,+ models: modelsFor(runner.kind),problem: problem ?? undefined,};}diff --git a/src/daemon/agent/runners/models.test.ts b/src/daemon/agent/runners/models.test.tsnew file mode 100644index 0000000..8c053fe--- /dev/null+++ b/src/daemon/agent/runners/models.test.ts@@ -0,0 +1,229 @@+import { execFileSync } from 'node:child_process';+import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { afterEach, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest';+import { AGENTS, type AgentKind } from '@/lib/agents/catalog';+import { stateDir } from '../../lockfile';+import { listing } from './fixtures/support';+import { RUNNERS } from './index';+import { modelsFor, refreshModels } from './models';+import type { Listing, Runner } from './types';++const bin = join(stateDir, 'model-bin');+const calls = join(stateDir, 'model-calls.log');+const store = join(stateDir, 'models.json');++const parsed = (kind: AgentKind, output: Listing) => {+ const lister = RUNNERS[kind].models;+ if (!lister || 'file' in lister) throw new Error(`${kind} does not list its models with a command`);+ return lister.parse(output);+};++const codexCache = () => readFileSync(new URL('./fixtures/codex/0.155.1-models_cache.json', import.meta.url), 'utf8');++describe("each CLI's own list, as recorded", () => {+ test('Antigravity lists every model with its label, in its own order', () => {+ const ids = parsed('antigravity', listing('antigravity', '1.2.11-models.txt'));+ expect([ids?.length, ids?.[0], ids?.at(-1)]).toEqual([14, 'gemini-3.8-flash-high', 'gpt-oss-120b-medium']);+ });++ test('Cursor lists the ids under its heading, and not the tip that follows them', () => {+ const ids = parsed('cursor', listing('cursor', '2026.09.18-models.txt')) ?? [];+ expect([ids[0], ids.includes('composer-2.5'), ids.some((id) => /tip|:/i.test(id)), ids.length]).toEqual(['auto', true, false, 241]);+ });++ test('Grok lists the default and the rest alike', () => {+ expect(parsed('grok', listing('grok', '1.0.40-models.txt'))).toEqual(['grok-4.7']);+ });++ test("Codex's cache yields the models its own picker lists, by its priority, and none of its hidden helpers", () => {+ const lister = RUNNERS.codex.models;+ expect(lister && 'file' in lister ? lister.parse(codexCache()) : null).toEqual(['gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.5']);+ });++ test.each([+ ['antigravity', '1.2.11-models-signed-out.txt'],+ ['cursor', '2026.09.18-models-signed-out.txt'],+ ['grok', '1.0.40-models-signed-out.txt'],+ ] as const)('%s signed out is no list at all', (kind, name) => {+ expect(parsed(kind, listing(kind, name))).toBeNull();+ });++ test('every curated fallback names only models its CLI listed', () => {+ const listed = {+ antigravity: parsed('antigravity', listing('antigravity', '1.2.11-models.txt')),+ cursor: parsed('cursor', listing('cursor', '2026.09.18-models.txt')),+ grok: parsed('grok', listing('grok', '1.0.40-models.txt')),+ };+ const unlisted = Object.entries(listed).flatMap(([kind, ids]) =>+ AGENTS[kind as AgentKind].models.filter((id) => !ids?.includes(id)).map((id) => `${kind}: ${id}`),+ );+ expect(unlisted).toEqual([]);+ });+});++describe('reading and keeping a list', () => {+ const stub = (name: string, body: string) => {+ const path = join(bin, name);+ writeFileSync(path, `#!/bin/sh\necho "${name} $*" >> "${calls}"\n${body}\n`);+ chmodSync(path, 0o755);+ return path;+ };+ const spawned = () => (existsSync(calls) ? readFileSync(calls, 'utf8').split('\n').filter(Boolean) : []);+ const agy = RUNNERS.antigravity;+ const settings = (path: string) => ({ bin: path });+ const now = vi.spyOn(Date, 'now');++ let listed: string;+ let signedOut: string;++ beforeAll(() => {+ mkdirSync(bin, { recursive: true });+ listed = stub('agy', `printf 'gemini-3.8-flash-high\\tFlash\\ngemini-3.1-pro-high\\tPro\\nother-model\\tOther\\n'`);+ signedOut = stub('agy-signed-out', `echo 'Fetching available models...' >&2\necho 'Error: Please sign in to view available models.' >&2\nexit 1`);+ });++ beforeEach(() => {+ rmSync(store, { force: true });+ rmSync(calls, { force: true });+ now.mockReturnValue(1_000_000);+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ test('with nothing read yet, the picker offers the curated list', () => {+ expect(modelsFor('antigravity')).toEqual({ ids: AGENTS.antigravity.models, from: 'catalog', error: undefined });+ });++ test("a clean read replaces it with the CLI's list, curated picks first", async () => {+ expect(await refreshModels(agy, settings(listed), '1.2.11')).toBe(true);+ expect(modelsFor('antigravity')).toEqual({+ ids: ['gemini-3.1-pro-high', 'gemini-3.8-flash-high', 'other-model'],+ from: 'cli',+ at: 1_000_000,+ error: undefined,+ });+ });++ test('a fresh list is not read again, until six hours on or until asked', async () => {+ await refreshModels(agy, settings(listed), '1.2.11');+ const again = await refreshModels(agy, settings(listed), '1.2.11');+ now.mockReturnValue(1_000_000 + 6 * 60 * 60_000);+ await refreshModels(agy, settings(listed), '1.2.11');+ await refreshModels(agy, settings(listed), '1.2.11', { force: true });+ expect([again, spawned().length]).toEqual([false, 3]);+ });++ test('a new CLI version, or another binary, reads the list again at once', async () => {+ await refreshModels(agy, settings(listed), '1.2.11');+ await refreshModels(agy, settings(listed), '1.2.12');+ await refreshModels(agy, settings(signedOut), '1.2.12');+ expect(spawned()).toEqual(['agy models', 'agy models', 'agy-signed-out models']);+ });++ test('a failed read keeps the last good list, and says why', async () => {+ await refreshModels(agy, settings(listed), '1.2.11');+ expect(await refreshModels(agy, settings(signedOut), '1.2.11')).toBe(true);+ expect(modelsFor('antigravity')).toMatchObject({+ ids: ['gemini-3.1-pro-high', 'gemini-3.8-flash-high', 'other-model'],+ from: 'cli',+ at: 1_000_000,+ error: 'Please sign in to view available models.',+ });+ });++ test('a failure is not retried for ten minutes, and the curated list stands in meanwhile', async () => {+ await refreshModels(agy, settings(signedOut), '1.2.11');+ await refreshModels(agy, settings(signedOut), '1.2.11');+ now.mockReturnValue(1_000_000 + 10 * 60_000);+ await refreshModels(agy, settings(signedOut), '1.2.11');+ expect([spawned().length, modelsFor('antigravity').from]).toEqual([2, 'catalog']);+ });++ test('two asks at once share one read', async () => {+ const [first, second] = await Promise.all([refreshModels(agy, settings(listed), '1.2.11'), refreshModels(agy, settings(listed), '1.2.11')]);+ expect([first, second, spawned().length]).toEqual([true, true, 1]);+ });++ test('an id a CLI could read as a flag, or one with spaces, is dropped; a list of nothing else is a failure', async () => {+ const hostile = stub('agy-hostile', `printf -- '--yolo\\tYolo\\nrm -rf\\tRm\\n'`);+ const mixed = stub('agy-mixed', `printf -- '--yolo\\tYolo\\ngemini-3.1-pro-high\\tPro\\n'`);+ await refreshModels(agy, settings(hostile), '1');+ const hostileList = modelsFor('antigravity');+ await refreshModels(agy, settings(mixed), '2');+ expect([hostileList.from, modelsFor('antigravity').ids]).toEqual(['catalog', ['gemini-3.1-pro-high']]);+ });++ test('a parser that throws is a failed read, not a crash', async () => {+ const broken: Runner = { ...agy, models: { args: ['models'], parse: () => { throw new Error('bug'); } } };+ expect(await refreshModels(broken, settings(listed), '1.2.11')).toBe(true);+ expect(modelsFor('antigravity').error).toBe('It printed no model list Browsentic could read.');+ });++ test('a binary that is not there is a failed read', async () => {+ await refreshModels(agy, settings(join(bin, 'no-such-agy')), '1.2.11');+ expect(modelsFor('antigravity').error).toContain('ENOENT');+ });++ test('a CLI that floods its output is stopped at 512 KB', async () => {+ const flood = stub('agy-flood', `yes 'gemini-3.8-flash-high\tFlash' | head -c 2000000`);+ await refreshModels(agy, settings(flood), '1.2.11');+ expect(modelsFor('antigravity')).toMatchObject({ from: 'catalog', error: '"agy-flood models" printed more than 512 KB.' });+ });++ test('a CLI that hangs is killed at ten seconds, with whatever it started', async () => {+ const hung = stub('agy-hung', 'sleep 37.25 &\nwait');+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ const reading = refreshModels(agy, settings(hung), '1.2.11');+ await vi.waitUntil(() => spawned().length === 1, { interval: 10, timeout: 5_000 });+ vi.advanceTimersByTime(10_000);+ await reading;+ vi.useRealTimers();+ await vi.waitUntil(() => !running('sleep 37.25'), { interval: 20, timeout: 2_000 });+ expect(modelsFor('antigravity').error).toBe('"agy-hung models" did not answer within 10 s.');+ });++ test('a corrupt cache reads as empty, and the next read writes a sound one', async () => {+ writeFileSync(store, '{"antigravity": {"bin": ');+ const before = modelsFor('antigravity').from;+ await refreshModels(agy, settings(listed), '1.2.11');+ expect([before, JSON.parse(readFileSync(store, 'utf8')).antigravity.ids.length]).toEqual(['catalog', 3]);+ });++ test('a hand-edited cache keeps only the ids that are safe to pass on', () => {+ writeFileSync(store, JSON.stringify({ antigravity: { bin: listed, triedAt: 1, ids: ['--yolo', 'gemini-3.1-pro-high'] }, nobody: { bin: 'x', triedAt: 1 } }));+ expect(modelsFor('antigravity').ids).toEqual(['gemini-3.1-pro-high']);+ });++ test("Codex's list is read from its cache file, spawning nothing", async () => {+ const codexHome = join(stateDir, 'codex-home');+ mkdirSync(codexHome, { recursive: true });+ writeFileSync(join(codexHome, 'models_cache.json'), codexCache());+ vi.stubEnv('CODEX_HOME', codexHome);+ await refreshModels(RUNNERS.codex, { bin: join(bin, 'no-such-codex') }, 'codex-cli 0.155.1');+ vi.unstubAllEnvs();+ expect(modelsFor('codex')).toMatchObject({ ids: ['gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.5'], from: 'cli' });+ });++ test('a Codex that has never run has no cache yet, and says so', async () => {+ vi.stubEnv('CODEX_HOME', join(stateDir, 'no-codex-home'));+ await refreshModels(RUNNERS.codex, { bin: 'codex' }, 'codex-cli 0.155.1');+ vi.unstubAllEnvs();+ expect(modelsFor('codex')).toMatchObject({ from: 'catalog', error: 'Codex has not written models_cache.json yet. It does the first time it runs.' });+ });++ test('an agent with no lister reads nothing', async () => {+ expect([await refreshModels(RUNNERS.claude, { bin: 'claude' }, '1'), modelsFor('claude').ids]).toEqual([false, AGENTS.claude.models]);+ });+});++function running(pattern: string): boolean {+ try {+ execFileSync('pgrep', ['-f', pattern]);+ return true;+ } catch {+ return false;+ }+}diff --git a/src/daemon/agent/runners/models.ts b/src/daemon/agent/runners/models.tsnew file mode 100644index 0000000..6d3cf15--- /dev/null+++ b/src/daemon/agent/runners/models.ts@@ -0,0 +1,222 @@+import { spawn } from 'node:child_process';+import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';+import { basename, join } from 'node:path';+import { AGENTS, isModelId, type AgentKind, type ModelList } from '@/lib/agents/catalog';+import { stateDir } from '../../lockfile';+import { log } from '../../log';+import type { AgentSettings } from '../config';+import { childEnv } from './drive';+import type { Listing, ModelLister, Runner } from './types';++const FRESH_MS = 6 * 60 * 60_000;+const RETRY_MS = 10 * 60_000;+const LIST_TIMEOUT_MS = 10_000;+const MAX_OUTPUT_BYTES = 512 * 1024;+const MAX_MODELS = 500;++const storePath = join(stateDir, 'models.json');++interface Entry {+ bin: string;+ version?: string;+ /** The last list that read cleanly. A failed read never replaces it. */+ ids?: string[];+ at?: number;+ triedAt: number;+ error?: string;+}++type Store = Partial<Record<AgentKind, Entry>>;++type Outcome = { ids: string[] } | { error: string };++const inFlight = new Map<AgentKind, Promise<boolean>>();++/** What the picker offers for this agent right now. Reads the cache and nothing else, so it never waits. */+export function modelsFor(kind: AgentKind): ModelList {+ const entry = readStore()[kind];+ const curated = AGENTS[kind].models;+ if (entry?.ids?.length) return { ids: suggestedFirst(entry.ids, curated), from: 'cli', at: entry.at, error: entry.error };+ return { ids: curated, from: 'catalog', error: entry?.error };+}++/**+ * Reads the agent's own list when it is due, one read per agent at a time. Resolves to whether+ * what the picker shows changed, and never rejects.+ */+export function refreshModels(+ runner: Runner,+ settings: AgentSettings,+ version: string | undefined,+ { force = false } = {},+): Promise<boolean> {+ const lister = runner.models;+ if (!lister) return Promise.resolve(false);+ const running = inFlight.get(runner.kind);+ if (running) return running;+ if (!force && !due(readStore()[runner.kind], settings.bin, version, lister)) return Promise.resolve(false);++ const reading = read(runner.kind, settings.bin, lister)+ .catch((error: unknown): Outcome => ({ error: String(error) }))+ .then((outcome) => record(runner.kind, settings.bin, version, outcome))+ .catch((error: unknown) => {+ log(`could not keep ${AGENTS[runner.kind].label}'s model list: ${String(error)}`);+ return false;+ })+ .finally(() => inFlight.delete(runner.kind));+ inFlight.set(runner.kind, reading);+ return reading;+}++function due(entry: Entry | undefined, bin: string, version: string | undefined, lister: ModelLister): boolean {+ if (!entry || entry.bin !== bin || entry.version !== version) return true;+ const age = Date.now() - entry.triedAt;+ if (entry.error) return age >= RETRY_MS;+ return 'file' in lister || age >= FRESH_MS;+}++async function read(kind: AgentKind, bin: string, lister: ModelLister): Promise<Outcome> {+ if ('file' in lister) {+ const path = lister.file();+ let content: string;+ try {+ content = readFileSync(path, 'utf8');+ } catch {+ return { error: `${AGENTS[kind].label} has not written ${basename(path)} yet. It does the first time it runs.` };+ }+ return accepted(() => lister.parse(content)) ?? { error: `${basename(path)} holds no model Browsentic could read.` };+ }++ const listing = await list(kind, bin, lister.args);+ if ('error' in listing) return listing;+ return accepted(() => lister.parse(listing)) ?? { error: reason(listing) };+}++/** A parser's answer, kept only if it is a usable list: ids a CLI cannot mistake for a flag, no repeats. */+function accepted(parse: () => string[] | null): { ids: string[] } | null {+ let parsed: string[] | null;+ try {+ parsed = parse();+ } catch {+ return null;+ }+ const ids = [...new Set((parsed ?? []).filter(isModelId))].slice(0, MAX_MODELS);+ return ids.length ? { ids } : null;+}++/** The line a person would read as the reason, e.g. "Please sign in to view available models." */+function reason({ stdout, stderr, code }: Listing): string {+ const lines = plain(`${stderr}\n${stdout}`)+ .split('\n')+ .map((line) => line.trim())+ .filter(Boolean);+ const said = lines.find((line) => /error|sign in|log ?in|authenticat/i.test(line));+ if (said) return said.replace(/^error:\s*/i, '').slice(0, 200);+ return code === 0 ? 'It printed no model list Browsentic could read.' : `It exited with code ${code}.`;+}++function list(kind: AgentKind, bin: string, args: string[]): Promise<Listing | { error: string }> {+ const cwd = join(stateDir, 'agents', kind, 'models');+ mkdirSync(cwd, { recursive: true, mode: 0o700 });+ const command = `"${[basename(bin), ...args].join(' ')}"`;+ const group = process.platform !== 'win32';++ return new Promise((resolve) => {+ let stdout = '';+ let stderr = '';+ let size = 0;+ let settled = false;+ const done = (result: Listing | { error: string }) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ resolve(result);+ };++ const child = spawn(bin, args, {+ cwd,+ env: { ...childEnv(kind), NO_COLOR: '1' },+ stdio: ['ignore', 'pipe', 'pipe'],+ detached: group,+ });+ // The whole group, so a wrapper script's own children go with it.+ const stop = (error: string) => {+ try {+ if (group && child.pid) process.kill(-child.pid, 'SIGKILL');+ else child.kill('SIGKILL');+ } catch {+ child.kill('SIGKILL');+ }+ done({ error });+ };+ const timer = setTimeout(() => stop(`${command} did not answer within ${LIST_TIMEOUT_MS / 1000} s.`), LIST_TIMEOUT_MS);+ timer.unref();++ const collect = (append: (text: string) => void) => (chunk: Buffer) => {+ size += chunk.length;+ if (size > MAX_OUTPUT_BYTES) return stop(`${command} printed more than ${MAX_OUTPUT_BYTES / 1024} KB.`);+ append(chunk.toString());+ };+ child.stdout.on('data', collect((text) => (stdout += text)));+ child.stderr.on('data', collect((text) => (stderr += text)));+ child.on('error', (error) => done({ error: error.message }));+ child.on('close', (code) => done({ stdout, stderr, code }));+ });+}++function record(kind: AgentKind, bin: string, version: string | undefined, outcome: Outcome): boolean {+ const store = readStore();+ const before = store[kind];+ const now = Date.now();+ const entry: Entry =+ 'ids' in outcome+ ? { bin, version, ids: outcome.ids, at: now, triedAt: now }+ : { bin, version, ids: before?.ids, at: before?.at, triedAt: now, error: outcome.error };+ if ('error' in outcome) log(`could not list ${AGENTS[kind].label}'s models: ${outcome.error}`);+ store[kind] = entry;+ writeStore(store);+ return JSON.stringify([before?.ids, before?.error]) !== JSON.stringify([entry.ids, entry.error]);+}++function readStore(): Store {+ let parsed: unknown;+ try {+ parsed = JSON.parse(readFileSync(storePath, 'utf8'));+ } catch {+ return {};+ }+ if (!parsed || typeof parsed !== 'object') return {};+ const store: Store = {};+ for (const [kind, value] of Object.entries(parsed as Record<string, unknown>)) {+ const entry = entryOf(value);+ if (entry && kind in AGENTS) store[kind as AgentKind] = entry;+ }+ return store;+}++function entryOf(value: unknown): Entry | null {+ if (!value || typeof value !== 'object') return null;+ const raw = value as Record<string, unknown>;+ if (typeof raw.bin !== 'string' || typeof raw.triedAt !== 'number') return null;+ const ids = Array.isArray(raw.ids) ? raw.ids.filter(isModelId) : undefined;+ return {+ bin: raw.bin,+ version: typeof raw.version === 'string' ? raw.version : undefined,+ ids: ids?.length ? ids : undefined,+ at: typeof raw.at === 'number' ? raw.at : undefined,+ triedAt: raw.triedAt,+ error: typeof raw.error === 'string' ? raw.error.slice(0, 200) : undefined,+ };+}++function writeStore(store: Store): void {+ const temporary = `${storePath}.${process.pid}.tmp`;+ writeFileSync(temporary, `${JSON.stringify(store, null, 2)}\n`, { mode: 0o600 });+ renameSync(temporary, storePath);+}++function suggestedFirst(ids: string[], curated: string[]): string[] {+ return [...curated.filter((id) => ids.includes(id)), ...ids.filter((id) => !curated.includes(id))];+}++const plain = (text: string) => text.replace(/\u001B\[[0-9;]*[A-Za-z]/g, '');diff --git a/src/daemon/agent/runners/types.ts b/src/daemon/agent/runners/types.tsindex 0072e31..6e3d1d7 100644--- a/src/daemon/agent/runners/types.ts+++ b/src/daemon/agent/runners/types.ts@@ -62,6 +62,20 @@ export interface StreamSink {export type StreamReader = (line: string, sink: StreamSink) => void;+export interface Listing {+ stdout: string;+ stderr: string;+ code: number | null;+}++/**+ * Where a CLI lists the models its account can use: a subcommand it prints them from, or a file+ * it keeps them in. `parse` answers null for anything but a clean list — signed out included.+ */+export type ModelLister =+ | { args: string[]; parse(listing: Listing): string[] | null }+ | { file(): string; parse(content: string): string[] | null };+export interface Runner {kind: AgentKind;/** Arguments that make the binary print its version, used to prove it is installed. */@@ -71,6 +85,8 @@ export interface Runner {workspace(mode: RunMode): string;/** Directories where this CLI keeps the user's own skills, feeding the panel's skill picker. */skillDirs?(): string[];+ /** Absent: the picker offers the catalog's curated models. */+ models?: ModelLister;stream(context: StreamContext): Plan;/** Fresh per run — readers carry state across lines. */reader(): StreamReader;diff --git a/src/daemon/cli.ts b/src/daemon/cli.tsindex cef1c24..26aa85c 100644--- a/src/daemon/cli.ts+++ b/src/daemon/cli.ts@@ -2,9 +2,10 @@ import { readFileSync } from 'node:fs';import { createInterface } from 'node:readline/promises';import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';import { describeActions } from '@/lib/actions/registry';-import { AGENTS, AGENT_KINDS, AGENT_LIST, isAgentKind } from '@/lib/agents/catalog';+import { AGENTS, AGENT_KINDS, AGENT_LIST, isAgentKind, type AgentKind, type ModelList } from '@/lib/agents/catalog';import { RESERVED_ACTIONS } from '@/lib/actions/reserved';import { assertToolNamesRoundTrip, toolNameFor } from '@/lib/actions/tool-names';+import { formatWhen } from '@/lib/format-when';import { basename, join } from 'node:path';import { agentSkills } from './agent/agent-skills';import { forgetGrants, listGrants } from './agent/approvals';@@ -39,6 +40,7 @@ const USAGE = `browsentic ${pkg.version} — hand your real browser to the agentbrowsentic agent <name> switch to claude, codex, antigravity, vibe, grok, cursor, qwen or opencodebrowsentic agent fix <name> let Browsentic fix what that agent still needsbrowsentic agent model <name> [model] pin that agent's model, or omit it for the CLI's default+ browsentic agent models <name> list the models that agent offers; --refresh asks its CLI againbrowsentic skills list the skills the agent can route to, and where they came frombrowsentic approvals list the “always on this site” approvals you have granted@@ -593,9 +595,13 @@ async function chooseAgent(first?: string, second?: string, third?: string): Proconsole.error(`Name the agent whose model to set. Pick one of: ${AGENT_KINDS.join(', ')}`);process.exit(1);}- writeAgentModel(second, third ?? null);+ if (!writeAgentModel(second, third ?? null)) {+ console.error(`"${third}" is not a model id: it has to start with a letter or digit and hold no spaces.`);+ process.exit(1);+ }first = second = undefined;}+ if (first === 'models') return listModels(second);// Renamed to "fix" because `browsentic setup` now means something else entirely. The old// spelling stays as an undocumented alias for one release.@@ -621,6 +627,7 @@ async function chooseAgent(first?: string, second?: string, third?: string): Proconst mark = runner.kind === state.active ? '●' : '○';const version = runner.version ? ` — ${runner.version}` : '';console.log(`${mark} ${agent.label.padEnd(12)} ${runner.ready ? 'ready' : 'unavailable'}${version}`);+ if (runner.ready && runner.models) console.log(` models: ${modelSource(runner.kind, runner.models)}`);if (runner.problem) {console.log(` ${runner.problem.message}`);if (runner.problem.fix) console.log(` ${runner.problem.fix}`);@@ -630,6 +637,34 @@ async function chooseAgent(first?: string, second?: string, third?: string): Proconsole.log(`\nThe side panel runs on ${AGENTS[state.active].label}.`);}+async function listModels(named?: string): Promise<void> {+ if (!isAgentKind(named)) {+ console.error(`Name the agent whose models to list. Pick one of: ${AGENT_KINDS.join(', ')}`);+ process.exit(1);+ }+ const bridge = await connect();+ const state = await bridge.agent(process.argv.includes('--refresh') ? { models: named } : undefined);+ await bridge.close();++ const runner = state.runners.find((status) => status.kind === named);+ const models: ModelList = runner?.models ?? { ids: AGENTS[named].models, from: 'catalog' };+ if (wantsJson) {+ console.log(JSON.stringify({ agent: named, model: runner?.model ?? null, ...models }, null, 2));+ return;+ }+ for (const id of models.ids) console.log(`${id === runner?.model ? '●' : ' '} ${id}`);+ if (runner?.model && !models.ids.includes(runner.model)) console.log(`● ${runner.model} (pinned, not listed)`);+ console.log(`\n${modelSource(named, models)}`);+}++function modelSource(kind: AgentKind, models: ModelList): string {+ const source =+ models.from === 'cli' && models.at !== undefined+ ? `${models.ids.length} listed by ${AGENTS[kind].bin}, ${formatWhen(models.at)}`+ : `Browsentic's built-in list of ${models.ids.length}`;+ return models.error ? `${source}. The last read failed: ${models.error}` : `${source}.`;+}+async function revoke(browser?: string): Promise<void> {const bridge = await connect();const revoked = await bridge.revoke(browser);diff --git a/src/daemon/control.ts b/src/daemon/control.tsindex 76ec426..d29c032 100644--- a/src/daemon/control.ts+++ b/src/daemon/control.ts@@ -33,7 +33,7 @@ export type ControlRequest =| { id: string; op: 'pair' }| { id: string; op: 'sessions' }| { id: string; op: 'revoke'; session?: string; origin?: string }- | { id: string; op: 'agent'; set?: AgentKind; grant?: AgentKind };+ | { id: string; op: 'agent'; set?: AgentKind; grant?: AgentKind; models?: AgentKind };export type ControlMessage =| { id: string; op: 'describe'; tools: ToolDescriptor[]; reserved?: string[] }diff --git a/src/daemon/daemon.ts b/src/daemon/daemon.tsindex 8da00c3..2bdbbd5 100644--- a/src/daemon/daemon.ts+++ b/src/daemon/daemon.ts@@ -54,7 +54,7 @@ import { analyzeRecording } from './agent/recording';import { nameSession } from './agent/title';import { configPath, readAgentConfig, writeActiveAgent, writeAgentModel, writeGuardrailSetting } from './agent/config';import { agentSkills } from './agent/agent-skills';-import { agentState, grantRunner } from './agent/runners';+import { agentState, grantRunner, refreshModelLists } from './agent/runners';import { deleteSiteMap, deleteSkill, saveSkill } from './agent/skill-store';import { loadSkills } from './agent/skills';import { commitStaging, discardStaging } from './agent/site-map-store';@@ -457,6 +457,7 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):accepted.send({ t: 'welcome', ...welcome, proof: await serverProof(secret, transcript, welcome) });scheduleIdleExit();void pushAgentState(accepted);+ watchModels();pushSkillCatalog(accepted);if (!known) await adoptExtensionManifest(accepted);}@@ -506,12 +507,28 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):if (request.t === 'setAgentModel') {// A model change keeps held conversations — every CLI resumes a session under a new model.const model = typeof request.model === 'string' ? request.model : null;- writeAgentModel(request.agent, model);+ if (!writeAgentModel(request.agent, model)) {+ return failure('INVALID_INPUT', `"${String(model)}" is not a model id: it has to start with a letter or digit and hold no spaces.`);+ }log(`${AGENTS[request.agent].label} model set to ${model?.trim() || 'the default'}`);}if (request.t === 'grantAgent') await grantRunner(request.agent);- const refresh = request.t !== 'agentState' || request.refresh === true;- return success(await agentState(readAgentConfig(), { refresh }));+ const recheck = request.t === 'agentState' && request.refresh === true;+ const state = await agentState(readAgentConfig(), { refresh: request.t !== 'agentState' || recheck });+ watchModels({ force: recheck });+ return success(state);+ }++ /**+ * Reads each agent's own model list after the state has gone out, and sends the state again+ * when one changed. A forced read sends it regardless, so the list's age is current.+ */+ function watchModels({ force = false } = {}): void {+ void refreshModelLists(readAgentConfig(), { force })+ .then((changed) => {+ if (changed || force) for (const link of openLinks()) void pushAgentState(link);+ })+ .catch((error: unknown) => log(`could not refresh the model lists: ${String(error)}`));}function settleGuardrail(request: GuardrailFrame): ActionResult<GuardrailSettings> {@@ -687,8 +704,11 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):log(`control ${client} set the agent to ${AGENTS[request.set].label}`);}if (request.grant) await grantRunner(request.grant);- const state = await agentState(readAgentConfig(), { refresh: !!changed });- if (changed) announceAgent();+ const listed = isAgentKind(request.models);+ if (listed) await refreshModelLists(readAgentConfig(), { force: true, only: request.models });+ const state = await agentState(readAgentConfig(), { refresh: !!changed || listed });+ if (changed || listed) announceAgent();+ else watchModels();return send(ws, { id: request.id, op: 'agent', state });}if (request.op === 'revoke') {diff --git a/src/daemon/guardrails/spawn.test.ts b/src/daemon/guardrails/spawn.test.tsindex ff85b5e..a6fb721 100644--- a/src/daemon/guardrails/spawn.test.ts+++ b/src/daemon/guardrails/spawn.test.ts@@ -446,6 +446,20 @@ describe('spawn containment', () => {});});+ describe('a model a CLI could read as a flag', () => {+ for (const kind of AGENT_KINDS) {+ test(`is refused for ${kind}`, () => {+ const problems = vetPlan(kind, 'run', plus(planOf(kind, 'run'), '--model', '-p'), stateDir);+ expect(problems.some((problem) => problem.includes('could read as a flag'))).toBe(true);+ });+ }++ test("is not Cursor's bracketed override", () => {+ const plan = plus(planOf('cursor', 'run'), '--model', 'claude-opus-4-8[context=1m,effort=high]');+ expect(vetPlan('cursor', 'run', plan, stateDir)).toEqual([]);+ });+ });+describe('every agent the catalog knows about declares containment', () => {for (const kind of AGENT_KINDS) {test(`${kind} declares containment`, () => {diff --git a/src/daemon/guardrails/spawn.ts b/src/daemon/guardrails/spawn.tsindex 6aac5a5..c003b25 100644--- a/src/daemon/guardrails/spawn.ts+++ b/src/daemon/guardrails/spawn.ts@@ -26,7 +26,7 @@* assumed away.*/-import { AGENTS, type AgentKind } from '@/lib/agents/catalog';+import { AGENTS, isModelId, type AgentKind } from '@/lib/agents/catalog';/** `run` drives the browser; `task` is a one-shot that must not reach it at all. */export type SpawnMode = 'run' | 'task';@@ -432,6 +432,10 @@ export function vetPlan(kind: AgentKind, mode: SpawnMode, plan: SpawnPlan, home:}}+ for (const model of everyValueOf(plan.args, '--model')) {+ if (!isModelId(model)) problems.push(`${label} is spawned with the model ${JSON.stringify(model)}, which it could read as a flag.`);+ }+if (!within(plan.cwd, home)) problems.push(`${label} would run in ${plan.cwd}, which is outside ${home}.`);return problems;diff --git a/src/daemon/remote-bridge.ts b/src/daemon/remote-bridge.tsindex 78fd71f..5ce0ff2 100644--- a/src/daemon/remote-bridge.ts+++ b/src/daemon/remote-bridge.ts@@ -63,7 +63,7 @@ export class RemoteBridge implements Bridge {return reply && 'sessions' in reply ? reply.sessions : [];}- async agent(change?: { set?: AgentKind; grant?: AgentKind }): Promise<AgentState> {+ async agent(change?: { set?: AgentKind; grant?: AgentKind; models?: AgentKind }): Promise<AgentState> {const reply = await this.request({ id: randomUUID(), op: 'agent', ...change });if (reply && 'state' in reply) return reply.state;throw new Error('The Browsentic daemon did not answer about its agent');diff --git a/src/extension/components/agent-picker.tsx b/src/extension/components/agent-picker.tsxindex a22ea0e..f9b3878 100644--- a/src/extension/components/agent-picker.tsx+++ b/src/extension/components/agent-picker.tsx@@ -3,6 +3,7 @@ import { Check, Loader2, RefreshCw, ShieldCheck, TriangleAlert } from 'lucide-reimport { browser } from 'wxt/browser';import { AgentMark } from '@/extension/components/agent-marks';+import { ModelFilter } from '@/extension/components/model-filter';import { StatusDot } from '@/extension/components/status-pill';import { Button } from '@/extension/components/ui/button';import {@@ -13,8 +14,16 @@ import {SelectValue,} from '@/extension/components/ui/select';import { BRIDGE_CHANNEL, type ActionResult } from '@/lib/actions/protocol';-import { AGENTS, AGENT_LIST, type AgentKind, type AgentState, type RunnerStatus } from '@/lib/agents/catalog';+import {+ AGENTS,+ AGENT_LIST,+ type AgentKind,+ type AgentState,+ type ModelList,+ type RunnerStatus,+} from '@/lib/agents/catalog';import { useDaemonState } from '@/lib/bridge/use-daemon-state';+import { formatWhen } from '@/lib/format-when';import { cn } from '@/lib/utils';type Request =@@ -28,6 +37,9 @@ const busyKey = (request: Request): string =>const CLI_DEFAULT = '__default__';+/** Past this many models, a dropdown is a scroll hunt, so the picker offers a filter instead. */+const LONG_LIST = 20;+export function AgentPicker() {const daemon = useDaemonState();const state = daemon?.agent;@@ -133,8 +145,8 @@ function AgentRow({onModel: (model: string | null) => void;}) {const agent = AGENTS[runner.kind];- const models =- runner.model && !agent.models.includes(runner.model) ? [runner.model, ...agent.models] : agent.models;+ const list = offered(runner);+ const pinned = runner.model && !list.ids.includes(runner.model) ? runner.model : null;return (<divclassName={cn(@@ -167,32 +179,49 @@ function AgentRow({<span className="font-mono text-[10px] tracking-wider uppercase opacity-70">{describe(runner)}</span>{busy ? <Loader2 className="size-3 animate-spin" /> : active && <Check className="size-3" />}</button>- {runner.ready && models.length > 0 && (+ {runner.ready && (<divclassName={cn(- 'flex items-center gap-2 border-t px-2.5 py-1.5',+ 'flex flex-wrap items-center gap-x-2 gap-y-1 border-t px-2.5 py-1.5',active ? 'border-brand/25' : 'border-line',)}><span className="font-mono text-[10px] tracking-[0.14em] text-ink-faint uppercase">Model</span>- <Select- value={runner.model ?? CLI_DEFAULT}- onValueChange={(value) => onModel(value === CLI_DEFAULT ? null : value)}- disabled={disabled}- >- <SelectTrigger className="h-6 min-w-0 flex-1 py-0 font-mono text-[10px]">- <SelectValue />- </SelectTrigger>- <SelectContent align="end" className="font-mono text-[10px]">- <SelectItem value={CLI_DEFAULT}>Default</SelectItem>- {models.map((model) => (- <SelectItem key={model} value={model}>- {model}- </SelectItem>- ))}- </SelectContent>- </Select>+ {list.ids.length > LONG_LIST ? (+ <ModelFilter+ value={runner.model ?? null}+ ids={list.ids}+ suggested={agent.models.filter((id) => list.ids.includes(id))}+ pinned={pinned}+ disabled={disabled}+ onModel={onModel}+ />+ ) : (+ <Select+ value={runner.model ?? CLI_DEFAULT}+ onValueChange={(value) => onModel(value === CLI_DEFAULT ? null : value)}+ disabled={disabled}+ >+ <SelectTrigger className="h-6 min-w-0 flex-1 py-0 font-mono text-[10px]">+ <SelectValue />+ </SelectTrigger>+ <SelectContent align="end" className="font-mono text-[10px]">+ <SelectItem value={CLI_DEFAULT}>Default</SelectItem>+ {pinned && <SelectItem value={pinned}>{pinned} · not listed</SelectItem>}+ {list.ids.map((model) => (+ <SelectItem key={model} value={model}>+ {model}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}{modelBusy && <Loader2 className="size-3 animate-spin text-ink-faint" />}+ {active && (+ <p className="basis-full truncate font-mono text-[9px] text-ink-faint" title={list.error}>+ {describeList(runner.kind, list)}+ </p>+ )}</div>)}</div>@@ -214,3 +243,14 @@ function describe(runner: RunnerStatus): string {}const unknownRunner = (kind: AgentKind): RunnerStatus => ({ kind, bin: AGENTS[kind].bin, ready: false });++/** The daemon's list when it sent a usable one, the catalog's otherwise. */+function offered({ kind, models }: RunnerStatus): ModelList {+ return models && Array.isArray(models.ids) && models.ids.length ? models : { ids: AGENTS[kind].models, from: 'catalog' };+}++function describeList(kind: AgentKind, { ids, from, at, error }: ModelList): string {+ const source = from === 'cli' && at !== undefined ? `${ids.length} listed by ${AGENTS[kind].bin} · ${formatWhen(at)}` : 'built-in list';+ if (!error) return source;+ return from === 'cli' ? `${source} · last read failed` : `${source} · ${error}`;+}diff --git a/src/extension/components/model-filter.tsx b/src/extension/components/model-filter.tsxnew file mode 100644index 0000000..ea970dd--- /dev/null+++ b/src/extension/components/model-filter.tsx@@ -0,0 +1,127 @@+import { useState, type ReactNode } from 'react';+import { Check, ChevronDown } from 'lucide-react';++import { Input } from '@/extension/components/ui/input';+import { cn } from '@/lib/utils';++/**+ * The model picker for a CLI that lists more models than a dropdown can show: the curated ones it+ * really has first, then everything else behind a filter. It unfolds in place, below its row.+ */+export function ModelFilter({+ value,+ ids,+ suggested,+ pinned,+ disabled,+ onModel,+}: {+ value: string | null;+ ids: string[];+ suggested: string[];+ pinned: string | null;+ disabled: boolean;+ onModel: (model: string | null) => void;+}) {+ const [open, setOpen] = useState(false);+ const [query, setQuery] = useState('');++ const needle = query.trim().toLowerCase();+ const matches = (id: string) => id.toLowerCase().includes(needle);+ const top = suggested.filter(matches);+ const rest = ids.filter((id) => !suggested.includes(id) && matches(id));++ const pick = (model: string | null) => {+ setOpen(false);+ setQuery('');+ if (model !== value) onModel(model);+ };++ return (+ <>+ <button+ type="button"+ onClick={() => setOpen(!open)}+ disabled={disabled}+ aria-expanded={open}+ className={cn(+ 'flex h-6 min-w-0 flex-1 items-center justify-between gap-1.5 rounded-md border border-line bg-surface/60 px-2 font-mono text-[10px] text-ink-dim transition-colors',+ 'enabled:hover:border-line-strong enabled:hover:text-ink focus-visible:ring-2 focus-visible:ring-brand/50 focus-visible:outline-none',+ 'disabled:cursor-not-allowed disabled:opacity-50',+ )}+ >+ <span className="min-w-0 truncate">{value ?? 'Default'}</span>+ <ChevronDown className={cn('size-3 shrink-0 opacity-60 transition-transform', open && 'rotate-180')} />+ </button>++ {open && (+ <div className="basis-full space-y-1 rounded-lg border border-line-strong bg-surface p-1">+ <Input+ autoFocus+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === 'Escape') setOpen(false);+ if (event.key === 'Enter' && (top[0] ?? rest[0])) pick(top[0] ?? rest[0]);+ }}+ placeholder={`Filter ${ids.length} models`}+ aria-label="Filter models"+ className="h-6 px-2 font-mono text-[10px]"+ />+ <div className="max-h-48 overflow-y-auto overscroll-contain font-mono text-[10px]">+ {!needle && <Option selected={value === null} onPick={() => pick(null)}>Default</Option>}+ {pinned && matches(pinned) && (+ <Option selected={value === pinned} onPick={() => pick(pinned)}>+ {pinned} <span className="text-ink-faint">· not listed</span>+ </Option>+ )}+ <Group title="Suggested" ids={top} value={value} onPick={pick} />+ <Group title={top.length ? 'All models' : null} ids={rest} value={value} onPick={pick} />+ {!top.length && !rest.length && <p className="px-2 py-1 text-ink-faint">No model matches “{query.trim()}”.</p>}+ </div>+ </div>+ )}+ </>+ );+}++function Group({+ title,+ ids,+ value,+ onPick,+}: {+ title: string | null;+ ids: string[];+ value: string | null;+ onPick: (model: string) => void;+}) {+ if (!ids.length) return null;+ return (+ <div role="group" aria-label={title ?? undefined}>+ {title && <p className="px-2 pt-1.5 pb-0.5 text-[9px] tracking-[0.14em] text-ink-faint uppercase">{title}</p>}+ {ids.map((id) => (+ <Option key={id} selected={id === value} onPick={() => onPick(id)}>+ {id}+ </Option>+ ))}+ </div>+ );+}++function Option({ selected, onPick, children }: { selected: boolean; onPick: () => void; children: ReactNode }) {+ return (+ <button+ type="button"+ onClick={onPick}+ className={cn(+ 'relative flex w-full items-center rounded-md py-1 pr-6 pl-2 text-left text-ink-dim transition-colors',+ 'hover:bg-brand/15 hover:text-brand focus-visible:bg-brand/15 focus-visible:text-brand focus-visible:outline-none',+ selected && 'text-brand',+ )}+ >+ <span className="min-w-0 truncate">{children}</span>+ {selected && <Check className="absolute right-1.5 size-3" />}+ </button>+ );+}diff --git a/src/lib/actions/protocol.ts b/src/lib/actions/protocol.tsindex b830ded..02cc067 100644--- a/src/lib/actions/protocol.ts+++ b/src/lib/actions/protocol.ts@@ -11,7 +11,7 @@ import type { SiteMapDraft } from '@/lib/skills/site-map';export const ACTION_CHANNEL = 'browsentic/action';export const BRIDGE_CHANNEL = 'browsentic/bridge';-export const SOCKET_PROTOCOL_VERSION = 18;+export const SOCKET_PROTOCOL_VERSION = 19;export const EXTERNAL_RUN_ID = 'external';diff --git a/src/lib/agents/catalog.test.ts b/src/lib/agents/catalog.test.tsnew file mode 100644index 0000000..1b5088d--- /dev/null+++ b/src/lib/agents/catalog.test.ts@@ -0,0 +1,34 @@+import { describe, expect, test } from 'vitest';+import { AGENT_LIST, isModelId } from './catalog';++describe('isModelId', () => {+ test.each([+ 'sonnet',+ 'claude-sonnet-5',+ 'gpt-5.6-terra',+ 'anthropic/claude-opus-5-5',+ 'claude-opus-4-8[context=1m,effort=high,fast=false]',+ 'ollama/llama3:8b',+ ])('takes %s', (id) => {+ expect(isModelId(id)).toBe(true);+ });++ test.each([+ ['a flag', '--dangerously-skip-permissions'],+ ['a short flag', '-p'],+ ['a space', 'gpt 5'],+ ['a newline', 'gpt-5\nactive_model = "x"'],+ ['an escape code', 'gpt-5\u001b[31m'],+ ['a bidi override', 'gpt-5'],+ ['nothing', ''],+ ['a leading dot', '.hidden'],+ ['something too long', `m${'x'.repeat(200)}`],+ ['a number', 5],+ ])('refuses %s', (_, value) => {+ expect(isModelId(value)).toBe(false);+ });++ test('every curated model passes', () => {+ expect(AGENT_LIST.flatMap((agent) => agent.models).filter((id) => !isModelId(id))).toEqual([]);+ });+});diff --git a/src/lib/agents/catalog.ts b/src/lib/agents/catalog.tsindex d66fb8e..be6a0dc 100644--- a/src/lib/agents/catalog.ts+++ b/src/lib/agents/catalog.ts@@ -11,7 +11,7 @@ export interface AgentDescriptor {bin: string;install: string;docs: string;- /** Model ids the picker offers, strongest first. Curated, not queried — the CLIs have no list command. */+ /** Model ids the picker offers, strongest first, whenever the CLI cannot list its own. */models: string[];/** Shipped before a whole conversation was run against the real CLI; the picker and the docs say so. */beta?: boolean;@@ -25,7 +25,8 @@ export const AGENTS: Record<AgentKind, AgentDescriptor> = {bin: 'claude',install: 'npm i -g @anthropic-ai/claude-code',docs: 'https://claude.com/claude-code',- models: ['claude-fable-5', 'claude-opus-5', 'claude-sonnet-5', 'claude-haiku-4-5'],+ // Claude Code resolves each alias to the newest model of that family, so this list does not age.+ models: ['fable', 'opus', 'sonnet', 'haiku'],},codex: {kind: 'codex',@@ -43,7 +44,7 @@ export const AGENTS: Record<AgentKind, AgentDescriptor> = {bin: 'agy',install: 'https://antigravity.google/docs/cli/install',docs: 'https://antigravity.google/docs/cli',- models: ['gemini-3-pro', 'gemini-3-flash'],+ models: ['gemini-3.1-pro-high', 'gemini-3.8-flash-high', 'gemini-3.8-flash-medium'],},vibe: {kind: 'vibe',@@ -72,8 +73,7 @@ export const AGENTS: Record<AgentKind, AgentDescriptor> = {bin: 'cursor-agent',install: 'curl https://cursor.com/install -fsS | bash',docs: 'https://cursor.com/docs/cli/overview',- // `cursor-agent models` lists the account's own set, but it needs a login, so these are curated.- models: ['composer-2.5', 'claude-opus-4-8', 'gpt-5', 'sonnet-4-thinking'],+ models: ['auto', 'composer-2.5', 'claude-opus-5-thinking-high', 'gpt-5.3-codex'],beta: true,},qwen: {@@ -117,6 +117,24 @@ export interface AgentProblem {grantable?: boolean;}+/**+ * Anything a CLI will take as a model, and nothing it could read as a flag: no leading dash, no+ * whitespace, no control or format characters. Cursor's `claude-opus-4-8[effort=high]` passes.+ */+export function isModelId(value: unknown): value is string {+ return typeof value === 'string' && /^[A-Za-z0-9][^\s\p{C}]{0,199}$/u.test(value);+}++export interface ModelList {+ ids: string[];+ /** `cli` when the agent's own CLI listed them, `catalog` when it could not and these are curated. */+ from: 'cli' | 'catalog';+ /** When the CLI's list was read. */+ at?: number;+ /** Why the last attempt to read it failed. */+ error?: string;+}+export interface RunnerStatus {kind: AgentKind;bin: string;@@ -124,6 +142,7 @@ export interface RunnerStatus {version?: string;/** The model this runner will be spawned with; unset means the CLI's own default. */model?: string;+ models?: ModelList;problem?: AgentProblem;}