Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Read Claude Code's cached model catalog when refreshing models (#8042)

[._.]/c4048bdae0a3
diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.js
index 589a5f3927..1bcb61091e 100644
--- a/client/src/utils/providers.test.js
+++ b/client/src/utils/providers.test.js
@@ -1356,7 +1356,10 @@ describe('supportsModelRefresh', () => {
// have a usable fetcher or stay out of this list.
expect(withButton).toEqual([
'antigravity-cli', 'antigravity-tui', 'cerebras', 'claude-code',
- 'claude-code-bedrock', 'claude-ollama', 'claude-ollama-tui',
+ // #8034: claude-code-bedrock stays off this list. Its command is `claude`,
+ // but the cached catalog is first-party ids, so a refresh would overwrite
+ // the Bedrock catalog and strand defaultModel. The card keeps the stored list.
+ 'claude-ollama', 'claude-ollama-tui',
'claude-sglang', 'claude-sglang-tui', 'codex', 'codex-lmstudio',
'codex-ollama', 'codex-tui',
'cursor-cli',
diff --git a/server/lib/aiToolkit/internal/claudeCodeCatalog.js b/server/lib/aiToolkit/internal/claudeCodeCatalog.js
new file mode 100644
index 0000000000..748466d185
--- /dev/null
+++ b/server/lib/aiToolkit/internal/claudeCodeCatalog.js
@@ -0,0 +1,189 @@
+/**
+ * Read the model catalog Claude Code itself caches, so a `claude` provider's
+ * **Refresh Models** stops re-serving a hand-maintained list.
+ *
+ * Unlike every other vendor here, the `claude` binary ships NO `models`
+ * subcommand — `claude --help` has `--model <model>` and nothing that prints
+ * the catalog, and an unknown id is rejected with prose ("isn't described by
+ * this version's model catalog"), not an enumeration. So there is no
+ * `_execCliModelList` probe to write.
+ *
+ * What the binary DOES do is fetch the picker catalog for this account from
+ * `/api/model_selector/<surface>` (claude.ai OAuth) and cache the response at
+ * `<configDir>/cache/model-catalog/<key>.json`. That file is the authoritative
+ * answer to the question the provider card is actually asking — which models
+ * THIS user's plan and THIS installed CLI version can select — and reading it
+ * costs no network call, no API key, and no child process. The endpoint itself
+ * is internal and unversioned; the cache file carries its own `version` and is
+ * gated on it below, so a shape change reads as "no catalog" rather than as a
+ * silently wrong list.
+ *
+ * NOT a substitute for the first-party Models API (`GET /v1/models`): that one
+ * is documented and stable but needs an `ANTHROPIC_API_KEY`, which a
+ * subscription-auth CLI provider does not have. A `type: 'api'` Anthropic
+ * record with a key still goes through `_refreshAPIProviderModels`.
+ *
+ * Pure by design (the fs read lives in `providers.js` with the rest of this
+ * directory's I/O) and self-contained — no imports out to other PortOS modules,
+ * see ../AGENTS.md.
+ */
+
+/** The surface id Claude Code fetches its own picker catalog under. */
+export const CLAUDE_CODE_SURFACE = 'cc';
+
+/** `<configDir>/cache/model-catalog` — the directory the CLI writes into. */
+export const CLAUDE_CATALOG_SUBPATH = Object.freeze(['cache', 'model-catalog']);
+
+/**
+ * The config directory the installed CLI reads, honoring the same
+ * `CLAUDE_CONFIG_DIR` override the binary does. Returns `null` when neither a
+ * override nor a home directory is known, so the caller skips the read rather
+ * than probing `/undefined/.claude`.
+ */
+export function claudeConfigDir(env = {}, home = '') {
+ const override = typeof env.CLAUDE_CONFIG_DIR === 'string' ? env.CLAUDE_CONFIG_DIR.trim() : '';
+ if (override) return override;
+ return home ? `${home}/.claude` : null;
+}
+
+/**
+ * Compare two dotted version strings numerically, the way the CLI's own
+ * `min_claude_code_version` gate does. Returns true when `version` is at least
+ * `minimum`. A missing or unparseable `minimum` means "no floor" — the catalog
+ * omits the key for models every supported version can select.
+ */
+export function versionAtLeast(version, minimum) {
+ if (!minimum) return true;
+ const parts = (value) => String(value || '').split('.').map((part) => Number.parseInt(part, 10));
+ const have = parts(version);
+ const need = parts(minimum);
+ // An unreadable INSTALLED version must not hide models. The floor exists to
+ // stop offering an id the binary would reject; with no version to compare we
+ // cannot answer that, and dropping the whole catalog is the worse error.
+ if (!Number.isFinite(have[0])) return true;
+ for (let i = 0; i < Math.max(have.length, need.length); i += 1) {
+ const a = Number.isFinite(have[i]) ? have[i] : 0;
+ const b = Number.isFinite(need[i]) ? need[i] : 0;
+ if (a !== b) return a > b;
+ }
+ return true;
+}
+
+/**
+ * Whether a parsed cache file is a Claude Code catalog this module understands.
+ * `version` is the file's OWN schema marker (2 at time of writing) — gate on it
+ * so a future rewrite degrades to "no catalog found" instead of feeding a
+ * changed shape through the accessors below.
+ */
+const SUPPORTED_CACHE_VERSIONS = Object.freeze([2]);
+
+export function isSupportedCatalog(parsed, surface = CLAUDE_CODE_SURFACE) {
+ return Boolean(
+ parsed
+ && typeof parsed === 'object'
+ && SUPPORTED_CACHE_VERSIONS.includes(parsed.version)
+ && parsed.catalog?.surface === surface
+ && Array.isArray(parsed.catalog?.config?.models),
+ );
+}
+
+/**
+ * The one entry both accessors below answer from: the freshest cache file that
+ * parses as a catalog for `surface`. Shared rather than restated, because
+ * `catalogAge` reports the age OF the entry `selectCatalogModels` read — two
+ * copies of this filter-and-sort could drift and make the logged timestamp
+ * describe a different file than the ids.
+ */
+function freshestCatalog(entries, surface) {
+ return (Array.isArray(entries) ? entries : [])
+ .filter((entry) => isSupportedCatalog(entry, surface))
+ .sort((a, b) => (Number(b.fetchedAt) || 0) - (Number(a.fetchedAt) || 0))[0] || null;
+}
+
+/**
+ * Pick the model ids out of the cache files the caller read.
+ *
+ * `entries` is every parsed `<configDir>/cache/model-catalog/*.json`. There can
+ * legitimately be several — one per account the user has signed in as, and one
+ * per surface — so the FRESHEST supported `cc` entry wins rather than the first
+ * one `readdir` happened to return. `fetchedAt` is the CLI's own stamp.
+ *
+ * Returns `[]` when nothing usable was found; the caller decides whether that
+ * is an error (it is — see `_fetchAnthropicModels`) so this stays pure.
+ *
+ * Ordering is the catalog's own, which is the picker's order: `main` models
+ * first, then `overflow`. That makes the provider card's first option the same
+ * model `claude` would default to, so a refresh does not silently re-point a
+ * record at a retired id.
+ */
+export function selectCatalogModels(entries, {
+ cliVersion = '',
+ surface = CLAUDE_CODE_SURFACE,
+ applyVersionFloor = true,
+} = {}) {
+ const freshest = freshestCatalog(entries, surface);
+ if (!freshest) return [];
+
+ const ids = freshest.catalog.config.models
+ .filter((model) => model && typeof model.id === 'string' && model.id)
+ // A model the INSTALLED binary is too old to select would be persisted into
+ // the record's picker and then rejected at spawn time with the CLI's own
+ // "isn't described by this version's model catalog" prose. The catalog
+ // declares that floor per model; honor it. Callers that need to tell "the
+ // cache has ids" from "this binary can select none of them" pass
+ // `applyVersionFloor: false`.
+ .filter((model) => !applyVersionFloor || versionAtLeast(cliVersion, model.min_claude_code_version))
+ .map((model) => model.id);
+
+ return [...new Set(ids)];
+}
+
+/**
+ * How stale the chosen catalog is, for the caller's log line. The CLI refreshes
+ * on its own schedule whenever a session runs; PortOS never writes this file.
+ */
+export function catalogAge(entries, { surface = CLAUDE_CODE_SURFACE } = {}) {
+ const freshest = freshestCatalog(entries, surface);
+ return freshest ? Number(freshest.fetchedAt) || null : null;
+}
+
+/**
+ * Env markers that point the `claude` binary at a third-party backend instead
+ * of the first-party subscription/API endpoint. Taken from the binary's own
+ * `CLAUDE_CODE_USE_*` set; `ANTHROPIC_AWS` / `ANTHROPIC_GOOGLE_CLOUD` are the
+ * Claude-Platform variants of the same choice.
+ *
+ * Such a record's models are namespaced by its backend
+ * (`global.anthropic.claude-opus-5`, `claude-opus-4-5@20251101`), and the
+ * catalog this module reads holds only first-party ids — the CLI never fetches
+ * the picker catalog when it is not talking to claude.ai. Answering a refresh
+ * with the first-party list would overwrite a Bedrock record's real ids with
+ * ones its endpoint rejects, and strand its own `defaultModel` outside its
+ * model list. So these records resolve to NO fetcher: the card offers no
+ * Refresh button and its stored catalog stands. See PortOS issue #8034.
+ */
+const THIRD_PARTY_BACKEND_VARS = Object.freeze([
+ 'CLAUDE_CODE_USE_BEDROCK',
+ 'CLAUDE_CODE_USE_VERTEX',
+ 'CLAUDE_CODE_USE_FOUNDRY',
+ 'CLAUDE_CODE_USE_MANTLE',
+ 'CLAUDE_CODE_USE_ANTHROPIC_AWS',
+ 'CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD',
+]);
+
+/**
+ * Truthy the way the CLI reads these: any set, non-empty value other than the
+ * explicit off-switches. `"0"` / `"false"` are how an install disables a marker
+ * it inherited, and must not count as "pointed at Bedrock".
+ */
+const envFlagEnabled = (value) => {
+ if (value === undefined || value === null) return false;
+ const normalized = String(value).trim().toLowerCase();
+ return normalized !== '' && normalized !== '0' && normalized !== 'false';
+};
+
+export function usesThirdPartyBackend(provider) {
+ const envVars = provider?.envVars;
+ if (!envVars || typeof envVars !== 'object') return false;
+ return THIRD_PARTY_BACKEND_VARS.some((name) => envFlagEnabled(envVars[name]));
+}
diff --git a/server/lib/aiToolkit/internal/claudeCodeCatalog.test.js b/server/lib/aiToolkit/internal/claudeCodeCatalog.test.js
new file mode 100644
index 0000000000..2e48e4e451
--- /dev/null
+++ b/server/lib/aiToolkit/internal/claudeCodeCatalog.test.js
@@ -0,0 +1,184 @@
+import { describe, expect, it } from 'vitest';
+import {
+ CLAUDE_CODE_SURFACE,
+ catalogAge,
+ claudeConfigDir,
+ isSupportedCatalog,
+ selectCatalogModels,
+ usesThirdPartyBackend,
+ versionAtLeast,
+} from './claudeCodeCatalog.js';
+
+/**
+ * Shape transcribed from a real `<configDir>/cache/model-catalog/*.json`
+ * (schema `version: 2`) with invented model ids — the file carries the signed-in
+ * account's entitlements, which never belong in a fixture.
+ */
+const catalogFile = ({ fetchedAt = 1_000, surface = CLAUDE_CODE_SURFACE, models = [], version = 2 } = {}) => ({
+ version,
+ fetchedAt,
+ staleAt: fetchedAt + 3_600_000,
+ catalog: { surface, config: { id: surface, models }, state: {} },
+});
+
+const model = (id, extra = {}) => ({ id, name: id, section: 'main', ...extra });
+
+describe('claudeConfigDir', () => {
+ it('prefers CLAUDE_CONFIG_DIR over the home default, matching the CLI', () => {
+ expect(claudeConfigDir({ CLAUDE_CONFIG_DIR: '/opt/cc' }, '/home/example')).toBe('/opt/cc');
+ });
+
+ it('falls back to <home>/.claude', () => {
+ expect(claudeConfigDir({}, '/home/example')).toBe('/home/example/.claude');
+ });
+
+ // The caller must skip the read rather than probe a path built from
+ // `undefined` — an ENOENT there reads as "no catalog cached" and would hide a
+ // genuinely broken environment behind the same message.
+ it('answers null when neither an override nor a home directory is known', () => {
+ expect(claudeConfigDir({ CLAUDE_CONFIG_DIR: ' ' }, '')).toBeNull();
+ });
+});
+
+describe('versionAtLeast', () => {
+ it.each([
+ ['2.1.280', '2.1.280', true],
+ ['2.1.281', '2.1.280', true],
+ ['2.1.279', '2.1.280', false],
+ ['2.2.0', '2.1.999', true],
+ ['10.0.0', '9.9.9', true],
+ ])('%s vs floor %s → %s', (have, need, expected) => {
+ expect(versionAtLeast(have, need)).toBe(expected);
+ });
+
+ it('treats a missing floor as no constraint', () => {
+ expect(versionAtLeast('2.1.0', undefined)).toBe(true);
+ });
+
+ // A failed `claude --version` probe must widen the catalog, never empty it:
+ // hiding every model is a worse error than offering one the binary rejects
+ // with a legible message.
+ it('treats an unreadable installed version as no constraint', () => {
+ expect(versionAtLeast('', '2.1.280')).toBe(true);
+ });
+});
+
+describe('isSupportedCatalog', () => {
+ it('accepts the shipped schema version for the cc surface', () => {
+ expect(isSupportedCatalog(catalogFile({ models: [model('a')] }))).toBe(true);
+ });
+
+ // The endpoint behind this file is internal and unversioned. Gating on the
+ // file's own marker makes a future rewrite read as "no catalog" — which the
+ // caller surfaces as an error that preserves the stored list — instead of
+ // feeding a changed shape through the accessors.
+ it.each([
+ ['an unknown schema version', catalogFile({ version: 3, models: [model('a')] })],
+ ['a different surface', catalogFile({ surface: 'web', models: [model('a')] })],
+ ['a non-array models field', { version: 2, catalog: { surface: 'cc', config: { models: {} } } }],
+ ['a null payload', null],
+ ])('rejects %s', (_label, parsed) => {
+ expect(isSupportedCatalog(parsed)).toBe(false);
+ });
+});
+
+describe('selectCatalogModels', () => {
+ it('returns the catalog ids in picker order', () => {
+ const entries = [catalogFile({
+ models: [model('alpha-3'), model('alpha-2'), model('alpha-1', { section: 'overflow' })],
+ })];
+ expect(selectCatalogModels(entries)).toEqual(['alpha-3', 'alpha-2', 'alpha-1']);
+ });
+
+ // The directory holds one file per signed-in account. Picking whichever
+ // `readdir` returned first would make the answer depend on filesystem order.
+ it('picks the freshest supported entry when several accounts are cached', () => {
+ const entries = [
+ catalogFile({ fetchedAt: 500, models: [model('stale-1')] }),
+ catalogFile({ fetchedAt: 9_000, models: [model('fresh-1')] }),
+ ];
+ expect(selectCatalogModels(entries)).toEqual(['fresh-1']);
+ });
+
+ it('drops models the installed CLI is too old to select', () => {
+ const entries = [catalogFile({
+ models: [
+ model('needs-new', { min_claude_code_version: '2.1.280' }),
+ model('always-ok'),
+ ],
+ })];
+ expect(selectCatalogModels(entries, { cliVersion: '2.1.200' })).toEqual(['always-ok']);
+ expect(selectCatalogModels(entries, { cliVersion: '2.1.280' })).toEqual(['needs-new', 'always-ok']);
+ });
+
+ it('skips entries whose schema it does not understand', () => {
+ const entries = [
+ catalogFile({ fetchedAt: 9_000, version: 3, models: [model('unreadable')] }),
+ catalogFile({ fetchedAt: 100, models: [model('readable')] }),
+ ];
+ expect(selectCatalogModels(entries)).toEqual(['readable']);
+ });
+
+ it.each([
+ ['no entries', []],
+ ['only unsupported entries', [catalogFile({ version: 99, models: [model('x')] })]],
+ ['a supported entry with no ids', [catalogFile({ models: [{ name: 'no id' }] })]],
+ ])('answers an empty list for %s so the caller can throw', (_label, entries) => {
+ expect(selectCatalogModels(entries)).toEqual([]);
+ });
+
+ it('de-duplicates ids repeated across sections', () => {
+ const entries = [catalogFile({ models: [model('dupe'), model('dupe', { section: 'overflow' })] })];
+ expect(selectCatalogModels(entries)).toEqual(['dupe']);
+ });
+});
+
+describe('catalogAge', () => {
+ it('reports the chosen entry’s fetch stamp', () => {
+ const entries = [catalogFile({ fetchedAt: 42 }), catalogFile({ fetchedAt: 4_242 })];
+ expect(catalogAge(entries)).toBe(4_242);
+ });
+
+ it('answers null when nothing usable is cached', () => {
+ expect(catalogAge([])).toBeNull();
+ });
+
+ // The two accessors must answer from the SAME entry: the log line reports the
+ // age of the catalog whose ids were persisted. When they each filtered and
+ // sorted separately the pair could drift and describe different files, so the
+ // shared selector is pinned here rather than only in each accessor's own test.
+ it('reports the age of the very entry whose ids were selected', () => {
+ const entries = [
+ catalogFile({ fetchedAt: 100, models: [model('from-older')] }),
+ catalogFile({ fetchedAt: 9_000, models: [model('from-newer')] }),
+ // Newest of all, but an unsupported schema — neither accessor may pick it.
+ catalogFile({ fetchedAt: 50_000, version: 3, models: [model('from-unreadable')] }),
+ ];
+ expect(selectCatalogModels(entries)).toEqual(['from-newer']);
+ expect(catalogAge(entries)).toBe(9_000);
+ });
+});
+
+describe('usesThirdPartyBackend', () => {
+ it.each([
+ ['Bedrock', { CLAUDE_CODE_USE_BEDROCK: '1' }],
+ ['Vertex', { CLAUDE_CODE_USE_VERTEX: 'true' }],
+ ['Foundry', { CLAUDE_CODE_USE_FOUNDRY: 'yes' }],
+ ['Claude Platform on AWS', { CLAUDE_CODE_USE_ANTHROPIC_AWS: '1' }],
+ ])('recognizes a record pointed at %s', (_label, envVars) => {
+ expect(usesThirdPartyBackend({ command: 'claude', envVars })).toBe(true);
+ });
+
+ // `"0"` / `"false"` is how an install disables a marker it inherited from a
+ // shared settings file. Reading those as "on" would hide the Refresh button
+ // from a record that is in fact talking to claude.ai.
+ it.each([
+ ['0', { CLAUDE_CODE_USE_BEDROCK: '0' }],
+ ['false', { CLAUDE_CODE_USE_BEDROCK: 'false' }],
+ ['an empty string', { CLAUDE_CODE_USE_BEDROCK: '' }],
+ ['no markers at all', { ANTHROPIC_MODEL: 'claude-opus-5' }],
+ ['no envVars', undefined],
+ ])('treats %s as first-party', (_label, envVars) => {
+ expect(usesThirdPartyBackend({ command: 'claude', envVars })).toBe(false);
+ });
+});
diff --git a/server/lib/aiToolkit/internal/modelFetchers.js b/server/lib/aiToolkit/internal/modelFetchers.js
index a69fceec3f..045bb44b9f 100644
--- a/server/lib/aiToolkit/internal/modelFetchers.js
+++ b/server/lib/aiToolkit/internal/modelFetchers.js
@@ -1,4 +1,5 @@
import { commandBasename } from './commandBasename.js';
+import { usesThirdPartyBackend } from './claudeCodeCatalog.js';
/**
* The single per-vendor table behind model refresh.
*
@@ -143,11 +144,13 @@ export const MODEL_FETCHERS = [
},
{
key: 'claude',
- // Raw-string equality, NOT a basename: `_fetchAnthropicModels` returns a
- // static list, so widening this to every binary named `claude` on disk is a
- // separate call from widening the vendors that probe their own CLI.
- cliMatch: (p) => p?.command === 'claude',
- cliNameMatch: (p) => displayName(p).includes('claude'),
+ // Raw-string equality, NOT a basename. `_fetchAnthropicModels` reads the
+ // catalog the INSTALLED Claude Code caches for the signed-in account, so a
+ // differently-named binary on disk would be answered for by whichever
+ // `claude` owns `~/.claude` — widening this is a separate call from
+ // widening the vendors that probe their own CLI.
+ cliMatch: (p) => p?.command === 'claude' && !usesThirdPartyBackend(p),
+ cliNameMatch: (p) => displayName(p).includes('claude') && !usesThirdPartyBackend(p),
fetch: '_fetchAnthropicModels',
},
{
diff --git a/server/lib/aiToolkit/internal/modelFetchers.test.js b/server/lib/aiToolkit/internal/modelFetchers.test.js
index 16880a8843..a7656d55b6 100644
--- a/server/lib/aiToolkit/internal/modelFetchers.test.js
+++ b/server/lib/aiToolkit/internal/modelFetchers.test.js
@@ -17,7 +17,7 @@ const SHIPPED = JSON.parse(readFileSync(resolve(__dirname, '../../../../data.ref
const SHIPPED_REFRESHABLE = [
'pi-cli', 'pi-tui',
'antigravity-cli', 'antigravity-tui', 'cerebras', 'claude-code',
- 'claude-code-bedrock', 'claude-ollama', 'claude-ollama-tui', 'cursor-cli',
+ 'claude-ollama', 'claude-ollama-tui', 'cursor-cli',
'cursor-tui', 'grok', 'lmstudio', 'mtplx', 'nvidia-nim', 'ollama',
'slotstream',
'opencode-llama-tui',
@@ -53,6 +53,15 @@ const SHIPPED_REFRESHABLE = [
];
const SHIPPED_NOT_REFRESHABLE = [
'claude-code-tui', 'claude-code-tui-bedrock',
+ // #8034 moved this one OUT of the refreshable set on purpose. It is
+ // `command: 'claude'` like the subscription record, so it matched the
+ // anthropic row and a refresh overwrote its `global.anthropic.*` /
+ // `us.anthropic.*` catalog with first-party ids its endpoint rejects —
+ // stranding its own `defaultModel` outside its model list. The catalog that
+ // row now reads (Claude Code's own cache) holds only first-party ids, so
+ // there is nothing correct to answer a Bedrock refresh with; the card offers
+ // no button and the stored catalog stands.
+ 'claude-code-bedrock',
'grok-cli', 'grok-tui', 'kimi-cli', 'kimi-tui',
'opencode-zen-cli', 'opencode-zen-tui',
// Kilo is an OpenCode fork and follows the same split as the Zen wrappers
@@ -361,3 +370,35 @@ describe('MODEL_FETCHERS shape', () => {
}
});
});
+
+describe('claude records pointed at a third-party backend', () => {
+ // #8034: `claude-code-bedrock` is `command: 'claude'` like every other Claude
+ // record, so it matched the anthropic row and a Refresh overwrote its
+ // `global.anthropic.*` / `us.anthropic.*` ids with first-party ones its
+ // endpoint rejects — stranding its own `defaultModel` outside its model list.
+ it('resolves to NO fetcher so the card offers no Refresh button', () => {
+ const bedrock = {
+ id: 'claude-code-bedrock',
+ type: 'cli',
+ command: 'claude',
+ name: 'Claude Code CLI: Bedrock',
+ envVars: { CLAUDE_CODE_USE_BEDROCK: '1' },
+ };
+ expect(resolveModelFetcher(bedrock)).toBeNull();
+ expect(canRefreshModels(bedrock)).toBe(false);
+ });
+
+ it('still resolves a first-party claude record to the anthropic fetcher', () => {
+ const subscription = { id: 'claude-code', type: 'cli', command: 'claude', name: 'Claude Code CLI' };
+ expect(resolveModelFetcher(subscription).fetch).toBe('_fetchAnthropicModels');
+ });
+
+ // The ollama row sits ABOVE the claude row and must keep winning: a `claude`
+ // binary pointed at a local daemon carries no CLAUDE_CODE_USE_* marker, so the
+ // new guard never sees it, but pinning the precedence here makes a future
+ // reorder fail loudly.
+ it('leaves an ollama-backed claude wrapper on the ollama fetcher', () => {
+ const wrapper = { id: 'claude-ollama', type: 'cli', command: 'claude', ollamaBacked: true };
+ expect(resolveModelFetcher(wrapper).fetch).toBe('_fetchOllamaToolCapableModels');
+ });
+});
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.js
index fb1d65580c..c9caacc947 100644
--- a/server/lib/aiToolkit/providers.js
+++ b/server/lib/aiToolkit/providers.js
@@ -1,6 +1,7 @@
import { composeBootstrapSpawn } from './internal/credentialBootstrap.js';
import { expandModePair, modeSiblingPayload, providerModeGroups, sharedModeUpdates, unifyProviderModes } from './internal/providerModes.js';
-import { readFile, rename } from 'fs/promises';
+import { readFile, readdir, rename } from 'fs/promises';
+import { homedir } from 'os';
import { existsSync } from 'fs';
import { join, dirname, delimiter, isAbsolute } from 'path';
import { atomicWrite } from './internal/atomicWrite.js';
@@ -28,6 +29,12 @@ import { canRefreshModels, ollamaRefreshGroupKey, resolveModelFetcher } from './
import { modelCatalogUpdate, modelContextWindowPatch, parseModelCatalog, toModelCatalog } from './internal/modelCatalog.js';
import { normalizeModelAccess } from './internal/modelAccess.js';
import { isCompositeProviderId } from './internal/providerRef.js';
+import {
+ CLAUDE_CATALOG_SUBPATH,
+ catalogAge,
+ claudeConfigDir,
+ selectCatalogModels,
+} from './internal/claudeCodeCatalog.js';
// Re-exported (rather than defined here) so the model-fetcher table can key its
// ollama row on the same predicate without importing back into this module.
@@ -1879,24 +1886,90 @@ export function createProviderService(config = {}) {
return checked.filter(Boolean);
},
- async _fetchAnthropicModels(_provider) {
- return [
- 'claude-opus-5',
- 'claude-opus-4-8',
- 'claude-opus-4-7',
- 'claude-sonnet-5',
- 'claude-sonnet-4-6',
- 'claude-opus-4-5-20251101',
- 'claude-sonnet-4-5-20250929',
- 'claude-sonnet-4-20250514',
- 'claude-haiku-4-5-20251001',
- 'claude-3-5-haiku-latest',
- 'claude-3-5-sonnet-20241022',
- 'claude-3-5-sonnet-20240620',
- 'claude-3-opus-20240229',
- 'claude-3-sonnet-20240229',
- 'claude-3-haiku-20240307'
- ];
+ /**
+ * Read the model catalog the installed Claude Code caches for THIS account.
+ *
+ * Every other vendor in the fetcher table answers a `models` subcommand;
+ * `claude` ships none, so this reads the file the binary writes instead —
+ * `<configDir>/cache/model-catalog/*.json`, refreshed by the CLI whenever a
+ * session runs. See internal/claudeCodeCatalog.js for why that file and not
+ * `/v1/models` (which needs an API key a subscription record does not have).
+ *
+ * THROWS rather than falling back to a hardcoded list, the same posture
+ * `_execCliModelList` documents: `refreshProviderModels` persists whatever
+ * comes back and the card toasts "Models refreshed", so degrading to a
+ * static list would silently re-stamp the stale answer the user clicked
+ * Refresh to escape. Throwing leaves the stored catalog untouched and puts
+ * the real cause — "run `claude` once so it caches its catalog" — in the
+ * toast. The shipped `data.reference/providers.json` list remains the SEED
+ * for a fresh install, exactly as the antigravity catalog is.
+ */
+ async _fetchAnthropicModels(provider) {
+ const env = { ...process.env, ...provider?.envVars };
+ const configDir = claudeConfigDir(env, homedir());
+ if (!configDir) throw new Error('Cannot locate the Claude Code config directory (no HOME and no CLAUDE_CONFIG_DIR)');
+ const catalogDir = join(configDir, ...CLAUDE_CATALOG_SUBPATH);
+
+ const files = await readdir(catalogDir).catch(() => null);
+ if (!files) {
+ throw new Error(`Claude Code has not cached a model catalog yet (${catalogDir} is missing) — run \`claude\` once, then refresh`);
+ }
+
+ const entries = (await Promise.all(
+ files.filter((name) => name.endsWith('.json')).map(async (name) => {
+ const raw = await readFile(join(catalogDir, name), 'utf8').catch(() => null);
+ if (raw === null) return null;
+ try {
+ return JSON.parse(raw);
+ } catch {
+ // One unreadable file must not lose a sibling that parses — the
+ // directory holds one entry per signed-in account.
+ return null;
+ }
+ }),
+ )).filter(Boolean);
+
+ const cliVersion = await this._claudeCliVersion(provider);
+ const models = selectCatalogModels(entries, { cliVersion });
+ if (models.length === 0) {
+ // A cache full of ids this binary's floor rejects is a different
+ // problem from an empty or unreadable cache. "Run claude once" does
+ // not help the first one — the file is already there.
+ const present = selectCatalogModels(entries, { applyVersionFloor: false });
+ if (present.length > 0) {
+ throw new Error(`Claude Code ${cliVersion || 'unknown'} cannot select any model in the cached catalog — upgrade \`claude\`, then refresh`);
+ }
+ throw new Error(`No usable Claude Code model catalog in ${catalogDir} — run \`claude\` once, then refresh`);
+ }
+
+ const age = catalogAge(entries);
+ // An out-of-range `fetchedAt` must not fail a refresh that already
+ // selected ids. `Date#toISOString` throws on those, and this log runs
+ // before the list is returned.
+ const stamp = age ? new Date(age) : null;
+ const cached = stamp && !Number.isNaN(stamp.getTime()) ? stamp.toISOString() : 'unknown';
+ console.log(`📋 Claude Code catalog: ${models.length} models (cached ${cached})`);
+ return models;
+ },
+
+ /**
+ * The installed binary's version, used only to drop catalog entries whose
+ * `min_claude_code_version` this build cannot select. Best-effort: an
+ * unreadable version means "no floor" (see `versionAtLeast`), so a failed
+ * probe widens the list rather than emptying it.
+ */
+ async _claudeCliVersion(provider) {
+ const spawned = resolveProbeSpawn(provider, 'claude', ['--version']);
+ const { command, args } = prepareWindowsSafeSpawn(spawned.command, spawned.args);
+ const pending = execFileAsync(command, args, {
+ timeout: 10000,
+ env: { ...process.env, ...provider?.envVars },
+ });
+ // Same reason as `_execCliModelList`: an open stdin makes some CLIs wait
+ // out the whole timeout instead of printing `--version`.
+ pending.child?.stdin?.end();
+ const { stdout } = await pending.catch(() => ({ stdout: '' }));
+ return (/(\d+\.\d+\.\d+)/.exec(stdout || '') || [])[1] || '';
},
async _fetchGeminiModels(provider) {
diff --git a/server/lib/aiToolkit/providers.test.js b/server/lib/aiToolkit/providers.test.js
index b85b21fb5e..3bec3c1760 100644
--- a/server/lib/aiToolkit/providers.test.js
+++ b/server/lib/aiToolkit/providers.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
-import { chmod, mkdtemp, rm, writeFile } from 'fs/promises';
+import { chmod, mkdir, mkdtemp, rm, writeFile } from 'fs/promises';
import { tmpdir } from 'os';
import { delimiter, join } from 'path';
import { createProviderService, isOllamaBackedProvider } from './providers.js';
@@ -1500,8 +1500,8 @@ describe('Provider Service', () => {
errSpy.mockRestore();
// Reached the AGY fetcher (which then failed on the bogus path) rather
- // than _fetchAnthropicModels, which would have succeeded and persisted
- // claude ids onto an agy provider.
+ // than _fetchAnthropicModels, which would have persisted the cached
+ // Claude catalog onto an agy provider.
expect(err.message).toMatch(/agy models' failed/);
const after = await providerService.getProviderById('antigravity-cli');
expect(after.models).toEqual(stored);
@@ -1510,17 +1510,96 @@ describe('Provider Service', () => {
// The name test still applies once no command has claimed the provider, and
// a `claude` command still beats an "antigravity" name — the split must not
- // invert that.
- it('still routes a claude-commanded provider named "antigravity" to Anthropic', async () => {
+ // invert that. The catalog is a fixture: the old assertion read this
+ // machine's `~/.claude` cache and required `claude-opus-5`, so a CI runner
+ // with no Claude install failed the refresh instead of proving the route.
+ const writeClaudeCatalog = async (models, fetchedAt = 1_700_000_000_000) => {
+ const configDir = join(TEST_DATA_DIR, 'claude-config');
+ const catalogDir = join(configDir, 'cache', 'model-catalog');
+ await mkdir(catalogDir, { recursive: true });
+ await writeFile(join(catalogDir, 'account.json'), JSON.stringify({
+ version: 2,
+ fetchedAt,
+ catalog: { surface: 'cc', config: { id: 'cc', models }, state: {} },
+ }));
+ return configDir;
+ };
+
+ const writeFakeClaude = async (versionLine) => {
+ const binDir = join(TEST_DATA_DIR, 'bin');
+ await mkdir(binDir, { recursive: true });
+ const command = join(binDir, 'claude');
+ await writeFile(command, `#!/bin/sh\nprintf '%s\\n' '${versionLine}'\n`);
+ await chmod(command, 0o755);
+ return binDir;
+ };
+
+ const claudeEnv = (configDir, binDir) => ({
+ CLAUDE_CONFIG_DIR: configDir,
+ PATH: `${binDir}${delimiter}${process.env.PATH || ''}`,
+ });
+
+ it.skipIf(process.platform === 'win32')('refreshes a claude-commanded provider from the cached catalog, not the antigravity sentinel', async () => {
+ const configDir = await writeClaudeCatalog([
+ { id: 'fixture-alpha', name: 'fixture-alpha', section: 'main' },
+ { id: 'fixture-beta', name: 'fixture-beta', section: 'main' },
+ ]);
+ const binDir = await writeFakeClaude('2.1.280 (Claude Code)');
const p = await providerService.createProvider({
- name: 'Claude via Antigravity', type: 'cli', command: 'claude', models: ['x'],
+ name: 'Claude via Antigravity',
+ type: 'cli',
+ command: 'claude',
+ models: ['x'],
+ envVars: claudeEnv(configDir, binDir),
});
+
const updated = await providerService.refreshProviderModels(p.id);
expect(updated).not.toBeNull();
- expect(updated.models).toContain('claude-opus-5');
+ expect(updated.models).toEqual(['fixture-alpha', 'fixture-beta']);
expect(updated.models).not.toContain('antigravity-configured-default');
});
+ it('leaves the stored list when Claude Code has no cached catalog', async () => {
+ const p = await providerService.createProvider({
+ name: 'Claude via Antigravity',
+ type: 'cli',
+ command: 'claude',
+ models: ['x'],
+ envVars: { CLAUDE_CONFIG_DIR: join(TEST_DATA_DIR, 'empty-claude-config') },
+ });
+
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const err = await providerService.refreshProviderModels(p.id).catch(e => e);
+ errSpy.mockRestore();
+
+ expect(err).toBeInstanceOf(Error);
+ expect(err.message).toMatch(/has not cached a model catalog/);
+ expect(err.status).toBe(502);
+ expect((await providerService.getProviderById(p.id)).models).toEqual(['x']);
+ });
+
+ it.skipIf(process.platform === 'win32')('tells the user to upgrade when every cached model needs a newer CLI', async () => {
+ const configDir = await writeClaudeCatalog([
+ { id: 'needs-new', name: 'needs-new', section: 'main', min_claude_code_version: '9.0.0' },
+ ]);
+ const binDir = await writeFakeClaude('2.0.0 (Claude Code)');
+ const p = await providerService.createProvider({
+ name: 'Claude Code CLI',
+ type: 'cli',
+ command: 'claude',
+ models: ['kept'],
+ envVars: claudeEnv(configDir, binDir),
+ });
+
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const err = await providerService.refreshProviderModels(p.id).catch(e => e);
+ errSpy.mockRestore();
+
+ expect(err.message).toMatch(/upgrade `claude`/);
+ expect(err.status).toBe(502);
+ expect((await providerService.getProviderById(p.id)).models).toEqual(['kept']);
+ });
+
// …and the residual NAME half of that same split is pinned too. Left
// unpinned, a future cleanup deletes it as apparently-redundant while the
// client's mirrored `name.includes('antigravity')` keeps offering the