@@ -8,12 +8,11 @@ import {
88 replaceProviderModels,
99 setModelInfoState,
1010 } from "../session/db/model-info-repo.ts";
11-
12-const ZEN_BASE = "https://opencode.ai/zen/v1";
13-const OPENAI_BASE = "https://api.openai.com";
14-const ANTHROPIC_BASE = "https://api.anthropic.com";
15-const GOOGLE_BASE = "https://generativelanguage.googleapis.com/v1beta";
16-const MODELS_DEV_URL = "https://models.dev/api.json";
11+import {
12+ fetchModelsDevPayload,
13+ fetchProviderCandidates,
14+ type ProviderModelCandidate,
15+} from "./model-info-fetch.ts";
1716
1817 const MODELS_DEV_SYNC_KEY = "last_models_dev_sync_at";
1918 const PROVIDER_SYNC_KEY_PREFIX = "last_provider_sync_at:";
@@ -89,13 +88,6 @@ interface ModelsDevEntry {
8988 rawJson: string | null;
9089 }
9190
92-interface ProviderModelCandidate {
93- providerModelId: string;
94- displayName: string;
95- contextWindow: number | null;
96- free: boolean;
97-}
98-
9991 interface ParsedModelString {
10092 provider: string | null;
10193 modelId: string;
@@ -418,224 +410,6 @@ function getLastSyncAt(): number | null {
418410 return latest;
419411 }
420412
421-async function fetchJson(
422- url: string,
423- init: RequestInit,
424- timeoutMs: number,
425-): Promise<unknown | null> {
426- try {
427- const response = await fetch(url, {
428- ...init,
429- signal: AbortSignal.timeout(timeoutMs),
430- });
431- if (!response.ok) return null;
432- return (await response.json()) as unknown;
433- } catch {
434- return null;
435- }
436-}
437-
438-async function fetchModelsDevPayload(): Promise<unknown | null> {
439- return fetchJson(MODELS_DEV_URL, {}, 10_000);
440-}
441-
442-async function fetchZenModels(): Promise<ProviderModelCandidate[] | null> {
443- const key = process.env.OPENCODE_API_KEY;
444- if (!key) return null;
445- return fetchPaginatedModelsList(
446- `${ZEN_BASE}/models`,
447- { headers: { Authorization: `Bearer ${key}` } },
448- 8_000,
449- "data",
450- "id",
451- (item, modelId) => {
452- const contextWindow =
453- typeof item.context_window === "number" &&
454- Number.isFinite(item.context_window)
455- ? Math.max(0, Math.trunc(item.context_window))
456- : null;
457- return {
458- providerModelId: modelId,
459- displayName: item.id as string,
460- contextWindow,
461- free:
462- (item.id as string).endsWith("-free") ||
463- item.id === "gpt-5-nano" ||
464- item.id === "big-pickle",
465- };
466- },
467- );
468-}
469-
470-function processModelsList(
471- payload: unknown,
472- arrayKey: string,
473- idKey: string,
474- mapper: (
475- item: Record<string, unknown>,
476- modelId: string,
477- ) => ProviderModelCandidate | null,
478-): ProviderModelCandidate[] | null {
479- if (!isRecord(payload) || !Array.isArray(payload[arrayKey])) return null;
480- const out: ProviderModelCandidate[] = [];
481- for (const item of payload[arrayKey] as unknown[]) {
482- if (!isRecord(item) || typeof item[idKey] !== "string") continue;
483- const modelId = normalizeModelId(item[idKey] as string);
484- if (!modelId) continue;
485- const mapped = mapper(item as Record<string, unknown>, modelId);
486- if (mapped) out.push(mapped);
487- }
488- return out;
489-}
490-
491-async function fetchPaginatedModelsList(
492- url: string,
493- init: RequestInit,
494- timeoutMs: number,
495- arrayKey: string,
496- idKey: string,
497- mapper: (
498- item: Record<string, unknown>,
499- modelId: string,
500- ) => ProviderModelCandidate | null,
501-): Promise<ProviderModelCandidate[] | null> {
502- const out: ProviderModelCandidate[] = [];
503- const seen = new Set<string>();
504- const baseUrl = new URL(url);
505- let nextAfter: string | null = null;
506-
507- for (let page = 0; page < 10; page += 1) {
508- const currentUrl = new URL(baseUrl);
509- if (nextAfter !== null) currentUrl.searchParams.set("after", nextAfter);
510- const payload = await fetchJson(currentUrl.toString(), init, timeoutMs);
511- const rows = processModelsList(payload, arrayKey, idKey, mapper);
512- if (rows === null) {
513- return null;
514- }
515- for (const row of rows) {
516- if (seen.has(row.providerModelId)) continue;
517- seen.add(row.providerModelId);
518- out.push(row);
519- }
520- if (!isRecord(payload)) break;
521- if (payload.has_more !== true || typeof payload.last_id !== "string") break;
522- nextAfter = payload.last_id;
523- }
524-
525- return out;
526-}
527-
528-async function fetchOpenAIModels(): Promise<ProviderModelCandidate[] | null> {
529- const key = process.env.OPENAI_API_KEY;
530- if (!key) return null;
531- return fetchPaginatedModelsList(
532- `${OPENAI_BASE}/v1/models`,
533- { headers: { Authorization: `Bearer ${key}` } },
534- 6_000,
535- "data",
536- "id",
537- (item, modelId) => ({
538- providerModelId: modelId,
539- displayName: item.id as string,
540- contextWindow: null,
541- free: false,
542- }),
543- );
544-}
545-
546-async function fetchAnthropicModels(): Promise<
547- ProviderModelCandidate[] | null
548-> {
549- const key = process.env.ANTHROPIC_API_KEY;
550- if (!key) return null;
551- const payload = await fetchJson(
552- `${ANTHROPIC_BASE}/v1/models`,
553- {
554- headers: {
555- "x-api-key": key,
556- "anthropic-version": "2023-06-01",
557- },
558- },
559- 6_000,
560- );
561- return processModelsList(payload, "data", "id", (item, modelId) => {
562- const displayName =
563- typeof item.display_name === "string" &&
564- item.display_name.trim().length > 0
565- ? item.display_name
566- : (item.id as string);
567- return {
568- providerModelId: modelId,
569- displayName,
570- contextWindow: null,
571- free: false,
572- };
573- });
574-}
575-
576-async function fetchGoogleModels(): Promise<ProviderModelCandidate[] | null> {
577- const key = process.env.GOOGLE_API_KEY ?? process.env.GEMINI_API_KEY;
578- if (!key) return null;
579- const payload = await fetchJson(
580- `${GOOGLE_BASE}/models?key=${encodeURIComponent(key)}`,
581- {},
582- 6_000,
583- );
584- return processModelsList(payload, "models", "name", (item, modelId) => {
585- const displayName =
586- typeof item.displayName === "string" && item.displayName.trim().length > 0
587- ? item.displayName
588- : modelId;
589- const contextWindow =
590- typeof item.inputTokenLimit === "number" &&
591- Number.isFinite(item.inputTokenLimit)
592- ? Math.max(0, Math.trunc(item.inputTokenLimit))
593- : null;
594- return {
595- providerModelId: modelId,
596- displayName,
597- contextWindow,
598- free: false,
599- };
600- });
601-}
602-
603-async function fetchOllamaModels(): Promise<ProviderModelCandidate[] | null> {
604- const base = process.env.OLLAMA_BASE_URL ?? "http://localhost:11434";
605- const payload = await fetchJson(`${base}/api/tags`, {}, 3_000);
606- return processModelsList(payload, "models", "name", (item, modelId) => {
607- const details = item.details;
608- let sizeSuffix = "";
609- if (isRecord(details) && typeof details.parameter_size === "string") {
610- sizeSuffix = ` (${details.parameter_size})`;
611- }
612- return {
613- providerModelId: modelId,
614- displayName: `${item.name as string}${sizeSuffix}`,
615- contextWindow: null,
616- free: false,
617- };
618- });
619-}
620-
621-const PROVIDER_CANDIDATE_FETCHERS: Readonly<
622- Record<string, () => Promise<ProviderModelCandidate[] | null>>
623-> = {
624- zen: fetchZenModels,
625- openai: fetchOpenAIModels,
626- anthropic: fetchAnthropicModels,
627- google: fetchGoogleModels,
628- ollama: fetchOllamaModels,
629-};
630-
631-async function fetchProviderCandidates(
632- provider: string,
633-): Promise<ProviderModelCandidate[] | null> {
634- const fetcher = PROVIDER_CANDIDATE_FETCHERS[provider];
635- if (!fetcher) return null;
636- return fetcher();
637-}
638-
639413 function providerRowsFromCandidates(
640414 candidates: ProviderModelCandidate[],
641415 matchIndex: ModelMatchIndex,