Skip to content

Commit 2aa3e9e

Browse files
fix(cli): fall back to built-in models.dev catalog when fetch fails
When the remote models.dev catalog cannot be fetched, fall back to the built-in catalog so CLI/TUI model selection keeps working offline or under network failure. Import the shared helper via the #/utils alias.
1 parent f1a3475 commit 2aa3e9e

6 files changed

Lines changed: 177 additions & 5 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@moonshot-ai/kimi-code": patch
3+
---
4+
5+
Fall back to the built-in models.dev catalog snapshot when the public catalog is unreachable, so Known third-party provider import still works offline or in blocked networks.

‎apps/kimi-code/src/cli/sub/provider.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ import {
2525
CatalogFetchError,
2626
createKimiHarness,
2727
DEFAULT_CATALOG_URL,
28-
fetchCatalog,
2928
resolveCatalogImport,
3029
type Catalog,
3130
type CatalogProviderEntry,
@@ -35,6 +34,7 @@ import {
3534
import type { Command } from 'commander';
3635

3736
import { createKimiCodeHostIdentity, createKimiCodeUserAgent } from '#/cli/version';
37+
import { fetchCatalogOrBuiltIn } from '#/utils/catalog-fetch';
3838

3939
interface WritableLike {
4040
write(chunk: string): boolean;
@@ -434,7 +434,13 @@ export async function handleCatalogAdd(
434434

435435
async function loadCatalogOrExit(deps: ProviderDeps, url: string): Promise<Catalog> {
436436
try {
437-
return await fetchCatalog(url, { userAgent: createKimiCodeUserAgent() });
437+
const loaded = await fetchCatalogOrBuiltIn(url, { userAgent: createKimiCodeUserAgent() });
438+
if (loaded.fromBuiltIn) {
439+
deps.stderr.write(
440+
`Warning: failed to reach ${url}; using the built-in models.dev catalog snapshot.\n`,
441+
);
442+
}
443+
return loaded.catalog;
438444
} catch (error) {
439445
const suffix = error instanceof CatalogFetchError ? ` (HTTP ${String(error.status)})` : '';
440446
deps.stderr.write(`Failed to fetch catalog from ${url}${suffix}: ${errorMessage(error)}\n`);

‎apps/kimi-code/src/tui/commands/provider.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,13 @@ import {
99
catalogProviderModels,
1010
CatalogFetchError,
1111
DEFAULT_CATALOG_URL,
12-
fetchCatalog,
1312
resolveCatalogImport,
1413
type Catalog,
1514
type ThinkingEffort,
1615
} from '@moonshot-ai/kimi-code-sdk';
1716

1817
import { createKimiCodeUserAgent } from '#/cli/version';
18+
import { fetchCatalogOrBuiltIn } from '#/utils/catalog-fetch';
1919
import { ChoicePickerComponent } from '../components/dialogs/choice-picker';
2020
import {
2121
CustomRegistryImportDialogComponent,
@@ -162,11 +162,17 @@ async function handleCatalogProviderAdd(host: SlashCommandHost): Promise<void> {
162162
const spinner = host.showLoginProgressSpinner(`Fetching catalog from ${DEFAULT_CATALOG_URL}`);
163163
let catalog: Catalog | undefined;
164164
try {
165-
catalog = await fetchCatalog(DEFAULT_CATALOG_URL, {
165+
const loaded = await fetchCatalogOrBuiltIn(DEFAULT_CATALOG_URL, {
166166
signal: controller.signal,
167167
userAgent: createKimiCodeUserAgent(),
168168
});
169-
spinner.stop({ ok: true, label: 'Catalog loaded.' });
169+
catalog = loaded.catalog;
170+
spinner.stop({
171+
ok: true,
172+
label: loaded.fromBuiltIn
173+
? 'Catalog loaded from built-in snapshot (models.dev unreachable).'
174+
: 'Catalog loaded.',
175+
});
170176
} catch (error) {
171177
if (controller.signal.aborted) {
172178
spinner.stop({ ok: false, label: 'Aborted.' });
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import {
2+
DEFAULT_CATALOG_URL,
3+
fetchCatalog,
4+
loadBuiltInCatalog,
5+
type Catalog,
6+
type FetchCatalogOptions,
7+
} from '@moonshot-ai/kimi-code-sdk';
8+
9+
import { BUILT_IN_CATALOG_JSON } from '#/built-in-catalog';
10+
11+
export interface FetchCatalogOrBuiltInResult {
12+
readonly catalog: Catalog;
13+
/** True when the network fetch failed and the release-build snapshot was used. */
14+
readonly fromBuiltIn: boolean;
15+
}
16+
17+
export interface FetchCatalogOrBuiltInOptions extends FetchCatalogOptions {
18+
/**
19+
* Override the built-in snapshot JSON (tests). Defaults to the tsdown-injected
20+
* `__KIMI_CODE_BUILT_IN_CATALOG__` constant.
21+
*/
22+
readonly builtInJson?: string;
23+
}
24+
25+
/**
26+
* Fetches a models.dev-style catalog, falling back to the release-build
27+
* snapshot when the public default URL is unreachable.
28+
*
29+
* Custom `--url` overrides never fall back — a private registry must fail
30+
* loudly rather than silently substitute models.dev. User abort
31+
* (`signal.aborted`) also skips the fallback so Cancel stays Cancel.
32+
*/
33+
export async function fetchCatalogOrBuiltIn(
34+
url: string,
35+
options: FetchCatalogOrBuiltInOptions = {},
36+
): Promise<FetchCatalogOrBuiltInResult> {
37+
try {
38+
const catalog = await fetchCatalog(url, options);
39+
return { catalog, fromBuiltIn: false };
40+
} catch (error) {
41+
if (options.signal?.aborted) throw error;
42+
if (isAbortError(error)) throw error;
43+
if (url !== DEFAULT_CATALOG_URL) throw error;
44+
const builtIn = loadBuiltInCatalog(options.builtInJson ?? BUILT_IN_CATALOG_JSON);
45+
if (builtIn === undefined) throw error;
46+
return { catalog: builtIn, fromBuiltIn: true };
47+
}
48+
}
49+
50+
function isAbortError(error: unknown): boolean {
51+
return (
52+
(typeof DOMException !== 'undefined' &&
53+
error instanceof DOMException &&
54+
error.name === 'AbortError') ||
55+
(error instanceof Error && error.name === 'AbortError')
56+
);
57+
}
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import { DEFAULT_CATALOG_URL, CatalogFetchError } from '@moonshot-ai/kimi-code-sdk';
2+
import { describe, expect, it, vi } from 'vitest';
3+
4+
import { fetchCatalogOrBuiltIn } from '#/utils/catalog-fetch';
5+
6+
const BUILT_IN = JSON.stringify({
7+
anthropic: {
8+
id: 'anthropic',
9+
name: 'Anthropic',
10+
models: { 'claude-test': { id: 'claude-test', limit: { context: 200000 } } },
11+
},
12+
});
13+
14+
function jsonResponse(body: unknown, status = 200): Response {
15+
return new Response(JSON.stringify(body), {
16+
status,
17+
headers: { 'Content-Type': 'application/json' },
18+
});
19+
}
20+
21+
describe('fetchCatalogOrBuiltIn', () => {
22+
it('returns the network catalog when models.dev is reachable', async () => {
23+
const network = { openai: { id: 'openai', models: {} } };
24+
const fetchImpl = vi.fn(async () => jsonResponse(network));
25+
26+
const result = await fetchCatalogOrBuiltIn(DEFAULT_CATALOG_URL, {
27+
fetchImpl: fetchImpl as unknown as typeof fetch,
28+
builtInJson: BUILT_IN,
29+
});
30+
31+
expect(result.fromBuiltIn).toBe(false);
32+
expect(result.catalog).toEqual(network);
33+
});
34+
35+
it('falls back to the built-in snapshot when the default URL fetch fails', async () => {
36+
const fetchImpl = vi.fn(async () => jsonResponse('no', 503));
37+
38+
const result = await fetchCatalogOrBuiltIn(DEFAULT_CATALOG_URL, {
39+
fetchImpl: fetchImpl as unknown as typeof fetch,
40+
builtInJson: BUILT_IN,
41+
});
42+
43+
expect(result.fromBuiltIn).toBe(true);
44+
expect(result.catalog).toEqual(JSON.parse(BUILT_IN));
45+
});
46+
47+
it('does not fall back for a custom catalog URL', async () => {
48+
const fetchImpl = vi.fn(async () => jsonResponse('no', 500));
49+
50+
await expect(
51+
fetchCatalogOrBuiltIn('https://example.test/private.json', {
52+
fetchImpl: fetchImpl as unknown as typeof fetch,
53+
builtInJson: BUILT_IN,
54+
}),
55+
).rejects.toBeInstanceOf(CatalogFetchError);
56+
});
57+
58+
it('does not fall back when the caller aborted the request', async () => {
59+
const controller = new AbortController();
60+
controller.abort();
61+
const fetchImpl = vi.fn(async () => {
62+
throw new DOMException('Aborted', 'AbortError');
63+
});
64+
65+
await expect(
66+
fetchCatalogOrBuiltIn(DEFAULT_CATALOG_URL, {
67+
signal: controller.signal,
68+
fetchImpl: fetchImpl as unknown as typeof fetch,
69+
builtInJson: BUILT_IN,
70+
}),
71+
).rejects.toThrow();
72+
});
73+
74+
it('rethrows when fetch fails and no built-in snapshot is available', async () => {
75+
const fetchImpl = vi.fn(async () => jsonResponse('no', 500));
76+
77+
await expect(
78+
fetchCatalogOrBuiltIn(DEFAULT_CATALOG_URL, {
79+
fetchImpl: fetchImpl as unknown as typeof fetch,
80+
builtInJson: '',
81+
}),
82+
).rejects.toBeInstanceOf(CatalogFetchError);
83+
});
84+
});

‎packages/node-sdk/test/catalog.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
catalogProviderModels,
88
CatalogFetchError,
99
fetchCatalog,
10+
loadBuiltInCatalog,
1011
type CatalogModel,
1112
} from '../src/catalog';
1213

@@ -79,6 +80,19 @@ describe('fetchCatalog', () => {
7980
});
8081
});
8182

83+
describe('loadBuiltInCatalog', () => {
84+
it('parses a valid catalog JSON string', () => {
85+
const catalog = { anthropic: { id: 'anthropic', models: {} } };
86+
expect(loadBuiltInCatalog(JSON.stringify(catalog))).toEqual(catalog);
87+
});
88+
89+
it('returns undefined for missing or invalid input', () => {
90+
expect(loadBuiltInCatalog(undefined)).toBeUndefined();
91+
expect(loadBuiltInCatalog('')).toBeUndefined();
92+
expect(loadBuiltInCatalog('not-json')).toBeUndefined();
93+
});
94+
});
95+
8296
describe('catalogModelToAlias', () => {
8397
it('flattens a catalog model capability into alias fields', () => {
8498
expect(catalogModelToAlias('anthropic', model)).toEqual({

0 commit comments

Comments
 (0)